feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
# Connected primary paint
|
||||
|
||||
The independent line detector decomposes connected foreground into measured thin
|
||||
branches in its existing contour traversal. An enclosing rectangle is not an
|
||||
object model for a parking U or intersecting paint. Opposite contour edges supply
|
||||
bounded alternatives (at most one preferred pair per edge), rather than a grid
|
||||
of guessed positions or a list of failed historical objects.
|
||||
|
||||
Original colour, road, visibility, vehicle and binary-ridge gates are unchanged.
|
||||
The original whole-component and Hough proposals remain. Branch width, length,
|
||||
aspect and binary occupancy have the original component limits; additional
|
||||
parallel-side constraints are proposal filters, not final acceptance. No new
|
||||
images, old map input, source-geometry repair or rescue pass is used.
|
||||
|
||||
The primary extractor has its own small entrypoint with exactly the qualified
|
||||
extraction body. The legacy module remains byte-identical because it belongs to
|
||||
the frozen arrow contract. A shared primitive (`observation`) is imported from it;
|
||||
legacy callers retain their previous behavior. Downstream observation ownership,
|
||||
measured candidate bank, joint selection and independent final admission apply
|
||||
to every new proposal. A new candidate is never itself counted as recovery.
|
||||
|
||||
Qualification includes synthetic connected U paint and negative controls, all
|
||||
50 real primary views, unchanged non-line channels and retention of every old
|
||||
primary proposal; a dependent suffix checks all downstream gates. Only a new
|
||||
complete run from PLY can supply full elapsed-time and final-map comparisons.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Initial acquisition: structural observers are invariant
|
||||
|
||||
Road boundaries and observed facades depend on the structural orthographic
|
||||
views as well as the side-looking cameras. Their depth/opacity mosaics, selected
|
||||
RGB pixels, occluder masks and world raster extent must not change as a side
|
||||
effect of optimizing ground-paint coverage.
|
||||
|
||||
`initial_views.choose` therefore retains every bootstrap structural camera and
|
||||
optimizes only supplemental views. `ortho_render` keeps the structural survey
|
||||
index, identities, bounds and order intact. Supplements are published in the
|
||||
separate initial coverage manifest; they participate in paint observation,
|
||||
never in the structural raster assembly. All cameras are planned before the
|
||||
first render; no detector result, previous map or missed-object list is input.
|
||||
|
||||
The solver retains the existing 27 m usable half-width, 1 m observed samples,
|
||||
two distinct views, 60 m render window and bounded 15 s solve. The original
|
||||
complete greedy plan is a feasible fallback. A returned optimization that
|
||||
removes a structural camera is rejected even if its ground coverage is complete.
|
||||
|
||||
Existing semantic observations are projected to supplemental paint views by
|
||||
`coverage_semantics.carry`; unknown vehicle footprints remain blocked. This
|
||||
is the pre-existing conservative support-view contract, not a new inference
|
||||
or relaxed admission rule. Native RGB/depth for every view is rendered fresh.
|
||||
|
||||
On the Mira fixture, the constrained plan has 42 structural plus 24 supplemental
|
||||
views (66 total); the former complete plan had 42 plus 32 (74 total). The
|
||||
unconstrained 50-view replacement changed structural evidence and is no longer
|
||||
used. These counts prove coverage and camera retention, not map accuracy.
|
||||
|
||||
Regression evidence must include a fresh-source run. Replaying saved pixels is
|
||||
useful for diagnosis; saved old map geometry is never an input to recovery.
|
||||
All geometry, visibility, protected-object, conservation and paint gates remain
|
||||
unchanged. Shared-edge assembly and the joint marking selector are unchanged.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Joint measured-marking assembly — implementation notes
|
||||
|
||||
The unit of search is an immutable observation from the current Gaussian scene.
|
||||
The unit of assembly is a complete admitted configuration (a finite line, a
|
||||
continuous observed window, a pair, or a measured periodic family). A control
|
||||
map is allowed only in evaluation and is never an input to discovery/selection.
|
||||
|
||||
1. Form physical components by the exact union of raw positive paint outlines.
|
||||
Choose one area-moment axis per component, with the former rectangle axis
|
||||
only when area moments cannot establish an elongated shape. Keep independent
|
||||
line proposals and current-run upstream axes. Generate local measured-body
|
||||
alternatives from shared profiles, not repeated image searches.
|
||||
2. Compute camera ownership in batches with exact boundary fallback. Reuse
|
||||
identical sample requests and identical fitted series; never merge nearby
|
||||
coordinates or reuse results after their input/code fingerprint changes.
|
||||
3. Compile proposed changes against one immutable fresh upstream map. Preserve
|
||||
the strip, dark-gap, endpoint, two-view, protected-symbol, removed-paint and
|
||||
source-conservation predicates. This phase does not mutate geometry.
|
||||
4. Select whole configurations jointly with explicit duplicate, overlap,
|
||||
family-domain, seam and source-ownership constraints. Count fixed physical
|
||||
evidence from both connected-paint and independent line-strip detectors
|
||||
once; object count is not a reward. A missing contour in one detector must
|
||||
not veto a measured line from the other. Each original fresh source is
|
||||
retained or replaced exactly once. A family is indivisible.
|
||||
5. Represent dense pairwise conflicts by an exact clique edge cover. Each
|
||||
clique contains only mutually conflicting nodes, and every original edge
|
||||
remains represented. This changes the matrix, not the feasible solutions.
|
||||
6. Bound optimization time and distinguish optimal, feasible-at-limit and
|
||||
current-run fallback. Never report fallback as optimal, nor old reference
|
||||
geometry as recovery. All final validators still execute.
|
||||
|
||||
Qualification uses original/expanded bank × greedy/joint on the same frozen
|
||||
observations, then a fresh full-chain run. Microbenchmarks and cached-tail
|
||||
runs are explicitly not full-chain timings. Historical matching figures are
|
||||
diagnostics relative to a previous algorithm, not street-ground-truth recall.
|
||||
|
||||
Status: expanded-bank full run completed in 48m22s and failed the speed goal.
|
||||
The compact primary plan requires its own fresh full-chain qualification. The first expanded solver representation exceeded its time budget
|
||||
and was rejected; its evidence is preserved under joint-assembly-20261018-03.
|
||||
|
||||
Measurement reuses decoded observations in a byte-bounded 1.5 GiB cache per
|
||||
worker (four workers maximum, 16 GiB container); no persistent cache is created.
|
||||
Native sample requests still require exact coordinate-bit identity.
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Keep each symbol's qualified measurement contract through final assembly.
|
||||
|
||||
Legacy fit_score is a .74 template-fit measure. The qualified XY arrows use
|
||||
original-pixel IoU plus independent visibility, shape and source-association
|
||||
checks. Their source-association score is not the legacy fit_score quantity.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import hashlib,json
|
||||
from final_symbol_admission import admit,existing_fit_floor
|
||||
|
||||
def run():
|
||||
out=Path('/out');primary=Path('/primaryarrows')
|
||||
raw=Path('/fullplan/full-map.json').read_bytes();doc=json.loads(raw)
|
||||
admitted=json.loads((primary/'full-map.json').read_text())
|
||||
verification=json.loads((primary/'verification.json').read_text())
|
||||
digest=hashlib.sha256((primary/'arrow-observations.json').read_bytes()).hexdigest()
|
||||
if not(verification['passed'] and verification['original_pixels_remeasured']
|
||||
and verification['source_result_sha256']==digest
|
||||
and admitted['primary_arrow_contract']['source_sha256']==digest):
|
||||
raise ValueError('Primary arrow verification is not bound to its source')
|
||||
verified_observations={r['id']for r in verification['checks']}
|
||||
arrows={f['id']:f for f in admitted['features'] if f['properties'].get('source_observation_id') in verified_observations}
|
||||
current={f['id']:f for f in doc['features']}
|
||||
if any(current.get(i)!=f for i,f in arrows.items()):raise ValueError('A verified arrow changed during assembly')
|
||||
if any(f['properties'].get('admission_contract') and f['id']not in arrows for f in doc['features']):
|
||||
raise ValueError('An unverified arrow contract entered the map')
|
||||
legacy={**doc,'features':[f for f in doc['features']if f['id']not in arrows]}
|
||||
policy=Path('/candidate/symbol_rules.py').read_text()
|
||||
accepted,report=admit(legacy,existing_fit_floor(policy));ids={f['id']for f in accepted['features']}|set(arrows)
|
||||
result={**accepted,'features':[f for f in doc['features']if f['id']in ids]}
|
||||
report.update(primary_arrows=len(arrows),primary_verification_sha256=hashlib.sha256((primary/'verification.json').read_bytes()).hexdigest(),
|
||||
original_input_sha256=hashlib.sha256(raw).hexdigest(),legacy_policy_unchanged=True,
|
||||
arrow_policy='qualified observed-xy-markings-v5; independent raw-pixel remeasurement')
|
||||
(out/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
||||
(out/'admission-report.json').write_text(json.dumps(report,indent=2,allow_nan=False))
|
||||
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Independently verify fresh arrows, then merge under existing conflict rules."""
|
||||
from pathlib import Path
|
||||
import hashlib,json,time
|
||||
import numpy as np,shapely
|
||||
from shapely.geometry import shape
|
||||
from shapely.ops import transform
|
||||
from verify_topdown import verify_result
|
||||
from component_conflicts import symbol_replacements
|
||||
from layer_common import feature,sample
|
||||
|
||||
def assemble(base,observations,height,low,high):
|
||||
if any(f['properties'].get('subtype','').endswith('_arrow')for f in base['features']):
|
||||
raise ValueError('Arrows must have one primary reconstruction owner')
|
||||
current={f['id']:f for f in base['features']};rows=[];rejected=[]
|
||||
for item in observations['features']:
|
||||
q=shape(item['geometry']);props=item['properties'];kind=props['subtype']
|
||||
replacements=symbol_replacements(q,kind,current.values())
|
||||
if replacements is None:
|
||||
rejected.append(dict(observation_id=item['id'],reason='existing-geometric-conflict'));continue
|
||||
lifted=transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),q)
|
||||
p={k:v for k,v in props.items()if k not in {'class','class_name'}}
|
||||
p.update(source_observation_id=item['id'],height_status='inherited-not-qualified')
|
||||
output=feature(lifted,'road_marking',**p)
|
||||
if not lifted.is_valid or not np.isfinite(shapely.get_coordinates(lifted,include_z=True)).all():
|
||||
raise ValueError('Invalid lifted arrow')
|
||||
for f in replacements:assert current.pop(f['id'])==f
|
||||
if output['id']in current:raise ValueError('Duplicate assembled arrow')
|
||||
current[output['id']]=output
|
||||
rows.append(dict(observation_id=item['id'],before=replacements,after=output))
|
||||
return {**base,'features':list(current.values())},rows,rejected
|
||||
|
||||
def main():
|
||||
started=time.monotonic();out=Path('/out')
|
||||
verify_result(result=out,symbols='/symbolplan',out=out)
|
||||
raw=Path('/fullplan/full-map.json').read_bytes();base=json.loads(raw)
|
||||
observations=json.loads((out/'arrow-observations.json').read_text())
|
||||
with np.load('/evidence_plan/fields.npz')as z:height=z['z'];low,high=z['bounds']
|
||||
result,rows,rejected=assemble(base,observations,height,low,high)
|
||||
result['primary_arrow_contract']=dict(verified=True,source_sha256=hashlib.sha256((out/'arrow-observations.json').read_bytes()).hexdigest(),
|
||||
freshly_reconstructed=len(rows),retained_prior_arrows=0,conflict_rejections=len(rejected))
|
||||
(out/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
||||
(out/'arrow-assembly-report.json').write_text(json.dumps(dict(baseline_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
transactions=rows,rejected=rejected,seconds=time.monotonic()-started,prior_geometry_input_to_search=False),indent=2,allow_nan=False))
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Lossless bounded NPZ writer; trade a little disk for less CPU compression."""
|
||||
import zipfile
|
||||
import numpy as np
|
||||
|
||||
|
||||
def save(path,**arrays):
|
||||
with zipfile.ZipFile(path,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=1,allowZip64=True)as archive:
|
||||
for name,value in arrays.items():
|
||||
if not name or '/'in name or '\\'in name:raise ValueError('Invalid array key')
|
||||
array=np.asanyarray(value)
|
||||
if array.dtype.hasobject:raise ValueError('Object arrays are not observation evidence')
|
||||
with archive.open(name+'.npy','w',force_zip64=True)as member:
|
||||
np.lib.format.write_array(member,array,allow_pickle=False)
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"qualified_session": "topdown-writer-queue-20261016101327",
|
||||
"fresh_confirmed": 20,
|
||||
"reference": 21,
|
||||
"files": {
|
||||
"merge_arrow_artwork.json": "f4a1e57defeb20289a2d3984665ed65a98d363bf6f854a84a3f90fe5da5d7c54",
|
||||
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
|
||||
"component_conflicts.py": "dccc333197b47bbbf211212b38d5a0018c8bae5f403fed1cbe3e22be0a81967e",
|
||||
"verify_topdown.py": "ad9960f7502d12afd1594480385d2ab8e5c9c7005c950c244fe10d6b0f25d6cf",
|
||||
"observation_checks.py": "3d818a93b112dca4ae292698cc0d3103b3f1e2d08abaded440f6959ed6ae6ccb",
|
||||
"plan_marking_policy.py": "8aaf12acda90d395af5615c3ab637afe67d0e4e3dd31ba8e83bfab6ed8e84632",
|
||||
"registration.py": "1f66a2c70789251813ad19f92f77d5a0244a0dbafbb6bc98d6c6b0239f32192d",
|
||||
"registered_template.py": "6c256bab9275c1d4924e5eb9a5982b0b777e6e637603d33f6d0df00ffad29464",
|
||||
"recall_templates.py": "56c8f95854df245d31b1b132bf800ab8ac9356e775bed52042304047cd849497",
|
||||
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
|
||||
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
|
||||
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
|
||||
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
|
||||
"paint_channels.py": "46da37b13914c69c72f6f4ae1bb5ad70e6f6b77b42355b016df1b3c4d72fbc63",
|
||||
"component_surface.py": "e425be65d184d474c5485160547f122291529622244da73ca484469ffd994d69",
|
||||
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
|
||||
"row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0",
|
||||
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
|
||||
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
|
||||
"arrow_admission.py": "2ed5a28706416dc3a2b674cc4d8cf007049db91e3c70b530ea14f1eec986c516",
|
||||
"glyph_rules.py": "747d3da1f0e0cd3301a6f20c5185eab68c431b4966c491ea77210bc4db48eac1",
|
||||
"glyph_templates.py": "8ddc50348563b048c362a447d68a30872284dc08c88ca9d9c70c27a382a62758",
|
||||
"recall_rules.py": "7a54b3ff0aaaac84d71206f685dd8479f8bfb1966294c50f56567c908794f94c",
|
||||
"recall_extent.py": "fea1f876ccf52dbaf7a06a68c7bf7870a8ebbc1331c612366419a36291433fbf",
|
||||
"component_rules.py": "910be55c56c3b406e1727339b1054ee0693a5d7c4ec46cb3cfa8015a34eb0553",
|
||||
"reconcile_objects.py": "d777079ec51df718abd2228ac42aa32f5345159a1b7af38b3c75d14b0833d961",
|
||||
"preservation.py": "99d116202a166cb4778637dfbe8c0f8e0e6e24571148c6d6761be02de7568ef7",
|
||||
"admission_contract.py": "17f138adacc8f555b09029a9bac91400babec1003b46e91dec7937a2ec88d768",
|
||||
"standard_arrow_templates.py": "c9bec7e5f7bb96a426c56cf8f7ee293ffcc651f0f3e012cc1a6b8aea60f41ff2",
|
||||
"plan_registration.py": "18fcdad3d6757ccebad7be39719d933f832941d26114d270e2341411d1e5428d",
|
||||
"standard_arrow_evidence.py": "1678afe91acd81be83c79c6d52c223532b0e3d742a00b10c3e1870b1131e775b",
|
||||
"pixel_geometry.py": "6986fd917bc5e03a2d69d9492c6e2249bc77ff81325b4b0cc1fcb7a46107ad7c",
|
||||
"registration_evaluator.py": "3d92d86fdd27b2b907b2b5a155dbdda1dbee710a1e6107ed7bbdca4a863765db",
|
||||
"observation_evaluator.py": "594a4c484c4f9ad2fffd0c4e0b2b7ea29c6ffa5c3f16319af4ad320bf90fc420",
|
||||
"head_observation.py": "79424f41b6491e869182d11585244c25bf67a77674acd9c35aaa15310e8aa0c4",
|
||||
"object_evidence.py": "981ab59d0a3204888fa52ca7b8cb0ba9ecf2dd34ee041a1e7afe0f25a09e40cd",
|
||||
"arrow_evidence.py": "047c0d9fe6e17c1500b993f8a6166406db1950e38c0af4562886143238c377ad",
|
||||
"component_evidence.py": "ef889c65ce03baf5da245a45c2819927d93ac16d4575fa28e3078a340fdd57fb",
|
||||
"candidate_registry.py": "89bba5261277896eb000d48230c86b2a1f1be9d5015f6e4cecc622420e7f61ee",
|
||||
"ground_observations.py": "eb25dc2a332ab3973f3252fc0a22cc054363878e1943000c1703081410fa5aa7",
|
||||
"paint_channels_fast.py": "5d42ca412ea98bebfbe5ac391929515996b2787c454996740502bff6fa92f7e3",
|
||||
"observed_fixed.py": "1ac96b102fe6b9acea9294b3287f493eccf78a6257f90b358bd5bcb6c8b1c829",
|
||||
"direct_fixed.py": "d29160fe04ea7e8b3f80632c4069682228510a47fbdeb57a6e6f3715040412cb",
|
||||
"reconstruct_topdown.py": "9c16412efe2ee67d8cf639f6bb9a331bae411c2b5388aa988993d9d6aa5a4559"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
from pathlib import Path
|
||||
from collections import Counter
|
||||
import numpy as np,cv2,shapely,json,hashlib,os,time
|
||||
from shapely.geometry import shape,Polygon,LineString,mapping
|
||||
from shapely.ops import transform
|
||||
from layer_common import O,sample,feature
|
||||
from plan_primitives import regularize_paint
|
||||
from paint_templates import fit_symbol
|
||||
from crosswalk_family import rectangle_info
|
||||
from crossing_fit import joint_rectangles
|
||||
start=time.monotonic();cv2.setNumThreads(3)
|
||||
old=json.loads(Path('/fullplan/full-map.json').read_text());base=old
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
|
||||
def lift(g):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),g)
|
||||
records=json.loads(Path('/primary/observations.json').read_text())
|
||||
paint_candidates=[(shape(v['geometry']),v['properties'])for v in records['paint']]
|
||||
cross_candidates=[(shape(v['geometry']),v['properties'])for v in records['crossbars']]
|
||||
paint=[];rejected=[]
|
||||
def dedup(records):
|
||||
result=[]
|
||||
for p,props in sorted(records,key=lambda x:-x[0].area):
|
||||
if any(p.intersection(q).area/min(p.area,q.area)>.5 for q,_ in result):continue
|
||||
result.append((p,props))
|
||||
return result
|
||||
cross_candidates=dedup(cross_candidates)
|
||||
# A broad appearance proposal must not suppress a semantic component before
|
||||
# admission. Keep the two primary observation contracts separate until fitting.
|
||||
semantic=[r for r in paint_candidates if r[1].get('proposal_contract')=='semantic-paint-v1']
|
||||
appearance=[r for r in paint_candidates if r[1].get('proposal_contract')!='semantic-paint-v1']
|
||||
paint_candidates=dedup(semantic)+dedup(appearance);paint=[]
|
||||
# Group neighboring parallel stripes without fixture coordinates, then run existing joint fit.
|
||||
obs=[]
|
||||
for i,(p,props)in enumerate(cross_candidates):
|
||||
points=np.asarray(p.exterior.coords);box,center,u,v=rectangle_info(points);obs.append(dict(id=str(i),points=points,box=box,center=center,u=u,v=v))
|
||||
parent=list(range(len(obs)))
|
||||
def root(i):
|
||||
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
|
||||
return i
|
||||
for i,a in enumerate(obs):
|
||||
for j,b in enumerate(obs[:i]):
|
||||
delta=a['center']-b['center']
|
||||
if abs(a['u']@b['u'])>np.cos(np.deg2rad(12))and abs(delta@a['u'])<1 and abs(delta@a['v'])<2:parent[root(i)]=root(j)
|
||||
groups={}
|
||||
for i in range(len(obs)):groups.setdefault(root(i),[]).append(i)
|
||||
for ids in groups.values():
|
||||
if len(ids)<3:rejected.extend(dict(kind='crosswalk',reason='insufficient-family-support')for i in ids);continue
|
||||
fitted,rec=joint_rectangles([obs[i]for i in ids])
|
||||
if not rec['optimizer_success']or rec['boundary_residual_p95_m']>.15:rejected.append(dict(kind='crosswalk',reason='joint-fit-disagreement',stripes=len(ids)));continue
|
||||
for f,i in zip(fitted,ids):paint.append(feature(lift(Polygon(f['points'])),'road_marking',**cross_candidates[i][1],family_size=len(ids),fit_p95_m=f['fit_p95_m']))
|
||||
# Only admitted objects own paint; a rejected hypothesis cannot hide evidence.
|
||||
admitted_crossbars=[shapely.force_2d(shape(f['geometry']))for f in paint]
|
||||
for p,props in paint_candidates:
|
||||
if any(p.intersection(q).area>.2*p.area for q in admitted_crossbars):continue
|
||||
if any(p.intersection(shapely.force_2d(shape(f['geometry']))).area/max(min(p.area,shape(f['geometry']).area),1e-9)>.5 for f in paint if f['properties'].get('subtype')=='linear_marking'):continue
|
||||
if props.get('proposal_contract')!='semantic-paint-v1' and (props.get('semantic_support',0)<.10 or props.get('semantic_peak',0)<.3):
|
||||
rejected.append(dict(kind='paint',reason='appearance-without-object-support',geometry=mapping(p),**props));continue
|
||||
fitted,method=regularize_paint(p)
|
||||
if method=='parametric-paint-strip':
|
||||
paint.append(feature(lift(fitted),'road_marking',subtype='linear_marking',method=method,**props));continue
|
||||
rect=cv2.minAreaRect(np.asarray(p.exterior.coords,np.float32));a,b=sorted(rect[1]);iou=p.area/max(a*b,1e-8)
|
||||
if a>.045 and a<.5 and b>.5 and b/a>3 and iou>.72 and not p.interiors:
|
||||
paint.append(feature(lift(Polygon(cv2.boxPoints(rect))),'road_marking',subtype='linear_marking',method='rectangle-template',**props));continue
|
||||
# Recognize a whole appearance component; model support may cover only part
|
||||
# of a worn glyph. It must still locate the object, preventing symbols on noise.
|
||||
if props.get('semantic_support',0)<.14 or props.get('semantic_peak',0)<.35:
|
||||
rejected.append(dict(kind='symbol',reason='no-object-semantic-support',geometry=mapping(p),**props));continue
|
||||
center=p.centroid;boundaries=[shapely.force_2d(shape(x['geometry']))for x in base['features']if x['properties']['class']=='road_boundary']
|
||||
if not boundaries:
|
||||
rejected.append(dict(kind='symbol',reason='no-street-direction',geometry=mapping(p),**props));continue
|
||||
nearest=min(boundaries,key=lambda x:x.distance(center))
|
||||
station=nearest.project(center);head=np.asarray(nearest.interpolate(min(nearest.length,station+5)).coords[0])-np.asarray(nearest.interpolate(max(0,station-5)).coords[0])
|
||||
f=fit_symbol(p,heading=head if np.linalg.norm(head)>1 else None,allowed_kinds={'letter_A'})
|
||||
if f is not None:
|
||||
fitted,iou,kind,recall,params=f
|
||||
axis=np.array([np.cos(params[2]),np.sin(params[2])]);center=fitted.centroid;aligned=False
|
||||
for boundary in base['features']:
|
||||
if boundary['properties']['class']!='road_boundary':continue
|
||||
line=shapely.force_2d(shape(boundary['geometry']))
|
||||
if line.distance(center)>12:continue
|
||||
station=line.project(center);a=np.asarray(line.interpolate(max(0,station-3)).coords[0]);b=np.asarray(line.interpolate(min(line.length,station+3)).coords[0]);t=b-a;t/=max(np.linalg.norm(t),1e-8)
|
||||
if abs(t@axis)>.88:aligned=True;break
|
||||
if aligned:paint.append(feature(lift(fitted),'road_marking',subtype=kind,method='symbol-template',template_fit_score=iou,fit_recall=recall,template_parameters=params,**props))
|
||||
else:rejected.append(dict(kind='symbol',reason='incompatible-street-direction',geometry=mapping(p),**props))
|
||||
else:rejected.append(dict(kind='symbol',reason='no-template-admitted',geometry=mapping(p),**props))
|
||||
|
||||
from paint_dedup import deduplicate_glyphs
|
||||
paint,audit=deduplicate_glyphs(paint)
|
||||
result={**base,'features':base['features']+paint,'primary_observations_sha256':hashlib.sha256(Path('/primary/observations.json').read_bytes()).hexdigest()}
|
||||
assert all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all() for f in result['features'])
|
||||
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
||||
(O/'unresolved-markings.json').write_text(json.dumps(rejected,allow_nan=False))
|
||||
(O/'paint-assembly-report.json').write_text(json.dumps(dict(paint_subtypes=dict(Counter(f['properties'].get('subtype')for f in paint)),seconds=time.monotonic()-start,source_objects_reused=0,manual_rois=[]),indent=2))
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Four logical layers with frozen curbs, observed fronts and object-level paint.
|
||||
No tile-specific policy, manual coordinates, point cloud or collider inputs.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import json,hashlib,time,os
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import shape,Polygon,LineString,mapping
|
||||
from shapely.ops import unary_union,transform
|
||||
from rasterio.features import shapes
|
||||
from affine import Affine
|
||||
from scipy.ndimage import distance_transform_edt,gaussian_filter1d,binary_closing
|
||||
from layer_common import O,S,B,feature,parts,sample
|
||||
from fit_scene import world,resample
|
||||
from plan_boundaries import split_observed_boundary
|
||||
from plan_coverage import vectorize
|
||||
from plan_primitives import regularize_paint,frontage_envelope
|
||||
from frontage_chains import join_planes
|
||||
from paint_templates import fit_symbol
|
||||
from crosswalk_family import rectangle_info,joint_rectangles
|
||||
cv2.setNumThreads(3);start=time.monotonic();report={};tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
evidence_receipt=json.loads((O/'evidence/report.json').read_text())
|
||||
for rec in evidence_receipt['records']:
|
||||
assert hashlib.sha256((O/'evidence'/(rec['tile']+'.npz')).read_bytes()).hexdigest()==rec['sha256']
|
||||
assert {rec['tile']for rec in evidence_receipt['records']}=={t['id']for t in tiles}
|
||||
input_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest()for p in [S/'tile-index.json',B/'whole-map.json',B/'observed-lines-v1/fields.npz',B/'regions/whole/fields.npz',Path('/multiview/mapillary/atlas-sparse.npz'),O/'evidence/report.json']}
|
||||
base=json.loads((B/'whole-map.json').read_text());road_bytes=(B/'whole-map.json').read_bytes();fields=np.load(B/'observed-lines-v1/fields.npz');low,high=fields['bounds'];road=fields['road']>.5;side=fields['side']>.5;alpha=fields['alpha'];height=np.load(B/'regions/whole/fields.npz')['z'];h,w=side.shape;fields.close();cell=.1
|
||||
labels=np.where(side,2,np.where(road,1,0)).astype('uint8')
|
||||
np.savez_compressed(O/'fields.npz',bounds=np.array([low,high]),labels=labels,z=height,cell=cell)
|
||||
(O/'map.base.json').write_text(json.dumps(base,allow_nan=False))
|
||||
def lift(g):
|
||||
def f(x,y,z=None):
|
||||
xy=np.c_[x,y];zz=sample(height,xy,low,high);return x,y,zz
|
||||
return transform(f,g)
|
||||
# Coverage polygons identify observed sidewalk, not physical scan-end curbs.
|
||||
walk=[]
|
||||
coverage,classes=vectorize(labels,tolerance=.25,transform=Affine(cell,0,low[0],0,-cell,high[1]))
|
||||
for p,cls in zip(coverage,classes):
|
||||
if cls!=2 or p.area<3:continue
|
||||
walk.append(feature(lift(p),'pedestrian_area',method='shared-semantic-coverage-GEOS',boundary_role='coverage-outline-not-physical-curb',area_m2=p.area,physical_boundary_ids=[f['id']for f in base['features']if shape(f['geometry']).distance(p)<.6]))
|
||||
del coverage,classes
|
||||
# Facades reuse the existing Gaussian covariance/vertical-plane detector.
|
||||
import source_facade_planes
|
||||
source_facade_planes.main()
|
||||
facade_doc=json.loads((O/'map.source-facades-v3.json').read_text());rawfacades=[f for f in facade_doc['features']if f['properties']['class']=='building_facade']
|
||||
planes=[shapely.force_2d(shape(f['geometry']))for f in rawfacades]
|
||||
def ground_side(points,normal):
|
||||
plus=sum(np.mean(sample(labels,points+normal*d,low,high)>0)for d in [.5,1.,1.5])
|
||||
minus=sum(np.mean(sample(labels,points-normal*d,low,high)>0)for d in [.5,1.,1.5])
|
||||
return float(np.sign(plus-minus))
|
||||
envelope,envelope_report=frontage_envelope(planes,ground_side)
|
||||
joined=join_planes([g for g,ids in envelope]);facades=[]
|
||||
for p,ids in joined:
|
||||
g=LineString(p)
|
||||
facades.append(feature(lift(g),'building_facade',method='gaussian-covariance-vertical-planes-huber-join',source_plane_ids=sorted({rawfacades[j]['id']for i in ids for j in envelope[i][1]}),closed_footprint=False,hidden_backs_invented=False))
|
||||
# Additional true pedestrian/terrain interfaces; never raster coverage caps.
|
||||
a=np.load('/multiview/mapillary/atlas-sparse.npz');terrain=np.zeros((h,w),np.float32);terrain[a['rows'],a['cols']]=a['posterior'][4];a.close();near_terrain=distance_transform_edt(terrain<.45)*cell
|
||||
contours,_=cv2.findContours(side.astype('uint8'),cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE);walk_edges=[]
|
||||
road_geom=unary_union([shapely.force_2d(shape(f['geometry']))for f in base['features']]);facade_geom=unary_union([shapely.force_2d(shape(f['geometry']))for f in facades])
|
||||
for c in contours:
|
||||
if len(c)<30:continue
|
||||
p=c[:,0];xy=np.c_[low[0]+(p[:,0]+.5)*cell,high[1]-(p[:,1]+.5)*cell];xy=resample(np.vstack([xy,xy[0]]),.15)[:-1]
|
||||
seen=sample(alpha,xy,low,high)>.75;physical=sample(near_terrain,xy,low,high)<.5
|
||||
physical=binary_closing(physical,structure=np.ones(7))&seen
|
||||
for chain in split_observed_boundary(xy,physical,seen,minimum_length=3):
|
||||
g=LineString(chain.points).simplify(.2,preserve_topology=True)
|
||||
for piece in parts(g.difference(road_geom.buffer(.65)).difference(facade_geom.buffer(.5)),'LineString'):
|
||||
if piece.length>3:walk_edges.append(feature(lift(piece),'pedestrian_boundary',method='observed-walk-terrain-interface',closed=piece.is_closed))
|
||||
paint=[];rejected=[]
|
||||
result={**base,'schema_version':'missioncore.full-observed-plan-research/v1','features':base['features']+walk+walk_edges+facades+paint,'review_status':'unreviewed','road_baseline_sha256':hashlib.sha256(road_bytes).hexdigest(),'logical_layers':['roads','pedestrian_zones','buildings','road_markings']}
|
||||
# Validation is structural, separate from visual and metric accuracy.
|
||||
invalid=[]
|
||||
for f in result['features']:
|
||||
geom=shape(f['geometry']);coords=shapely.get_coordinates(geom,include_z=True)
|
||||
if not geom.is_valid or not np.isfinite(coords).all():invalid.append(f['id'])
|
||||
assert not invalid,invalid
|
||||
assert result['features'][:len(base['features'])]==base['features']
|
||||
assert all(shape(f['geometry']).geom_type=='LineString'and not shape(f['geometry']).is_closed for f in facades)
|
||||
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
||||
(O/'unresolved-markings.json').write_text(json.dumps(rejected,allow_nan=False))
|
||||
report=dict(frontage_envelope=envelope_report,input_sha256=input_hashes,scene=os.environ['SCENE'],seconds=time.monotonic()-start,road_curbs_preserved_exactly=True,road_baseline_sha256=hashlib.sha256(road_bytes).hexdigest(),counts={c:sum(f['properties']['class']==c for f in result['features'])for c in ['road_boundary','pedestrian_area','pedestrian_boundary','building_facade','road_marking']},pedestrian_area_m2=sum(shape(f['geometry']).area for f in walk),facade_length_m=sum(shape(f['geometry']).length for f in facades),paint_subtypes={c:sum(f['properties']['subtype']==c for f in paint)for c in sorted(set(f['properties']['subtype']for f in paint))},unresolved_markings=len(rejected),manual_rois=[],manual_geometry=False,point_clouds=False,colliders=False,metric_accuracy_measured=False,source_gaussian_planes_reused=True,hidden_building_backs_invented=0,all_geometry_valid_finite_xyz=True)
|
||||
(O/'report.json').write_text(json.dumps(report,indent=2));print('FULL-PLAN',json.dumps(report),flush=True)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Decode a fixed bounded set of concepts together on one image embedding.
|
||||
|
||||
This uses the pinned SAM3 model's FindStage batch interface. All confidence,
|
||||
presence, interpolation and mask thresholds match Sam3Processor. No proposal
|
||||
is accepted by this helper: downstream independent geometric checks remain.
|
||||
"""
|
||||
import torch
|
||||
from sam3.model.data_misc import FindStage,interpolate
|
||||
|
||||
class ConceptDecoder:
|
||||
def __init__(self,processor,batch_size=3):
|
||||
if batch_size not in [1,2,3]:raise ValueError('Unqualified batch size')
|
||||
self.processor=processor;self.batch_size=batch_size;self._text={}
|
||||
self.text_encodings=0;self.decoder_calls=0
|
||||
|
||||
@torch.inference_mode()
|
||||
def __call__(self,image,prompts):
|
||||
if len(prompts)!=len(set(prompts)):raise ValueError('Duplicate concept')
|
||||
result={};p=self.processor;model=p.model
|
||||
with torch.autocast('cuda',dtype=torch.bfloat16):
|
||||
state=p.set_image(image)
|
||||
for offset in range(0,len(prompts),self.batch_size):
|
||||
concepts=tuple(prompts[offset:offset+self.batch_size]);n=len(concepts)
|
||||
if concepts not in self._text:
|
||||
if len(self._text)>=16:raise ValueError('Exceeded fixed concept vocabulary')
|
||||
self._text[concepts]=model.backbone.forward_text(list(concepts),device=p.device)
|
||||
self.text_encodings+=1
|
||||
backbone={**state['backbone_out'],**{k:v.clone()if isinstance(v,torch.Tensor)else v for k,v in self._text[concepts].items()}}
|
||||
find=FindStage(img_ids=torch.zeros(n,device=p.device,dtype=torch.long),text_ids=torch.arange(n,device=p.device,dtype=torch.long),input_boxes=None,input_boxes_mask=None,input_boxes_label=None,input_points=None,input_points_mask=None)
|
||||
outputs=model.forward_grounding(backbone_out=backbone,find_input=find,find_target=None,geometric_prompt=model._get_dummy_prompt(num_prompts=n))
|
||||
probabilities=(outputs['pred_logits'].sigmoid()*outputs['presence_logit_dec'].sigmoid().unsqueeze(1)).squeeze(-1)
|
||||
for i,concept in enumerate(concepts):
|
||||
keep=probabilities[i]>p.confidence_threshold
|
||||
masks=interpolate(outputs['pred_masks'][i][keep].unsqueeze(1),(image.height,image.width),mode='bilinear',align_corners=False).sigmoid()
|
||||
result[concept]=dict(masks=(masks>.5).reshape(-1,image.height,image.width).cpu().numpy(),scores=probabilities[i][keep].float().cpu().numpy().reshape(-1))
|
||||
self.decoder_calls+=1
|
||||
return result
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Geometry-only ownership for two continuous Gaussian evidence mosaics."""
|
||||
from pathlib import Path
|
||||
from functools import lru_cache
|
||||
import numpy as np,cv2,shapely
|
||||
from PIL import Image
|
||||
from fit_scene import project
|
||||
from layer_common import S,sample
|
||||
from row_profiles import POLICY
|
||||
|
||||
def choose_owners(distances,coverage):
|
||||
# Stable order is geometry then tile index, never paint intensity/confidence.
|
||||
if distances.shape[1]==0:return np.full((len(distances),2),-1,dtype=int)
|
||||
order=np.argsort(np.where(coverage,distances,np.inf),axis=1,kind='stable')[:,:2]
|
||||
if order.shape[1]<2:order=np.pad(order,((0,0),(0,2-order.shape[1])),constant_values=-1)
|
||||
for j in range(2):
|
||||
okay=(order[:,j]>=0)&coverage[np.arange(len(order)),np.maximum(order[:,j],0)]
|
||||
order[~okay,j]=-1
|
||||
return order
|
||||
class GaussianViews:
|
||||
def __init__(self,tiles,labels,low,high,protected):
|
||||
self.tiles=tiles;self.labels=labels;self.low=low;self.high=high;self.protected=protected
|
||||
self.centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in tiles])
|
||||
@lru_cache(maxsize=90)
|
||||
def geometry(self,name):return dict(np.load(S/name/'top.geometry.npz'))
|
||||
@lru_cache(maxsize=4)
|
||||
def inputs(self,name):
|
||||
rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB'))
|
||||
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=z['vehicle'].astype('float32')
|
||||
return rgb,vehicle
|
||||
def strip_owners(self,origin,axis,ts):
|
||||
# The same complete transverse strip and stable camera ordering, batched
|
||||
# over immutable orthographic camera matrices rather than Python loops.
|
||||
if not hasattr(self,'_camera_batch'):
|
||||
cameras=[self.geometry(tile['id']) for tile in self.tiles]
|
||||
self._camera_batch=(np.asarray([g['view'][:2,:2] for g in cameras]),
|
||||
np.asarray([g['view'][:2,3] for g in cameras]),
|
||||
np.asarray([np.diag(g['intrinsics'])[:2] for g in cameras]),
|
||||
np.asarray([g['intrinsics'][:2,2] for g in cameras]))
|
||||
rotation,translation,scale,principal=self._camera_batch
|
||||
centers=origin+ts[:,None]*axis;n=np.array([-axis[1],axis[0]])
|
||||
ends=centers[:,None,:]+np.array([-1,1])[None,:,None]*POLICY['coverage_half_width_m']*n
|
||||
q=np.matmul(ends[:,None,:,:],rotation[None,:,:,:].swapaxes(-1,-2))+translation[None,:,None,:]
|
||||
uv=q*scale[None,:,None,:]+principal[None,:,None,:]-.5
|
||||
margin=POLICY['coverage_margin_px'];coverage=(uv.min(axis=(2,3))>=margin)&(uv.max(axis=(2,3))<1200-margin)
|
||||
# Preserve exact legacy boundary decisions despite BLAS summation
|
||||
# order. Only numerically borderline entries need scalar-camera math.
|
||||
borderline=((abs(uv-margin)<1e-8)|(abs(uv-(1200-margin))<1e-8)).any(axis=(2,3))
|
||||
for index in np.flatnonzero(borderline.any(axis=0)):
|
||||
selected=borderline[:,index];g=self.geometry(self.tiles[int(index)]['id'])
|
||||
a=project(centers[selected]-POLICY['coverage_half_width_m']*n,g)
|
||||
b=project(centers[selected]+POLICY['coverage_half_width_m']*n,g)
|
||||
exact=np.concatenate([a,b],axis=1)
|
||||
coverage[selected,index]=(exact.min(1)>=margin)&(exact.max(1)<1200-margin)
|
||||
distance=np.linalg.norm(centers[:,None,:]-self.centers[None,:,:],axis=2)
|
||||
return choose_owners(distance,coverage)
|
||||
def readers(self,origin,axis):
|
||||
o=np.asarray(origin);u=np.asarray(axis);n=np.array([-u[1],u[0]]);used=[{},{}];cache={}
|
||||
def ownership(points):
|
||||
ts,inverse=np.unique(np.round((points-o)@u,6),return_inverse=True)
|
||||
key=ts.tobytes()
|
||||
if key not in cache:
|
||||
cache[key]=self.strip_owners(o,u,ts)
|
||||
return cache[key][inverse]
|
||||
def reader(rank):
|
||||
def read(points, detailed=False):
|
||||
owners=ownership(points)[:,rank];gates={k:np.zeros(len(points),bool) for k in ['coverage','alpha','road','vehicle','protected']};colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool)
|
||||
for i in np.unique(owners):
|
||||
if i<0:continue
|
||||
select=np.flatnonzero(owners==i);xy=points[select];name=self.tiles[i]['id'];used[rank][name]=used[rank].get(name,0)+len(select);g=self.geometry(name);rgb,vehicle=self.inputs(name)
|
||||
uv=project(xy,g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
|
||||
def remap(a,q):return np.concatenate([cv2.remap(a,part[:,0,None],part[:,1,None],cv2.INTER_LINEAR).reshape(len(part),-1)for part in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))])
|
||||
colors[select]=remap(rgb,native);veh=remap(vehicle,uv).ravel();alpha=remap(g['alpha'].astype('float32'),uv).ravel()
|
||||
gates['coverage'][select]=True;gates['alpha'][select]=alpha>=.65;gates['road'][select]=sample(self.labels,xy,self.low,self.high)==1;gates['vehicle'][select]=veh<.20;gates['protected'][select]=~shapely.contains_xy(self.protected,xy[:,0],xy[:,1])
|
||||
allowed[select]=np.logical_and.reduce([v[select] for v in gates.values()])
|
||||
return (colors,allowed,gates) if detailed else (colors,allowed)
|
||||
return read
|
||||
return [reader(0),reader(1)],used
|
||||
@@ -0,0 +1,43 @@
|
||||
import numpy as np
|
||||
from scipy.ndimage import gaussian_filter1d
|
||||
from scipy.signal import find_peaks,peak_widths
|
||||
from beta_profiles import POLICY,section_evidence,supported
|
||||
from interval_profiles import runs
|
||||
def signal_at(view,offsets):
|
||||
ns=view['ns'];indices=np.rint((np.asarray(offsets)-ns[0])/POLICY['step_m']).astype(int)
|
||||
indices=np.clip(indices,1,len(ns)-2)
|
||||
index=indices[:,None]+np.array([-1,0,1])
|
||||
row=np.arange(len(view['ts']))[:,None]
|
||||
signal=gaussian_filter1d(np.median(view['contrast'][row,index],axis=1),1)
|
||||
valid=view['allowed'][row,index].all(1)
|
||||
return {**view,'signal':signal,'valid':valid}
|
||||
|
||||
|
||||
def local_body(view,center,length,mode):
|
||||
ts,ns=view['ts'],view['ns'];step=POLICY['step_m']
|
||||
region=abs(ts-center)<=length*.35
|
||||
if region.sum()<3:return None
|
||||
transverse=np.quantile(np.where(view['allowed'][region],view['contrast'][region],0),.8,axis=0)
|
||||
peaks,_=find_peaks(transverse,height=18,prominence=8,distance=4)
|
||||
peaks=[k for k in peaks if abs(ns[k]-view['offset'])<=POLICY['max_ridge_offset_m']]
|
||||
if not peaks:return None
|
||||
k=min(peaks,key=lambda k:abs(ns[k]-view['offset']))
|
||||
width=float(peak_widths(transverse,[k],rel_height=.5)[0][0]*step)
|
||||
if not .045<=width<=POLICY['max_seed_width_m']:return None
|
||||
offset=float(ns[k]);local=signal_at(view,np.full(len(ts),offset));sig,valid=local['signal'],local['valid']
|
||||
if mode=='intervals':
|
||||
paint=(sig>view['cut'])&valid
|
||||
for a,b in runs(~paint):
|
||||
if a>0 and b<len(ts)and (b-a)*step<=POLICY['max_crack_m']and valid[a:b].all():paint[a:b]=True
|
||||
intervals=[(float(ts[a]-step/2),float(ts[b-1]+step/2))for a,b in runs(paint)if (b-a)*step>=POLICY['min_dash_length_m']]
|
||||
else:
|
||||
positions,_=find_peaks(np.where(valid,sig,0),prominence=18,distance=int(.45/step))
|
||||
widths=peak_widths(np.where(valid,sig,0),positions,rel_height=.5)
|
||||
intervals=[(float(ts[0]+widths[2][j]*step),float(ts[0]+widths[3][j]*step))for j in range(len(positions))if .26<widths[0][j]*step<1.4]
|
||||
options=[ab for ab in intervals if abs((ab[0]+ab[1])/2-center)<=POLICY['max_phase_error_m']and abs((ab[1]-ab[0])-length)<=max(.2,.22*length)]
|
||||
if not options:return None
|
||||
interval=min(options,key=lambda ab:abs((ab[0]+ab[1])/2-center))
|
||||
local.update(offset=offset,width=width)
|
||||
return dict(view=local,edges=interval,offset=offset,width=width)
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Reuse invariant text encodings within one frozen model instance.
|
||||
|
||||
Image embeddings, decoder calls, confidence thresholds and mask projection are
|
||||
unchanged. Cache lifetime is the processor instance, never a service/global
|
||||
cache. Each use receives private tensor copies so decoders cannot mutate the
|
||||
next query's text observations.
|
||||
"""
|
||||
import torch
|
||||
from sam3.model.sam3_image_processor import Sam3Processor
|
||||
|
||||
class CachedTextProcessor(Sam3Processor):
|
||||
def __init__(self,*args,**kwargs):
|
||||
super().__init__(*args,**kwargs)
|
||||
self._text_encodings={}
|
||||
self.text_encodes=0
|
||||
self.text_requests=0
|
||||
|
||||
@torch.inference_mode()
|
||||
def set_text_prompt(self,prompt,state):
|
||||
if 'backbone_out'not in state:
|
||||
raise ValueError('You must call set_image before set_text_prompt')
|
||||
key=(prompt,torch.is_autocast_enabled('cuda'),torch.get_autocast_dtype('cuda'))
|
||||
self.text_requests+=1
|
||||
if key not in self._text_encodings:
|
||||
self._text_encodings[key]=self.model.backbone.forward_text([prompt],device=self.device)
|
||||
self.text_encodes+=1
|
||||
state['backbone_out'].update({k:v.clone() if isinstance(v,torch.Tensor) else v for k,v in self._text_encodings[key].items()})
|
||||
if 'geometric_prompt'not in state:
|
||||
state['geometric_prompt']=self.model._get_dummy_prompt()
|
||||
return self._forward_grounding(state)
|
||||
@@ -0,0 +1,40 @@
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import Polygon,mapping
|
||||
from layer_common import sample,parts
|
||||
from fit_scene import world
|
||||
def eligible(p):
|
||||
if p.is_empty or p.area<.08:return False
|
||||
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True)
|
||||
if W<=0:return False
|
||||
fill=p.area/(L*W)
|
||||
return (1.<L<4.5 and .4<W<2.2 and 1.1<L/W<4 and .10<fill<.70)or(3<L<60 and .45<W<5 and .03<fill<.40)
|
||||
|
||||
def collect(rgb,raw_vehicle,g,labels,low,high,name):
|
||||
size=rgb.shape[0];mpp=60/size;glyphs=[]
|
||||
def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g)
|
||||
# Sample the road field on the calibrated 1200px grid, then upsample its
|
||||
# categorical gate. No semantic marking confidence is an admission gate.
|
||||
yy,xx=np.mgrid[:1200,:1200];points=world(np.c_[xx.ravel(),yy.ravel()],g)
|
||||
road=(sample(labels,points,low,high)==1).reshape(1200,1200)
|
||||
allowed=cv2.resize((road&(raw_vehicle<.2)&(g['alpha']>.65)).astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0
|
||||
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/mpp)//2*2+1,)*2)
|
||||
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel);binary=((ridge>12)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))&allowed).astype('uint8')
|
||||
cc,hier=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);components=[]
|
||||
if hier is not None:
|
||||
for i,c in enumerate(cc):
|
||||
if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.008:continue
|
||||
holes=[];j=hier[0,i,2]
|
||||
while j>=0:
|
||||
if cv2.contourArea(cc[j])*mpp*mpp>.003:holes.append(xy(cc[j][:,0]))
|
||||
j=hier[0,j,0]
|
||||
components.extend(parts(shapely.make_valid(Polygon(xy(c[:,0]),holes))))
|
||||
union=shapely.union_all(components);candidates=list(components)
|
||||
for radius in [.08,.16]:
|
||||
for region in parts(union.buffer(radius).buffer(-radius)):
|
||||
if eligible(region):candidates.append(union.intersection(region.buffer(.015)))
|
||||
accepted=[]
|
||||
for p in candidates:
|
||||
if not eligible(p):continue
|
||||
if any(p.intersection(q).area/min(p.area,q.area)>.85 for q in accepted):continue
|
||||
accepted.append(p);glyphs.append(dict(geometry=mapping(p),source_tile=name))
|
||||
return glyphs
|
||||
@@ -0,0 +1,43 @@
|
||||
import numpy as np,cv2
|
||||
from fit_scene import world
|
||||
from layer_common import sample
|
||||
|
||||
def collect(rgb,vehicle,geometry,labels,low,high,name):
|
||||
proposals=[]
|
||||
size = rgb.shape[0]; cell = 60 / size
|
||||
yy, xx = np.mgrid[:1200, :1200]
|
||||
xy = world(np.c_[xx.ravel(), yy.ravel()], geometry)
|
||||
paved = np.isin(sample(labels, xy, low, high), [1, 2]).reshape(1200, 1200)
|
||||
known = paved & (geometry['alpha'] >= .8) & (vehicle < .2)
|
||||
known = cv2.resize(known.astype('uint8'), (size, size), interpolation=cv2.INTER_NEAREST) > 0
|
||||
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
|
||||
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
|
||||
k = max(3, round(.72 / cell) // 2 * 2 + 1)
|
||||
ridge = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT,
|
||||
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k)))
|
||||
paint = (known & (ridge > 12) & (gray > 100) & (hsv[:, :, 1] < 100)).astype('uint8')
|
||||
count = 0
|
||||
for closing_m in [0., .04, .08]:
|
||||
radius = max(1, round(closing_m / cell))
|
||||
binary = cv2.morphologyEx(paint, cv2.MORPH_CLOSE,
|
||||
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1))) if closing_m else paint
|
||||
contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
|
||||
if hierarchy is None:
|
||||
continue
|
||||
for i, contour in enumerate(contours):
|
||||
if hierarchy[0, i, 3] >= 0 or len(contour) < 4:
|
||||
continue
|
||||
rect = cv2.minAreaRect(contour)
|
||||
length, width = sorted(np.asarray(rect[1])*cell, reverse=True)
|
||||
if not (.35 < length < 2.5 and .25 < width < 1.7):
|
||||
continue
|
||||
holes = 0; j = hierarchy[0, i, 2]
|
||||
while j >= 0:
|
||||
holes += cv2.contourArea(contours[j]) >= 9
|
||||
j = hierarchy[0, j, 0]
|
||||
if holes < 2:
|
||||
continue
|
||||
center = world((np.asarray(rect[0])[None, :]+.5)*1200/size-.5, geometry)[0]
|
||||
proposals.append(dict(center=center.tolist(), source='paint-topology', seed_tile=name))
|
||||
count += 1
|
||||
return proposals
|
||||
@@ -0,0 +1,37 @@
|
||||
"""A raw connected outline defines its axis by paint area, not extreme pixels."""
|
||||
import numpy as np,cv2
|
||||
from beta_profiles import POLICY
|
||||
from stroke_seeds import from_component as rectangle_seed
|
||||
|
||||
|
||||
def from_component(polygon):
|
||||
if polygon.geom_type!='Polygon' or polygon.is_empty:return None
|
||||
# Already measured rectangles have no pixel fringe to reinterpret. Keeping
|
||||
# them exact also preserves the independent long-line detector's result.
|
||||
if polygon.symmetric_difference(polygon.minimum_rotated_rectangle).area<1e-9:return rectangle_seed(polygon)
|
||||
origin=np.array(polygon.centroid.coords[0])[:2]
|
||||
names=['m00','m10','m01','m20','m11','m02'];moments={k:0. for k in names}
|
||||
for ring,sign in [(polygon.exterior,1)]+[(r,-1)for r in polygon.interiors]:
|
||||
measured=cv2.moments((np.asarray(ring.coords)[:,:2]-origin).astype('float32'))
|
||||
for k in names:moments[k]+=sign*measured[k]
|
||||
if moments['m00']<=0:return None
|
||||
center=np.array([moments['m10'],moments['m01']])/moments['m00']
|
||||
covariance=np.array([[moments['m20'],moments['m11']],[moments['m11'],moments['m02']]])/moments['m00']-np.outer(center,center)
|
||||
values,vectors=np.linalg.eigh(covariance)
|
||||
if values[0]<=0 or values[1]<4*values[0]:return None
|
||||
axis=vectors[:,1];width=float(np.sqrt(12*values[0]));center=origin+center
|
||||
t=(np.asarray(polygon.exterior.coords)[:,:2]-center)@axis;length=float(np.ptp(t))
|
||||
if not POLICY['min_seed_length_m']<=length<=POLICY['max_seed_length_m']:return None
|
||||
if width>2*POLICY['normal_half_width_m']or length<2*width:return None
|
||||
return dict(origin=center+axis*(t.min()+t.max())/2,axis=axis,length=length,width=width,proposal_contract='connected-paint-area-axis; final-width-unmeasured')
|
||||
|
||||
|
||||
def preferred(polygon):
|
||||
"""One initial axis per component; choose from shape, never failed search.
|
||||
|
||||
Area moments resist extreme fringe pixels. Where that estimator cannot
|
||||
establish an elongated component, retain the original rectangle estimator.
|
||||
Both estimators only propose; all pixel/width/endpoint gates stay downstream.
|
||||
"""
|
||||
measured=from_component(polygon)
|
||||
return measured if measured is not None else rectangle_seed(polygon)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Transfer only whole conserved sources; leave neighbor choices to the solver.
|
||||
|
||||
An intersecting source outside this replacement's measurement domain is not
|
||||
deleted or clipped. It remains owned by its keep/replacement alternatives.
|
||||
The joint overlap and seam constraints prohibit selecting it with this body.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import shapely
|
||||
from marking_rules import POLICY, validate_removed
|
||||
from shapely.geometry import shape
|
||||
|
||||
|
||||
def plan(candidate, current, readers):
|
||||
p = shapely.union_all(candidate["polygons"])
|
||||
domain = p.buffer(POLICY["max_join_gap_m"])
|
||||
ids, neighbors = [], []
|
||||
for ident, feature in current.items():
|
||||
if feature["properties"].get("class") != "road_marking":
|
||||
continue
|
||||
q = shapely.force_2d(shape(feature["geometry"]))
|
||||
if q.intersection(domain).area < POLICY["max_overlap_m2"]:
|
||||
continue
|
||||
if feature["properties"].get("subtype") != "linear_marking":
|
||||
# Protected symbols retain the original hard ownership boundary.
|
||||
return None, dict(reason="protected-owner")
|
||||
if q.difference(domain).area > POLICY["max_overlap_m2"]:
|
||||
neighbors.append(ident)
|
||||
else:
|
||||
ids.append(ident)
|
||||
old = shapely.union_all([shapely.force_2d(shape(current[i]["geometry"])) for i in ids])
|
||||
removed = old.difference(p.buffer(POLICY["retained_paint_tolerance_m"]))
|
||||
if not removed.is_empty:
|
||||
normal = np.array([-candidate["axis"][1], candidate["axis"][0]])
|
||||
transverse = (shapely.get_coordinates(removed) - candidate["origin"]) @ normal
|
||||
if np.max(abs(transverse)) > 0.7:
|
||||
return None, dict(reason="removed-paint-outside-measurement")
|
||||
okay, evidence = validate_removed(old, p, candidate, readers)
|
||||
if not okay:
|
||||
return None, dict(reason="positive-or-unobserved-removed-paint", views=evidence)
|
||||
return sorted(ids), dict(
|
||||
reason="conserved-whole-sources-conditional-neighbors",
|
||||
views=evidence,
|
||||
conditional_neighbors=sorted(neighbors),
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Compose observed terminal junctions from independently admitted strips.
|
||||
|
||||
This does not admit raw proposals. It consumes the immutable admitted bank;
|
||||
the exact union is one physical object, never two overlapping output objects.
|
||||
Alternative axes, parallel tracks, interior crossings and gaps stay conflicts.
|
||||
"""
|
||||
import hashlib,json
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import shape,mapping
|
||||
from beta_profiles import describe
|
||||
from marking_rules import POLICY,VERSION
|
||||
from layer_common import feature
|
||||
|
||||
|
||||
def geometry(feature):
|
||||
return shapely.force_2d(shape(feature['geometry']))
|
||||
|
||||
|
||||
def identity(transaction):
|
||||
value=dict(sources=sorted(transaction['source_ids']),
|
||||
after=sorted(f['id']for f in transaction['after']),kind=transaction['kind'])
|
||||
return hashlib.sha256(json.dumps(value,sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def junction(a,b):
|
||||
"""A measured overlap must occupy a terminal cap of each distinct axis."""
|
||||
da,db=describe(a),describe(b)
|
||||
if da is None or db is None:return None
|
||||
if abs(da['axis']@db['axis'])>=np.cos(np.deg2rad(POLICY['max_join_angle_deg'])):return None
|
||||
shared=a.intersection(b)
|
||||
if shared.area<=POLICY['max_overlap_m2']:return None
|
||||
for d in [da,db]:
|
||||
t=(shapely.get_coordinates(shared)-d['origin'])@d['axis']
|
||||
cap=d['width']+POLICY['retained_paint_tolerance_m']
|
||||
# End caps must be disjoint: a short near-square patch has no
|
||||
# identifiable terminal junction, even if its fitted axes differ.
|
||||
if 2*cap>=d['length']:return None
|
||||
if not(t.min()>=d['length']/2-cap or t.max()<=-d['length']/2+cap):return None
|
||||
merged=a.union(b)
|
||||
if merged.geom_type!='Polygon' or not merged.is_valid:return None
|
||||
return merged
|
||||
|
||||
|
||||
def compose(configurations,lift):
|
||||
"""One composition per measured neighboring pair; no recursive closure."""
|
||||
allowed={'observed-finite-stroke','whole-observed-finite-stroke',
|
||||
'observed-continuous-addition','whole-observed-continuous-stroke','observed-continuous-extension'}
|
||||
unique={identity(c):c for c in configurations if c['kind']in allowed and len(c['after'])==1
|
||||
and not c.get('atomic_family') and c['after'][0]['properties'].get('subtype')=='linear_marking'}
|
||||
keys=sorted(unique);records=[unique[k]for k in keys]
|
||||
polygons=[geometry(c['after'][0])for c in records];tree=shapely.STRtree(polygons)
|
||||
output=[];checked=0
|
||||
for i,(a,pa) in enumerate(zip(records,polygons)):
|
||||
for j in sorted(int(k)for k in tree.query(pa,predicate='intersects')if k>i):
|
||||
b=records[j]
|
||||
if set(a['source_ids'])&set(b['source_ids']):continue
|
||||
checked+=1;merged=junction(pa,polygons[j])
|
||||
if merged is None:continue
|
||||
members=[keys[i],keys[j]];family=hashlib.sha256(json.dumps(members).encode()).hexdigest()[:20]
|
||||
sources=sorted(set(a['source_ids'])|set(b['source_ids']))
|
||||
tiles=sorted(set(a['source_tiles'])|set(b['source_tiles']))
|
||||
before={f['id']:f for c in [a,b]for f in c['before']}
|
||||
# Existing evidence is retained by exact set union, with no hull,
|
||||
# padding, snapping, endpoint extension or reused historical map.
|
||||
f=feature(lift(merged),'road_marking',subtype='linear_marking',line_kind='observed-connected-junction',
|
||||
method=VERSION,source_ids=sources,source_tiles=tiles,family_id=family,observed_paint=True,
|
||||
standard_compliance='not_assessed',endpoint_authority='admitted-member-strips',
|
||||
member_ids=[c['after'][0]['id']for c in [a,b]],
|
||||
member_widths_m=[describe(p)['width']for p in [pa,polygons[j]]])
|
||||
output.append(dict(kind='whole-observed-terminal-junction',source_ids=sources,output_ids=[f['id']],
|
||||
before=[before[k]for k in sorted(before)],after=[f],source_tiles=tiles,
|
||||
source_views=[a['source_views'],b['source_views']],profile_mode='admitted-terminal-union',
|
||||
family_id=family,bounds_xy=merged.bounds,domain=None,atomic_family=False,
|
||||
seam_members=[a['after'][0],b['after'][0]],
|
||||
evidence=dict(member_configurations=members,member_admission=[a['evidence'],b['evidence']],
|
||||
exact_union=True,added_area_m2=0.,removed_area_m2=0.,junction_area_m2=pa.intersection(polygons[j]).area)))
|
||||
return output,dict(input_configurations=len(configurations),eligible_strips=len(records),
|
||||
intersecting_pairs=checked,junctions=len(output),recursive_combinations=False,additional_image_reads=0,
|
||||
overlap_threshold_unchanged=POLICY['max_overlap_m2'])
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Bounded local strip proposals from opposite edges of connected paint.
|
||||
|
||||
The binary foreground is supplied by the existing primary detector. No colour,
|
||||
visibility, road or final-admission threshold is changed. A connected parking
|
||||
shape can contain several thin bodies; its whole bounding box is not a body.
|
||||
"""
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
def branches(contour,binary,mpp):
|
||||
boundary=cv2.approxPolyDP(contour,.025/mpp,True)[:,0].astype(float)
|
||||
if len(boundary)<=4:return []
|
||||
starts=boundary;ends=np.roll(boundary,-1,axis=0);vectors=ends-starts
|
||||
lengths=np.linalg.norm(vectors,axis=1);keep=lengths*mpp>.26
|
||||
starts,ends,lengths,vectors=starts[keep],ends[keep],lengths[keep],vectors[keep]
|
||||
if len(starts)<2:return []
|
||||
axes=vectors/lengths[:,None];candidates=[]
|
||||
# Each contour edge may support at most one opposite-side interpretation.
|
||||
# This bounds alternatives by observed boundary complexity, not a grid of
|
||||
# guessed angles/widths/positions or a list of previously missed objects.
|
||||
for i,(a,b,u)in enumerate(zip(starts,ends,axes)):
|
||||
n=np.array([-u[1],u[0]]);best=None
|
||||
alignment=axes@u
|
||||
for j in np.flatnonzero(alignment<-np.cos(np.deg2rad(8))):
|
||||
if j==i:continue
|
||||
q=np.array([starts[j],ends[j]])-a;t=q@u;offset=q@n
|
||||
width=abs(float(np.mean(offset)))
|
||||
if not .045<width*mpp<.45:continue
|
||||
if np.ptp(offset)*mpp>.045:continue
|
||||
lo=max(0.,float(t.min()));hi=min(lengths[i],float(t.max()))
|
||||
length=(hi-lo)*mpp
|
||||
if not .26<length<65 or length/(width*mpp)<=2.:continue
|
||||
center=(lo+hi)/2*u+a+np.mean(offset)/2*n
|
||||
half_u=(hi-lo)/2*u;half_n=width/2*n
|
||||
box=np.array([center-half_u-half_n,center+half_u-half_n,center+half_u+half_n,center-half_u+half_n])
|
||||
# Same .48 foreground occupancy gate as the original component
|
||||
# proposal, evaluated on this measured body, not on its parent.
|
||||
low=np.floor(box.min(0)).astype(int);high=np.ceil(box.max(0)).astype(int)+1
|
||||
low=np.maximum(low,0);high=np.minimum(high,[binary.shape[1],binary.shape[0]])
|
||||
if np.any(high<=low):continue
|
||||
mask=np.zeros((high[1]-low[1],high[0]-low[0]),np.uint8)
|
||||
cv2.fillConvexPoly(mask,np.rint(box-low).astype('int32'),1)
|
||||
fill=float(binary[low[1]:high[1],low[0]:high[0]][mask>0].mean())
|
||||
if fill<=.48:continue
|
||||
score=(length,fill,-width,-int(j))
|
||||
if best is None or score>best[0]:best=(score,box,tuple(sorted((i,int(j)))))
|
||||
if best is not None:candidates.append(best)
|
||||
unique={pair:(score,box)for score,box,pair in candidates}
|
||||
return [unique[pair][1]for pair in sorted(unique)]
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Carry existing observations to preplanned support views, without inference.
|
||||
|
||||
Vehicle exclusion is the maximum across covering source views; unknown is
|
||||
blocked. This is the same conservative transfer used by the former coverage
|
||||
renderer, now attached to the fixed initial acquisition instead of a rescue.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import numpy as np,cv2
|
||||
from fit_scene import world,project
|
||||
|
||||
def carry(survey,evidence,layers,run_root):
|
||||
manifest_path=Path(run_root)/'observation-coverage.json'
|
||||
if not manifest_path.exists():return
|
||||
manifest=json.loads(manifest_path.read_text())
|
||||
if not manifest['complete']:raise ValueError('Coverage acquisition incomplete')
|
||||
originals=[t for t in json.loads((survey/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in originals]);records=[]
|
||||
for tile in manifest['tiles']:
|
||||
name=tile['id'];center=np.mean(tile['bounds_xy'],axis=0)
|
||||
with np.load(survey/name/'top.geometry.npz')as z:g=dict(z)
|
||||
yy,xx=np.mgrid[:1200,:1200];points=world(np.c_[xx.ravel(),yy.ravel()],g)
|
||||
covered=np.zeros(len(points),bool);normal={};ground={};paint={};sources=[]
|
||||
for i,source in enumerate(originals):
|
||||
if abs(centers[i]-center).max()>65:continue
|
||||
sid=source['id']
|
||||
with np.load(survey/sid/'top.geometry.npz')as z:sg=dict(z)
|
||||
uv=project(points,sg).astype('float32');valid=(uv.min(1)>=0)&(uv.max(1)<1199)
|
||||
ids=np.flatnonzero(valid)
|
||||
if not len(ids):continue
|
||||
sources.append(sid);covered[ids]=True
|
||||
for path,target in [(evidence/(sid+'.normal.npz'),normal),(evidence/(sid+'.ground.npz'),ground),(layers/(sid+'.npz'),paint)]:
|
||||
with np.load(path)as data:
|
||||
for key in data.files:
|
||||
plane=target.setdefault(key,np.zeros(len(points),np.float32));a=data[key].astype('float32')
|
||||
vals=np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).ravel()for b in np.array_split(uv[ids],max(1,int(np.ceil(len(ids)/20000))))])
|
||||
plane[ids]=np.maximum(plane[ids],vals)
|
||||
if not normal:raise ValueError('Support view has no existing semantic observation')
|
||||
normal['vehicle'][~covered]=1.;ground['vehicle'][~covered]=1.
|
||||
for target,path in [(normal,evidence/(name+'.normal.npz')),(ground,evidence/(name+'.ground.npz')),(paint,layers/(name+'.npz'))]:
|
||||
np.savez_compressed(path,**{k:v.reshape(1200,1200).astype('float16')for k,v in target.items()})
|
||||
records.append(dict(tile=name,source_tiles=sources,unknown_pixels=int((~covered).sum())))
|
||||
(Path(run_root)/'coverage-semantics.json').write_text(json.dumps(dict(inference_calls=0,
|
||||
policy='maximum existing observations; unknown vehicle footprint blocked',records=records),indent=2))
|
||||
@@ -0,0 +1,59 @@
|
||||
import numpy as np, cv2
|
||||
from scipy.optimize import least_squares
|
||||
from shapely.geometry import LineString
|
||||
def rectangle_info(p):
|
||||
rect=cv2.minAreaRect(np.asarray(p[:,:2],np.float32));box=cv2.boxPoints(rect).astype(float);edges=np.roll(box,-1,axis=0)-box;j=np.argmax(np.linalg.norm(edges,axis=1));u=edges[j]/np.linalg.norm(edges[j]);theta=np.arctan2(u[1],u[0]);u=np.array([np.cos(theta),np.sin(theta)]);v=np.array([-u[1],u[0]])
|
||||
return box,np.mean(box,axis=0),u,v
|
||||
|
||||
def joint_rectangles(observations):
|
||||
"""One family: parallel rectangles with shared width and aligned endpoints.
|
||||
|
||||
Optimise angle, end position/slope, length/length-slope, width and stripe
|
||||
centres together. Sloping group ends are admitted without shearing a stripe.
|
||||
The input remains a set of observations; no unsupported stripe is generated.
|
||||
"""
|
||||
angles=np.array([np.arctan2(o['u'][1],o['u'][0]) for o in observations]);theta=.5*np.arctan2(np.sin(2*angles).sum(),np.cos(2*angles).sum());origin=np.mean([o['center'] for o in observations],axis=0)
|
||||
u=np.array([np.cos(theta),np.sin(theta)]);v=np.array([-u[1],u[0]])
|
||||
# Use edge points rather than minimum rectangles as residual observations.
|
||||
ps=[(o['points'][:,:2]-origin) for o in observations];uv=[np.column_stack([p@u,p@v]) for p in ps]
|
||||
centers=np.array([np.mean([a[:,1].min(),a[:,1].max()]) for a in uv]);lo=np.array([np.quantile(a[:,0],.02) for a in uv]);hi=np.array([np.quantile(a[:,0],.98) for a in uv]);widths=np.array([a[:,1].max()-a[:,1].min() for a in uv])
|
||||
line=np.polyfit(centers,lo,1);length=np.polyfit(centers,hi-lo,1);x0=np.r_[theta,line[1],line[0],length[1],length[0],np.median(widths),centers]
|
||||
lower=x0-np.r_[np.deg2rad(8),.5,.2,.7,.2,.2,np.full(len(centers),.3)];upper=x0+np.r_[np.deg2rad(8),.5,.2,.7,.2,.2,np.full(len(centers),.3)];lower[3]=max(lower[3],.5);lower[5]=max(lower[5],.15)
|
||||
def boundary_residual(x):
|
||||
u=np.array([np.cos(x[0]),np.sin(x[0])]);v=np.array([-u[1],u[0]]);pieces=[]
|
||||
for j,p in enumerate(ps):
|
||||
t=p@u;s=p@v;vc=x[6+j];left=x[1]+x[2]*vc;right=left+x[3]+x[4]*vc
|
||||
# Signed distance to the exact rectangle boundary; corners remain 90 degrees.
|
||||
dx=np.maximum(left-t,t-right);dy=np.abs(s-vc)-x[5]/2
|
||||
sdf=np.hypot(np.maximum(dx,0),np.maximum(dy,0))+np.minimum(np.maximum(dx,dy),0)
|
||||
pieces.extend(sdf)
|
||||
return np.array(pieces)
|
||||
# Each primary observation is an oriented rectangle. Associate its four
|
||||
# corners with its measured end/side once, before optimization. A nearest-edge
|
||||
# SDF switches branches at every corner and can stall despite a tiny residual.
|
||||
# The original boundary-distance gate remains the independent final metric.
|
||||
fit_points=[];assignments=[]
|
||||
for observation,p in zip(observations,ps):
|
||||
q=p[:-1] if len(p)>1 and np.array_equal(p[0],p[-1]) else p
|
||||
if len(q)!=4:raise ValueError('Crossing fit expects four measured rectangle corners')
|
||||
axis=np.asarray(observation['u'],float)
|
||||
if axis@u<0:axis=-axis
|
||||
normal=np.array([-axis[1],axis[0]])
|
||||
t=q@axis;s=q@normal
|
||||
fit_points.append(q);assignments.append((t>(t.min()+t.max())/2,s>(s.min()+s.max())/2))
|
||||
def residual(x):
|
||||
axis=np.array([np.cos(x[0]),np.sin(x[0])]);normal=np.array([-axis[1],axis[0]])
|
||||
pieces=[]
|
||||
for j,(p,(right_side,upper_side))in enumerate(zip(fit_points,assignments)):
|
||||
vc=x[6+j];left=x[1]+x[2]*vc;right=left+x[3]+x[4]*vc
|
||||
pieces.extend(p@axis-np.where(right_side,right,left))
|
||||
pieces.extend(p@normal-(vc+np.where(upper_side,x[5]/2,-x[5]/2)))
|
||||
return np.asarray(pieces)
|
||||
fit=least_squares(residual,x0,bounds=(lower,upper),loss='soft_l1',f_scale=.07,ftol=1e-6,xtol=1e-6,gtol=1e-6,max_nfev=300)
|
||||
x=fit.x;u=np.array([np.cos(x[0]),np.sin(x[0])]);v=np.array([-u[1],u[0]]);result=[]
|
||||
for j,o in enumerate(observations):
|
||||
vc=x[6+j];lo=x[1]+x[2]*vc;hi=lo+x[3]+x[4]*vc;w=x[5]/2
|
||||
uv=np.array([[lo,vc-w],[hi,vc-w],[hi,vc+w],[lo,vc+w],[lo,vc-w]])
|
||||
p=origin+uv[:,0,None]*u+uv[:,1,None]*v;line=LineString(p)
|
||||
result.append(dict(id=o['id'],points=p,fit_p95_m=float(np.quantile([line.distance(__import__('shapely').geometry.Point(q)) for q in o['points'][::3,:2]],.95))))
|
||||
return result,dict(angle_degrees=float(np.rad2deg(x[0])),width_m=float(x[5]),stripes=len(result),optimizer_success=bool(fit.success),optimizer_status=int(fit.status),optimizer_evaluations=int(fit.nfev),worst_stripe_p95_m=max(r['fit_p95_m'] for r in result),parameters=x.tolist(),origin=origin.tolist(),boundary_residual_p95_m=float(np.quantile(np.abs(boundary_residual(x)),.95)))
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
"""Make fresh complete-arrow hypotheses from whole-coverage SAM observations."""
|
||||
from pathlib import Path
|
||||
import json,time,hashlib,os
|
||||
import numpy as np,cv2,shapely
|
||||
from PIL import Image
|
||||
from shapely.geometry import shape,mapping
|
||||
from component_targets import vector
|
||||
from glyph_targets import targets
|
||||
from glyph_registration import fit_glyphs
|
||||
from recall_extent import semantic_extent,semantic_recall
|
||||
|
||||
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
root=Path('/symbolplan');out=Path('/out');start=time.monotonic();cv2.setNumThreads(2)
|
||||
manifest=root/'symbol-patches.json';patches={p['id']:p for p in json.loads(manifest.read_text())['patches']}
|
||||
semantics=json.loads((root/'symbol-semantics.json').read_text());assert semantics['patch_manifest_sha256']==sha(manifest)
|
||||
rows=[];seen=[];diagnostics=[];pending=[]
|
||||
for rec in semantics['records']:
|
||||
if not rec['detections'] or 1 not in rec['classes']:continue
|
||||
p=patches[rec['id']];image=root/'symbol-patches'/(p['id']+'.png');npz=root/'symbol-masks'/(p['id']+'.npz')
|
||||
assert sha(image)==p['sha256'] and sha(npz)==rec['sha256']
|
||||
with np.load(npz)as z:
|
||||
regions=[(i,vector(m,p))for i,(m,s,c)in enumerate(zip(z['masks'],z['scores'],z['classes']))if c==1 and s>=.50]
|
||||
proposals=targets(np.asarray(Image.open(image).convert('RGB')),p,z['masks'],z['scores'],z['classes'])
|
||||
for d in proposals:
|
||||
if d['ci']!=1:continue
|
||||
target=d['target'];region=d['region']
|
||||
if any(target.symmetric_difference(q).area/max(target.area,q.area)<.10 for q in seen):continue
|
||||
seen.append(target);extent,mask_ids=semantic_extent(region,regions)
|
||||
length,width=sorted(cv2.minAreaRect(np.asarray(extent.convex_hull.exterior.coords,'float32'))[1],reverse=True)
|
||||
if not 1.0<=length<=10.5 or not .25<=width<=4.0:continue
|
||||
pending.append(dict(patch=p['id'],masks=d['masks'],semantic_score=d['score'],target=target,region=region,extent=extent))
|
||||
# Standard spatial non-maximum suppression runs before expensive shape fitting.
|
||||
# Retain two distinct target interpretations for each semantic object (typically
|
||||
# silhouette and observed paint), not dozens of overlapping-window copies.
|
||||
groups=[]
|
||||
for d in sorted(pending,key=lambda x:-(x['semantic_score']*x['extent'].area)):
|
||||
matches=[g for g in groups if d['extent'].intersection(g[0]['extent']).area/max(d['extent'].union(g[0]['extent']).area,1e-9)>.45]
|
||||
if not matches:groups.append([d]);continue
|
||||
g=matches[0]
|
||||
if len(g)<2 and all(d['target'].symmetric_difference(v['target']).area/max(d['target'].union(v['target']).area,1e-9)>.12 for v in g):g.append(d)
|
||||
print('SPATIAL_GROUPS',len(groups),'RAW',len(pending),flush=True)
|
||||
for group in groups:
|
||||
for d in group:
|
||||
target=d['target'];region=d['region'];extent=d['extent'];fits=fit_glyphs(target);converted=[]
|
||||
for f in fits:
|
||||
q=f['polygon'];converted.append(dict(**{k:v for k,v in f.items()if k!='polygon'},extent_recall=semantic_recall(q,extent),containment=q.intersection(region.buffer(.20)).area/max(q.area,1e-9)))
|
||||
rows.append(dict(index=len(rows),patch=d['patch'],masks=d['masks'],semantic_score=d['semantic_score'],target=mapping(target),region=mapping(region),extent=mapping(extent),fits=converted))
|
||||
print('HYPOTHESIS',len(rows),d['patch'],len(fits),flush=True)
|
||||
(out/'arrow-gates.json').write_text(json.dumps(rows,indent=2));(out/'discovery-report.json').write_text(json.dumps(dict(patches=len(patches),candidates=len(rows),seconds=time.monotonic()-start,semantic_sha256=sha(root/'symbol-semantics.json'),manual_rois=[]),indent=2))
|
||||
@@ -0,0 +1,55 @@
|
||||
"""One deterministic native-image traversal; no prior map or missed-object input."""
|
||||
from pathlib import Path
|
||||
import json,time,hashlib
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import mapping,shape
|
||||
from scipy.ndimage import distance_transform_edt
|
||||
from layer_common import sample,feature
|
||||
from fit_scene import world
|
||||
from search_views import SearchViews
|
||||
from line_reconstruction import extract,dedup
|
||||
from search_rules import pack
|
||||
from paint_observations import collect as paint_observations
|
||||
from catalog_observations import collect as catalog_observations
|
||||
from compact_observations import collect as compact_observations
|
||||
from crossing_discovery import primitives
|
||||
|
||||
|
||||
def main():
|
||||
O=Path('/out');start=time.monotonic();cv2.setNumThreads(3);cv2.setRNGSeed(2026)
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
|
||||
tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
views=SearchViews(tiles,labels,low,high,None)
|
||||
lines=[];paint=[];crossbars=[];glyphs=[];compact=[];seeds=[];reports=[];sources={}
|
||||
from observation_tiles import ordered_tiles
|
||||
workers=int(__import__('os').environ.get('OBSERVATION_WORKERS','4'))
|
||||
for row in ordered_tiles(views.tiles,workers):
|
||||
lines.extend(row['lines']);paint.extend(row['paint']);crossbars.extend(row['crossbars'])
|
||||
glyphs.extend(row['glyphs']);compact.extend(row['compact']);seeds.extend(row['seeds'])
|
||||
reports.append(row['report']);sources[row['report']['tile']]=row['source']
|
||||
print('OBSERVATION',json.dumps(reports[-1]),flush=True)
|
||||
(O/'observation-progress.json').write_text(json.dumps(reports))
|
||||
|
||||
from stroke_inventory import deduplicate as indexed_line_dedup
|
||||
|
||||
def suppress(records,geometry,threshold):
|
||||
ordered=sorted(records,key=lambda r:-geometry(r).area);geometries=[geometry(r)for r in ordered]
|
||||
if not geometries:return []
|
||||
tree=shapely.STRtree(geometries);accepted=set();result=[]
|
||||
for i,(r,p)in enumerate(zip(ordered,geometries)):
|
||||
if any(j in accepted and p.intersection(geometries[j]).area/max(min(p.area,geometries[j].area),1e-9)>threshold for j in tree.query(p,predicate='intersects')):continue
|
||||
accepted.add(i);result.append(r)
|
||||
return result
|
||||
|
||||
lines=indexed_line_dedup(lines);glyphs=suppress(glyphs,lambda r:shape(r['geometry']),.85)
|
||||
seeds=suppress(seeds,lambda p:p,.5)
|
||||
# IDs and search inputs depend only on this observation run; there is no map seed.
|
||||
(O/'search-proposals.json').write_text(json.dumps(dict(lines=[pack(r)for r in lines],source_fields_sha256=hashlib.sha256(Path('/evidence_plan/fields.npz').read_bytes()).hexdigest(),glyphs=[],tile_reports=reports,source='systematic-primary-native-observations',manual_rois=[]),allow_nan=False))
|
||||
(O/'catalog-proposals.json').write_text(json.dumps(dict(glyphs=glyphs,source_fields_sha256=hashlib.sha256(Path('/evidence_plan/fields.npz').read_bytes()).hexdigest(),tile_reports=reports,source='systematic-primary-native-observations',manual_rois=[]),allow_nan=False))
|
||||
(O/'compact-seeds.json').write_text(json.dumps(compact))
|
||||
(O/'crossing-seeds.json').write_text(json.dumps([feature(p,'road_marking',subtype='crosswalk')for p in seeds]))
|
||||
(O/'observations.json').write_text(json.dumps(dict(paint=paint,crossbars=crossbars,source_semantics=sources,manual_rois=[],existing_map_input=False),allow_nan=False))
|
||||
(O/'observation-report.json').write_text(json.dumps(dict(tiles=len(reports),seconds=time.monotonic()-start,linear=len(lines),catalog=len(glyphs),paint=len(paint),crossbars=len(crossbars),compact=len(compact),crossing_seeds=len(seeds),existing_map_input=False,full_scene_traversals=1,workers=workers,maximum_pending_tiles=workers*2,detector_seconds={k:sum(r['detectors'][k]for r in reports)for k in reports[0]['detectors']}),indent=2))
|
||||
print('OBSERVATIONS_COMPLETE',time.monotonic()-start,flush=True)
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Own measured bodies and their intervening gaps within the current run."""
|
||||
import numpy as np
|
||||
from interval_profiles import rectangle
|
||||
|
||||
|
||||
class FamilyOwnership:
|
||||
def __init__(self):
|
||||
self.members={}
|
||||
self.owners={}
|
||||
|
||||
def allows(self,ids):
|
||||
ids=set(ids)
|
||||
return all(self.members[self.owners[i]].issubset(ids)for i in ids if i in self.owners)
|
||||
|
||||
def committed(self,ids,features,joint=False):
|
||||
for ident in ids:
|
||||
owner=self.owners.pop(ident,None)
|
||||
if owner is not None:
|
||||
self.members[owner].discard(ident)
|
||||
if not self.members[owner]:del self.members[owner]
|
||||
if joint:
|
||||
members={f['id']for f in features}
|
||||
owner=tuple(sorted(members));self.members[owner]=members
|
||||
for ident in members:self.owners[ident]=owner
|
||||
|
||||
|
||||
def admitted_domain(row,polygons):
|
||||
"""Reserve the committed span; rejected bodies do not acquire ownership."""
|
||||
coordinates=np.concatenate([np.asarray(p.exterior.coords)for p in polygons])
|
||||
longitudinal=(coordinates-row['origin'])@row['axis']
|
||||
domain_coordinates=np.asarray(row['domain'].exterior.coords)
|
||||
normal=np.array([-row['axis'][1],row['axis'][0]])
|
||||
transverse=(domain_coordinates-row['origin'])@normal
|
||||
return row['domain'].intersection(rectangle(row['origin'],row['axis'],float(longitudinal.min()),float(longitudinal.max()),float(np.ptp(transverse)),float((transverse.min()+transverse.max())/2)))
|
||||
|
||||
|
||||
def unowned_bodies(polygons,domains):
|
||||
"""A competing hypothesis cannot fill an already measured dark gap."""
|
||||
return [p for p in polygons if not any(p.intersection(d).area>.005 for d in domains)]
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Whole measured stroke ownership; retain positive paint during replacement."""
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import shape
|
||||
from marking_rules import plan_replacement,validate_removed,isolated_addition,POLICY
|
||||
|
||||
|
||||
def replacement(candidate,current,readers):
|
||||
p=candidate['polygons'][0]
|
||||
proposal={**candidate,'domain':p.buffer(POLICY['max_join_gap_m'])}
|
||||
plan=plan_replacement(proposal,current)
|
||||
if plan is None:return None,dict(reason='incompatible-ownership')
|
||||
ids,polygons=plan
|
||||
old=shapely.union_all([shapely.force_2d(shape(current[i]['geometry']))for i in ids])
|
||||
removed=old.difference(p.buffer(POLICY['retained_paint_tolerance_m']))
|
||||
if not removed.is_empty:
|
||||
axis=candidate['axis'];normal=np.array([-axis[1],axis[0]])
|
||||
transverse=(shapely.get_coordinates(removed)-candidate['origin'])@normal
|
||||
if np.max(abs(transverse))>.7:return None,dict(reason='removed-paint-outside-measurement')
|
||||
okay,evidence=validate_removed(old,p,candidate,readers)
|
||||
if not okay:return None,dict(reason='positive-or-unobserved-removed-paint',views=evidence)
|
||||
rest={i:f for i,f in current.items()if i not in ids}
|
||||
if not isolated_addition(p,rest):return None,dict(reason='unresolved-neighbor-seam')
|
||||
return ids,dict(reason='retained-or-two-view-dark',views=evidence)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Sample fixed tiles before seeing any object geometry or paint score."""
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from fit_scene import project
|
||||
from layer_common import sample
|
||||
from object_evidence import CELL, HALO, TILE, grid
|
||||
|
||||
|
||||
class FixedObservations:
|
||||
def __init__(self, views):
|
||||
self.views = views
|
||||
self.calls = 0
|
||||
self._tiles = lru_cache(maxsize=1024)(self._sample)
|
||||
|
||||
def __call__(self, key):
|
||||
return self._tiles(key)
|
||||
|
||||
# Boolean evidence only (~34 KiB/tile), not decoded images. Bounded to
|
||||
# ~34 MiB so paired packaging experiments reuse exactly the same samples.
|
||||
def _sample(self, key):
|
||||
self.calls += 1
|
||||
_, points = grid(key, halo=True)
|
||||
n, h = round(TILE / CELL), round(HALO / CELL)
|
||||
size = n + 2 * h
|
||||
lo = np.array(key) * TILE - HALO
|
||||
hi = np.array(key) * TILE + TILE + HALO
|
||||
corners = np.array([[lo[0], lo[1]], [lo[0], hi[1]], [hi[0], lo[1]], [hi[0], hi[1]]])
|
||||
center = (lo + hi) / 2
|
||||
eligible = []
|
||||
for i, tile in enumerate(self.views.tiles):
|
||||
uv = project(corners, self.views.geometry(tile["id"]))
|
||||
if uv.min() >= 20 and uv.max() < 1180:
|
||||
eligible.append((float(np.linalg.norm(center - self.views.centers[i])), i))
|
||||
result = {k: np.zeros((2, n * n), bool) for k in ["physical", "road", "paint"]}
|
||||
result["views"] = []
|
||||
for rank, (_, i) in enumerate(sorted(eligible)[:2]):
|
||||
name = self.views.tiles[i]["id"]
|
||||
g = self.views.geometry(name)
|
||||
rgb, vehicle = self.views.inputs(name)
|
||||
uv = project(points, g).astype("float32")
|
||||
native = (uv + 0.5) * (rgb.shape[0] / 1200) - 0.5
|
||||
|
||||
def read(a, coordinates):
|
||||
return cv2.remap(
|
||||
a,
|
||||
coordinates[:, 0].reshape(size, size),
|
||||
coordinates[:, 1].reshape(size, size),
|
||||
cv2.INTER_LINEAR,
|
||||
)
|
||||
|
||||
colors = read(rgb, native)
|
||||
gray = cv2.cvtColor(colors, cv2.COLOR_RGB2GRAY)
|
||||
bg = cv2.morphologyEx(
|
||||
gray, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (31, 31))
|
||||
)
|
||||
hsv = cv2.cvtColor(colors, cv2.COLOR_RGB2HSV)
|
||||
paint = (
|
||||
(gray.astype(float) - bg > 15)
|
||||
& (gray > 100)
|
||||
& ((hsv[:, :, 1] < 100) | ((hsv[:, :, 0] > 12) & (hsv[:, :, 0] < 36)))
|
||||
)
|
||||
near = (
|
||||
cv2.dilate(
|
||||
paint.astype("uint8"), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
)
|
||||
> 0
|
||||
)
|
||||
physical = (read(g["alpha"].astype("float32"), uv) >= 0.65) & (read(vehicle, uv) < 0.2)
|
||||
road = (
|
||||
sample(self.views.labels, points, self.views.low, self.views.high) == 1
|
||||
).reshape(size, size)
|
||||
for k, value in [("physical", physical), ("road", road), ("paint", near)]:
|
||||
result[k][rank] = value[h : h + n, h : h + n].ravel()
|
||||
result["views"].append(name)
|
||||
for k in ["physical", "road", "paint"]:
|
||||
result[k].setflags(write=False)
|
||||
return result
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Fixed structural observers plus a complete initial paint coverage plan.
|
||||
|
||||
The bootstrap structural camera set defines the road/facade evidence. Coverage
|
||||
optimization may add distinct paint observers; it cannot replace these cameras
|
||||
or change their bounds, identity or ordering. All cameras are planned before
|
||||
rendering, without an existing map, missed-object list or recovery pass.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import copy,json
|
||||
import numpy as np
|
||||
from observation_coverage import POLICY
|
||||
|
||||
|
||||
def targets(survey,index):
|
||||
points=[]
|
||||
for tile in index['tiles']:
|
||||
path=Path(survey)/tile['id']/'surface-atlas.npz'
|
||||
if not path.is_file():continue
|
||||
with np.load(path)as z:
|
||||
depth=z['z'];cell=float(z['cell_m']);low=z['bounds'][0]
|
||||
stride=max(1,round(POLICY['sample_m']/cell))
|
||||
rr,cc=np.where(np.isfinite(depth[::stride,::stride]));rr*=stride;cc*=stride
|
||||
points.append(np.c_[low[0]+(cc+.5)*cell,low[1]+(depth.shape[0]-rr-.5)*cell])
|
||||
if not points:raise ValueError('Missing bootstrap observations')
|
||||
return np.unique(np.concatenate(points),axis=0)
|
||||
|
||||
|
||||
def counts_at(points,centers):
|
||||
counts=np.zeros(len(points),np.int32)
|
||||
for center in centers:counts+=(abs(points-center).max(1)<=POLICY['usable_half_width_m'])
|
||||
return counts
|
||||
|
||||
|
||||
def unique_centers(centers):
|
||||
chosen=[]
|
||||
for c in np.unique(np.asarray(centers,float).reshape(-1,2),axis=0):
|
||||
if not chosen or np.all(np.max(abs(np.asarray(chosen)-c),axis=1)>=1e-6):chosen.append(c)
|
||||
return np.asarray(chosen,float).reshape(-1,2)
|
||||
|
||||
|
||||
class CoverageBudgetExceeded(ValueError):pass
|
||||
|
||||
|
||||
def greedy(points,initial,candidates,limit):
|
||||
counts=counts_at(points,initial);selected=list(np.asarray(initial,float).reshape(-1,2))
|
||||
pool=np.asarray([c for c in candidates if not len(initial) or not np.any(np.max(abs(np.asarray(initial)-c),axis=1)<1e-6)],float).reshape(-1,2)
|
||||
# Exact same <= footprint predicate as the original planner. Each Boolean
|
||||
# row is packed once instead of rebuilding a candidate×point×XY tensor on
|
||||
# every iteration. Storage is O(cameras*targets/8), not float64 XYZ cubes.
|
||||
masks=[int.from_bytes(np.packbits(abs(points-c).max(1)<=POLICY['usable_half_width_m'],bitorder='little').tobytes(),'little')for c in pool]
|
||||
available=np.ones(len(pool),bool)
|
||||
while np.any(counts<POLICY['required_views']):
|
||||
if len(selected)>=limit:raise CoverageBudgetExceeded('Initial observation budget exceeded')
|
||||
needed=int.from_bytes(np.packbits(counts<POLICY['required_views'],bitorder='little').tobytes(),'little')
|
||||
gains=[(mask&needed).bit_count()if available[i]else -1 for i,mask in enumerate(masks)]
|
||||
if not gains or max(gains)<=0:raise CoverageBudgetExceeded('Cannot provide distinct footprints')
|
||||
i=int(np.argmax(gains));c=pool[i];selected.append(c);available[i]=False
|
||||
counts+=(abs(points-c).max(1)<=POLICY['usable_half_width_m'])
|
||||
return np.asarray(selected,float),counts
|
||||
|
||||
|
||||
def minimum_cover(points,pool,incumbent,seconds=15.,fixed=()):
|
||||
"""Bounded binary covering problem; equivalent rows retain every sample."""
|
||||
import time
|
||||
from scipy.optimize import milp,Bounds,LinearConstraint
|
||||
from scipy.sparse import csc_matrix,vstack
|
||||
start=time.monotonic()
|
||||
cover=np.column_stack([abs(points-c).max(1)<=POLICY['usable_half_width_m'] for c in pool])
|
||||
packed=np.packbits(cover,axis=1,bitorder='little')
|
||||
_,indices=np.unique(packed,axis=0,return_index=True)
|
||||
matrix=vstack([csc_matrix(cover[indices].astype(float)),csc_matrix(np.ones((1,len(pool))))],format='csc')
|
||||
fixed=unique_centers(fixed)
|
||||
lower=np.zeros(len(pool))
|
||||
for center in fixed:
|
||||
ids=np.flatnonzero(np.max(abs(pool-center),axis=1)<1e-6)
|
||||
if len(ids)!=1:raise ValueError('Structural camera missing or duplicated in coverage pool')
|
||||
lower[ids[0]]=1.
|
||||
result=milp(np.ones(len(pool)),integrality=np.ones(len(pool)),bounds=Bounds(lower,1.),
|
||||
constraints=LinearConstraint(matrix,np.r_[np.full(len(indices),POLICY['required_views']),0.],np.r_[np.full(len(indices),np.inf),len(incumbent)]),
|
||||
options=dict(time_limit=seconds,mip_rel_gap=0.))
|
||||
selected=incumbent;state='feasible-greedy-fallback'
|
||||
if result.x is not None and np.isfinite(result.x).all():
|
||||
x=np.rint(result.x)
|
||||
proposed=pool[x>.5]
|
||||
if np.max(abs(result.x-x))<1e-5 and len(proposed)<=len(incumbent) and np.all(x>=lower) and np.all(counts_at(points,proposed)>=POLICY['required_views']):
|
||||
selected=proposed;state='optimal'if result.status==0 else 'feasible-at-limit'
|
||||
bound=getattr(result,'mip_dual_bound',None)
|
||||
return selected,dict(status=state,solver_status=int(result.status),seconds=time.monotonic()-start,
|
||||
camera_candidates=len(pool),original_sample_constraints=len(points),equivalent_sample_constraints=len(indices),
|
||||
lower_bound=float(bound)if bound is not None and np.isfinite(bound)else None,
|
||||
greedy_views=len(incumbent),selected_views=len(selected))
|
||||
|
||||
|
||||
def choose(points,original,optimize=True):
|
||||
points=np.unique(np.asarray(points,float).reshape(-1,2),axis=0)
|
||||
original=unique_centers(original)
|
||||
if not len(points)or not np.isfinite(points).all()or not np.isfinite(original).all():raise ValueError('Invalid observed coverage geometry')
|
||||
grid=np.unique(np.round(points/POLICY['camera_grid_m'])*POLICY['camera_grid_m'],axis=0)
|
||||
limit=len(original)+POLICY['max_additional_views']
|
||||
legacy,legacy_counts=greedy(points,original,grid,limit)
|
||||
pool=unique_centers(np.r_[grid,original])
|
||||
selected,counts,method=legacy,legacy_counts,'fixed-structure-complete-cover'
|
||||
solver=None
|
||||
if optimize:
|
||||
selected,solver=minimum_cover(points,pool,selected,fixed=original)
|
||||
counts=counts_at(points,selected)
|
||||
if len(selected)<len(legacy):method='fixed-structure-joint-cover'
|
||||
assert np.all(counts>=POLICY['required_views'])
|
||||
assert len(unique_centers(selected))==len(selected)
|
||||
assert len(selected)<=len(legacy)
|
||||
assert all(np.any(np.max(abs(selected-c),axis=1)<1e-6)for c in original)
|
||||
return selected,dict(target_samples=len(points),initial_two_view_samples=int((counts_at(points,original)>=POLICY['required_views']).sum()),planned_two_view_samples=int((counts>=POLICY['required_views']).sum()),minimum_views=int(counts.min()),bootstrap_views=len(original),legacy_complete_views=len(legacy),planned_views=len(selected),plan_method=method,solver=solver,unknown_ground_inferred=False,object_input=False,additional_views=len(selected)-len(original),structural_views=len(original),structural_cameras_preserved=True)
|
||||
|
||||
|
||||
def plan(survey,index,selection=None):
|
||||
points=targets(survey,index)
|
||||
originals=np.array([np.mean(t['bounds_xy'],axis=0)for t in index['tiles']])
|
||||
centers,report=choose(points,originals) if selection is None else selection
|
||||
if not all(np.any(np.max(abs(centers-c),axis=1)<1e-6)for c in originals):raise ValueError('Coverage plan replaced a structural camera')
|
||||
tiles=[];jobs={}
|
||||
additions=[c for c in centers if not np.any(np.max(abs(originals-c),axis=1)<1e-6)]
|
||||
for i,center in enumerate(additions):
|
||||
nearest=index['tiles'][int(np.argmin(np.linalg.norm(originals-center,axis=1)))]
|
||||
job=copy.deepcopy(json.loads((Path(survey)/nearest['id']/'job.json').read_text()))
|
||||
name=f'primary-support-{i:03d}';bounds=[(center-30).tolist(),(center+30).tolist()]
|
||||
top=next(v for v in job['views']if v['id']=='top');delta=center-np.asarray(top['eye'][:2])
|
||||
top['eye'][:2]=center.tolist();top['target'][:2]=(np.asarray(top['target'][:2])+delta).tolist()
|
||||
job['bounds_xy']=bounds;jobs[name]=job
|
||||
tiles.append(dict(id=name,status='planned',bounds_xy=bounds,role='initial-two-view-support',center=center.tolist()))
|
||||
return tiles,jobs,dict(schema='missioncore.initial-observation-coverage/v2',structural_ids=[t['id']for t in index['tiles']],policy=POLICY,**report)
|
||||
@@ -0,0 +1,53 @@
|
||||
from pathlib import Path
|
||||
from collections import Counter
|
||||
import json,os,time,hashlib
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import shape,Polygon,LineString,mapping
|
||||
from shapely.ops import transform
|
||||
from scipy.ndimage import distance_transform_edt
|
||||
from layer_common import O,S,B,feature,parts,sample
|
||||
from fit_scene import world
|
||||
from plan_primitives import regularize_paint
|
||||
from frontage_chains import join_planes
|
||||
from shared_surface_edges import reconcile_features
|
||||
from paint_templates import fit_symbol
|
||||
from crosswalk_family import rectangle_info,joint_rectangles
|
||||
cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text());base=json.loads((O/'whole-map.json').read_text());tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
with np.load('/fullplan/fields.npz')as f:labels=f['labels'];height=f['z'];low,high=f['bounds'];cell=float(f['cell'])
|
||||
road=labels==1
|
||||
# Reconcile the accepted physical edges with the fresh coverage polygons.
|
||||
# Original labels remain evidence for downstream checks, never edited to fit.
|
||||
areas=[f for f in old['features']if f['properties']['class']=='pedestrian_area']
|
||||
boundaries=[f for f in base['features']if f['properties']['class']=='road_boundary']
|
||||
def classify(xy):
|
||||
return sample(labels,xy,low,high,cell=cell)
|
||||
areas,topology=reconcile_features(areas,boundaries,classify)
|
||||
walk=areas+[f for f in old['features']if f['properties']['class']=='pedestrian_boundary']
|
||||
(O/'surface-topology.json').write_text(json.dumps(topology,allow_nan=False))
|
||||
def lift(g):
|
||||
def project(x,y,z=None):return x,y,sample(height,np.c_[x,y],low,high)
|
||||
return transform(project,g)
|
||||
allfacades=[f for f in old['features']if f['properties']['class']=='building_facade'];rawfacades=[];rejected_facades=[]
|
||||
with np.load(O/'occluder-field.npz')as occ:vehicle_field=occ['vehicle']
|
||||
for item in allfacades:
|
||||
line=shapely.force_2d(shape(item['geometry']));p=np.array([line.interpolate(t).coords[0]for t in np.linspace(0,line.length,max(3,int(line.length/.2)))])
|
||||
fraction=float(np.mean(sample(vehicle_field,p,low,high)>.5))
|
||||
if line.length<12 and fraction>.35:rejected_facades.append(dict(source_id=item['id'],reason='vehicle-supported-vertical-plane',vehicle_fraction=fraction));continue
|
||||
rawfacades.append(item)
|
||||
(O/'rejected-facades.json').write_text(json.dumps(rejected_facades,indent=2))
|
||||
planes=[shapely.force_2d(shape(f['geometry']))for f in rawfacades]
|
||||
def facade_bridge_allowed(line,sources):
|
||||
novel=line.difference(shapely.union_all(sources).buffer(.2))
|
||||
for segment in parts(novel,'LineString'):
|
||||
if segment.length<.4:continue
|
||||
p=np.array([segment.interpolate(t).coords[0]for t in np.linspace(0,segment.length,max(3,int(segment.length/.2)))])
|
||||
if np.mean(sample(labels,p,low,high)==1)>.2:return False
|
||||
return True
|
||||
joined=join_planes(planes,offset=.45,gap=8.,bridge_validator=facade_bridge_allowed);facades=[]
|
||||
for p,ids in joined:
|
||||
facades.append(feature(lift(LineString(p)),'building_facade',method='huber-frontage-chain-with-bounded-infill',source_ids=[rawfacades[i]['id']for i in ids],closed_footprint=False,hidden_backs_invented=False,schematic_join=True))
|
||||
|
||||
result={**base,'schema_version':'missioncore.systematic-plan/v1','features':base['features']+walk+facades,'logical_layers':['roads','pedestrian_zones','buildings','road_markings'],'review_status':'unreviewed','surface_topology':topology}
|
||||
assert all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all() for f in result['features'])
|
||||
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
||||
(O/'structure-report.json').write_text(json.dumps(dict(facades=len(facades),manual_rois=[],paint_search=False,shared_edges=len(topology['edges']),shared_length_m=sum(shape(e['geometry']).length for e in topology['edges']),surface_assembly='shared-observed-edges',original_evidence_unchanged=True,seconds=time.monotonic()-start)))
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Compile typed conflicts and fixed evidence for admitted whole families."""
|
||||
from collections import defaultdict, Counter
|
||||
import hashlib,json,time
|
||||
import numpy as np,shapely
|
||||
from shapely.geometry import shape
|
||||
from marking_rules import isolated_addition,POLICY
|
||||
from joint_choice import choose
|
||||
|
||||
CELL=.05
|
||||
|
||||
def geom(f):return shapely.force_2d(shape(f['geometry']))
|
||||
|
||||
def cells(p):
|
||||
"""Fixed world lattice; sampling density cannot grow with hypothesis count."""
|
||||
result=set()
|
||||
for q in getattr(p,'geoms',[p]):
|
||||
lo=np.floor(np.array(q.bounds[:2])/CELL).astype(int)
|
||||
hi=np.ceil(np.array(q.bounds[2:])/CELL).astype(int)
|
||||
xx=np.arange(lo[0],hi[0]+1)
|
||||
for start in range(lo[1],hi[1]+1,32):
|
||||
yy=np.arange(start,min(start+32,hi[1]+1));x,y=np.meshgrid(xx,yy)
|
||||
mask=shapely.contains_xy(q,(x+.5)*CELL,(y+.5)*CELL)
|
||||
result.update(zip(x[mask].tolist(),y[mask].tolist()))
|
||||
return result
|
||||
|
||||
|
||||
def select(old,configurations,appearance):
|
||||
started=time.monotonic();base={f['id']:f for f in old['features']}
|
||||
nodes=[];payload={};geometry={};domains={};atoms={}
|
||||
for f in old['features']:
|
||||
if f['properties'].get('subtype')!='linear_marking':continue
|
||||
key='keep:'+f['id'];payload[key]=dict(after=[f],source_ids=[f['id']],atomic_family=False)
|
||||
nodes.append(dict(id=key,sources=[f['id']],cost=0.,incumbent=True))
|
||||
for transaction in configurations:
|
||||
identity=dict(sources=sorted(transaction['source_ids']),after=sorted(f['id'] for f in transaction['after']),kind=transaction['kind'])
|
||||
key=hashlib.sha256(json.dumps(identity,sort_keys=True).encode()).hexdigest()
|
||||
if key in payload:continue
|
||||
payload[key]=transaction
|
||||
nodes.append(dict(id=key,sources=transaction['source_ids'],cost=0.,incumbent=False))
|
||||
nodes.sort(key=lambda n:n['id'])
|
||||
for n in nodes:
|
||||
key=n['id'];t=payload[key]
|
||||
geometry[key]=shapely.union_all([geom(f) for f in t['after']])
|
||||
atoms[key]=cells(geometry[key])
|
||||
if t.get('domain'):domains[key]=shape(t['domain'])
|
||||
# Immutable observations from this run, before candidate assembly. Native
|
||||
# source records identify a positive sample. This ranking never admits
|
||||
# an object: all existing typed two-view gates ran before this function.
|
||||
observations=[r for r in appearance if r['properties'].get('source_tile')]
|
||||
polygons=[shape(r['geometry']) for r in observations]
|
||||
tree=shapely.STRtree(polygons);all_cells=sorted(set().union(*atoms.values())) if atoms else []
|
||||
positive=set()
|
||||
for start in range(0,len(all_cells),10000):
|
||||
chunk=all_cells[start:start+10000];xy=(np.asarray(chunk,float)+.5)*CELL
|
||||
pairs=tree.query(shapely.points(xy),predicate='intersects');sources=defaultdict(set)
|
||||
for pi,oi in zip(*pairs):sources[int(pi)].add(observations[int(oi)]['properties']['source_tile'])
|
||||
positive.update(chunk[i] for i,names in sources.items() if names)
|
||||
membership=defaultdict(list)
|
||||
complexity_scale=.25/max(1.,sum(1.+.01*len(payload[n['id']]['after']) for n in nodes))
|
||||
for n in nodes:
|
||||
key=n['id'];a=atoms[key];supported=a&positive
|
||||
for cell in supported:membership[cell].append(key)
|
||||
# Missing primary-mask evidence is UNKNOWN, not observed dark road.
|
||||
# Contradictions are enforced by the existing two-view admission gates.
|
||||
# Complexity is only a small tie-breaker below one metric sample.
|
||||
n['cost']=complexity_scale*(1.+.01*len(payload[key]['after']))
|
||||
conflicts=[];types=Counter();keys=[n['id'] for n in nodes]
|
||||
envelopes=[geometry[k].union(domains[k]) if k in domains else geometry[k] for k in keys]
|
||||
spatial=shapely.STRtree([p.buffer(POLICY['max_join_gap_m']) for p in envelopes])
|
||||
geometry_array=np.array([geometry[key] for key in keys],dtype=object)
|
||||
for i,key in enumerate(keys):
|
||||
neighbors=np.array([int(j) for j in spatial.query(envelopes[i]) if j>i],dtype=int)
|
||||
# The same GEOS intersection/area test, batched to avoid hundreds of
|
||||
# thousands of Python-to-GEOS calls on overlapping family subseries.
|
||||
overlap={}
|
||||
for start in range(0,len(neighbors),4096):
|
||||
ids=neighbors[start:start+4096]
|
||||
areas=shapely.area(shapely.intersection(geometry[key],geometry_array[ids]))
|
||||
overlap.update(zip(ids.tolist(),(areas>POLICY['max_overlap_m2']).tolist()))
|
||||
for j in neighbors:
|
||||
j=int(j)
|
||||
other=keys[j];a=payload[key];b=payload[other]
|
||||
# Fresh incumbent may contain overlapping provisional fragments;
|
||||
# retain it as a feasible fallback, never silently erase them.
|
||||
if key.startswith('keep:') and other.startswith('keep:'):continue
|
||||
reason=None
|
||||
if set(a['source_ids'])&set(b['source_ids']):reason='alternative-explanation'
|
||||
elif overlap[j]:reason='positive-paint-overlap'
|
||||
elif key in domains and other in domains and domains[key].intersection(domains[other]).area>POLICY['max_overlap_m2']:reason='incompatible-family-domain'
|
||||
elif key in domains and domains[key].intersection(geometry[other]).area>POLICY['max_overlap_m2']:reason='family-gap-ownership'
|
||||
elif other in domains and domains[other].intersection(geometry[key]).area>POLICY['max_overlap_m2']:reason='family-gap-ownership'
|
||||
elif not a.get('atomic_family') and not b.get('atomic_family'):
|
||||
left=a.get('seam_members',a['after']);right=b.get('seam_members',b['after'])
|
||||
if any(not isolated_addition(geom(f),{g['id']:g for g in right}) for f in left):reason='unresolved-line-seam'
|
||||
if reason:conflicts.append((key,other));types[reason]+=1
|
||||
selected,report=choose(nodes,conflicts,[(ids,1.) for ids in membership.values()])
|
||||
chosen=set(selected);current={i:f for i,f in base.items() if f['properties'].get('subtype')!='linear_marking'};transactions=[]
|
||||
for key in selected:
|
||||
t=payload[key]
|
||||
for f in t['after']:
|
||||
assert f['id'] not in current,'Conflicting selected feature identifiers'
|
||||
current[f['id']]=f
|
||||
if not key.startswith('keep:'):transactions.append(t)
|
||||
report.update(configurations=len(configurations),unique_configurations=len(nodes),selected_configurations=len(selected),fixed_positive_samples=len(positive),metric_cell_m=CELL,conflicts=dict(types),source='current-run-primary-observations',old_control_input=False,seconds_total=time.monotonic()-started)
|
||||
report['choices']=[dict(id=n['id'],selected=n['id'] in chosen,source_ids=n['sources'],incumbent=n['incumbent'],positive_samples=len(atoms[n['id']]&positive),cost=n['cost']) for n in nodes]
|
||||
return current,transactions,report
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Choose whole admissible configurations; never manufacture geometry.
|
||||
|
||||
Observation rewards belong to immutable metric samples, not objects. A sample
|
||||
covered by several compatible configurations is paid once. Fresh-run input
|
||||
objects must each be retained or replaced exactly once. Solver limits return a
|
||||
checked feasible incumbent, with a distinct status from proven optimality.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
import time
|
||||
import numpy as np
|
||||
from scipy.optimize import Bounds, LinearConstraint, milp
|
||||
from scipy.sparse import coo_matrix
|
||||
|
||||
|
||||
def conflict_cliques(count,edges):
|
||||
"""Exact edge cover by cliques; no new conflicts and no lost conflicts.
|
||||
|
||||
Family subseries produce dense overlap graphs. Encoding each overlap as a
|
||||
separate matrix row is wasteful. Bitset intersection only joins vertices
|
||||
already pairwise incompatible. Residual pairs are valid size-two cliques.
|
||||
"""
|
||||
adjacency=[0]*count
|
||||
for a,b in edges:adjacency[a]|=1<<b;adjacency[b]|=1<<a
|
||||
remaining=adjacency.copy();groups=[]
|
||||
while any(remaining):
|
||||
pivot=max(range(count),key=lambda i:remaining[i].bit_count())
|
||||
allowed=remaining[pivot];clique=[pivot];mask=1<<pivot
|
||||
while allowed:
|
||||
bit=allowed&-allowed;v=bit.bit_length()-1
|
||||
clique.append(v);mask|=bit;allowed&=adjacency[v]
|
||||
for v in clique:remaining[v]&=~mask
|
||||
groups.append(clique)
|
||||
return groups
|
||||
|
||||
|
||||
def choose(nodes, conflicts, samples, seconds=30., component_seconds=5.):
|
||||
started=time.monotonic()
|
||||
nodes=sorted(nodes,key=lambda n:n['id'])
|
||||
index={n['id']:i for i,n in enumerate(nodes)}
|
||||
assert len(index)==len(nodes)
|
||||
ownership=defaultdict(list)
|
||||
for i,n in enumerate(nodes):
|
||||
for source in n['sources']:ownership[source].append(i)
|
||||
edges=[(index[a],index[b]) for a,b in conflicts]
|
||||
groups=defaultdict(float)
|
||||
for members,weight in samples:
|
||||
key=tuple(sorted(index[n] for n in members))
|
||||
if key:groups[key]+=weight
|
||||
parent=list(range(len(nodes)))
|
||||
def root(i):
|
||||
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
|
||||
return i
|
||||
def connect(ids):
|
||||
for i in ids[1:]:parent[root(i)]=root(ids[0])
|
||||
for ids in list(ownership.values())+list(groups)+[list(e) for e in edges]:connect(ids)
|
||||
components=defaultdict(list)
|
||||
for i in range(len(nodes)):components[root(i)].append(i)
|
||||
selected=[];reports=[]
|
||||
for members in sorted(components.values(),key=lambda ids:nodes[ids[0]]['id']):
|
||||
local={i:k for k,i in enumerate(members)};m=len(members)
|
||||
rewards=[(tuple(local[i] for i in ids),w) for ids,w in groups.items() if ids[0] in local]
|
||||
c=np.array([nodes[i]['cost'] for i in members]+[-w for _,w in rewards],float)
|
||||
rr=[];cc=[];vv=[];lower=[];upper=[]
|
||||
def constraint(terms,lo,hi):
|
||||
row=len(lower)
|
||||
for col,value in terms:rr.append(row);cc.append(col);vv.append(value)
|
||||
lower.append(lo);upper.append(hi)
|
||||
for ids in ownership.values():
|
||||
if ids[0] in local:constraint([(local[i],1) for i in ids],1,1)
|
||||
local_edges=[(local[a],local[b]) for a,b in edges if a in local]
|
||||
cliques=conflict_cliques(m,local_edges)
|
||||
for ids in cliques:constraint([(i,1) for i in ids],-np.inf,1)
|
||||
for k,(ids,_) in enumerate(rewards):
|
||||
constraint([(m+k,1)]+[(i,-1) for i in ids],-np.inf,0)
|
||||
A=coo_matrix((vv,(rr,cc)),shape=(len(lower),len(c))).tocsc()
|
||||
lb=np.array(lower);ub=np.array(upper)
|
||||
fallback=np.zeros(len(c))
|
||||
fallback[:m]=[bool(nodes[i].get('incumbent')) for i in members]
|
||||
for k,(ids,_) in enumerate(rewards):fallback[m+k]=any(fallback[i] for i in ids)
|
||||
def valid(x):
|
||||
return x is not None and np.isfinite(x).all() and np.all(abs(x-np.rint(x))<1e-6) and np.all(x>=-1e-6) and np.all(x<=1+1e-6) and np.all(A@x>=lb-1e-6) and np.all(A@x<=ub+1e-6)
|
||||
assert valid(fallback),'Invalid current-run incumbent'
|
||||
# A bounded primal construction over already measured configurations.
|
||||
# It creates no geometry, performs no image query, and never splits a
|
||||
# family. Exact conservation constraints still govern every source.
|
||||
adjacency=[set() for _ in members]
|
||||
for a,b in local_edges:adjacency[a].add(b);adjacency[b].add(a)
|
||||
source_sets=[set(nodes[i]['sources']) for i in members]
|
||||
source_members=defaultdict(set)
|
||||
for k,ss in enumerate(source_sets):
|
||||
for source in ss:source_members[source].add(k)
|
||||
sample_sets=[set() for _ in members]
|
||||
for k,(ids,_) in enumerate(rewards):
|
||||
for i in ids:sample_sets[i].add(k)
|
||||
weights=np.array([w for _,w in rewards])
|
||||
chosen={i for i in range(m) if fallback[i]}
|
||||
def vector(selection):
|
||||
x=np.zeros(len(c));x[list(selection)]=1
|
||||
covered=set().union(*(sample_sets[i] for i in selection)) if selection else set()
|
||||
if covered:x[[m+k for k in covered]]=1
|
||||
return x
|
||||
order=sorted(range(m) if seconds>0 else [],key=lambda i:(-sum(weights[k] for k in sample_sets[i]),nodes[members[i]]['id']))
|
||||
for i in order:
|
||||
if i in chosen:continue
|
||||
remove=adjacency[i]&chosen
|
||||
for source in source_sets[i]:remove|=source_members[source]&chosen
|
||||
if any(not source_sets[j]<=source_sets[i] for j in remove):continue
|
||||
trial=(chosen-remove)|{i};x=vector(trial)
|
||||
if valid(x) and c@x<c@fallback-1e-7:chosen=trial;fallback=x
|
||||
budget=min(component_seconds,max(0.,seconds-(time.monotonic()-started)))
|
||||
result=None
|
||||
if budget>.001:
|
||||
result=milp(c,integrality=np.ones(len(c)),bounds=Bounds(0,1),constraints=LinearConstraint(A,lb,ub),options=dict(time_limit=budget,mip_rel_gap=0.))
|
||||
x=fallback;status='incumbent-time-budget'
|
||||
if result is not None and valid(result.x) and c@result.x<=c@fallback+1e-7:
|
||||
x=np.rint(result.x);status='optimal' if result.status==0 else 'feasible-limit'
|
||||
elif result is not None:status='incumbent-no-better-feasible-solution'
|
||||
selected.extend(nodes[i]['id'] for k,i in enumerate(members) if x[k]>.5)
|
||||
reports.append(dict(nodes=m,sample_groups=len(rewards),pairwise_conflicts=len(local_edges),conflict_cliques=len(cliques),status=status,objective=float(-c@x),incumbent_objective=float(-c@fallback),solver_status=None if result is None else int(result.status)))
|
||||
return selected,dict(seconds=time.monotonic()-started,components=reports,optimal=all(r['status']=='optimal' for r in reports),fixed_sample_groups=len(groups))
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Metric reconstruction rules independent of map names and coordinates."""
|
||||
import numpy as np,shapely
|
||||
from shapely.geometry import shape
|
||||
from interval_profiles import rectangle,strip,runs
|
||||
from beta_profiles import describe
|
||||
VERSION='stroke-window-family-v3'
|
||||
POLICY=dict(min_continuous_section_m=1.,min_valid=.98,min_paint_support=.93,min_contrast=22.,min_dark_flank=.85,max_overlap_m2=.005,removed_dark_fraction=.90,retained_paint_tolerance_m=.06,profile_core_fraction=.35,profile_core_min_half_m=.125,reject_unresolved_seam=True,max_join_gap_m=.20,max_join_angle_deg=3.,max_join_offset_m=.06,single_edit_per_family=True,primary_and_secondary_required=True,manual_rois=[],point_cloud_input=False)
|
||||
|
||||
def missing_parts(p,existing):
|
||||
d=describe(p)
|
||||
if d is None:return []
|
||||
o,u=d['origin'],d['axis'];L=d['length'];occupied=p.intersection(existing.buffer(.10));intervals=[]
|
||||
for q in getattr(occupied,'geoms',[occupied]):
|
||||
if q.is_empty:continue
|
||||
coords=shapely.get_coordinates(q);t=(coords-o)@u;intervals.append((t.min(),t.max()))
|
||||
merged=[]
|
||||
for a,b in sorted(intervals):
|
||||
if merged and a<=merged[-1][1]:merged[-1][1]=max(b,merged[-1][1])
|
||||
else:merged.append([a,b])
|
||||
cursor=-L/2;out=[]
|
||||
for a,b in merged+[[L/2,L/2]]:
|
||||
if a-cursor>=POLICY['min_continuous_section_m']:out.append(rectangle(o,u,cursor,a,d['width']))
|
||||
cursor=max(cursor,b)
|
||||
return out
|
||||
|
||||
def plan_replacement(r,current):
|
||||
new=shapely.union_all(r['polygons']);domain=r['domain'];ids=[]
|
||||
for i,f in current.items():
|
||||
if f['properties'].get('class')!='road_marking':continue
|
||||
p=shapely.force_2d(shape(f['geometry']))
|
||||
if p.intersection(domain).area<.005:continue
|
||||
if f['properties'].get('subtype')!='linear_marking':return None
|
||||
if p.difference(domain).area>.005:return None
|
||||
ids.append(i)
|
||||
if not ids:return None
|
||||
old=shapely.union_all([shapely.force_2d(shape(current[i]['geometry']))for i in ids])
|
||||
if old.symmetric_difference(new).area<max(.03,old.area*.07):return None
|
||||
return ids,r['polygons']
|
||||
|
||||
def validate_removed(old,new,r,readers):
|
||||
removed=old.difference(new.buffer(POLICY['retained_paint_tolerance_m']))
|
||||
if removed.area<.015:return True,[]
|
||||
o,u=r['origin'],r['axis'];xy=shapely.get_coordinates(removed);t=(xy-o)@u;ts=np.arange(t.min(),t.max()+.025,.025);ns=np.arange(-.7,.701,.025);n=np.array([-u[1],u[0]]);points=o+ts[:,None,None]*u+ns[None,:,None]*n;sel=shapely.contains_xy(removed,points[:,:,0],points[:,:,1]);ev=[]
|
||||
if sel.sum()<5:return False,[]
|
||||
for read in readers:
|
||||
con,valid=strip(o,u,ts,ns,read);e=dict(valid=float(valid[sel].mean()),dark=float((con[sel]<15).mean()));ev.append(e)
|
||||
return len(ev)==2 and all(e['valid']>=.98 and e['dark']>=.90 for e in ev),ev
|
||||
|
||||
def check_strip(p,readers):
|
||||
d=describe(p)
|
||||
if d is None:return False,[]
|
||||
ts=np.arange(-d['length']/2+.04,d['length']/2-.04,.025);ns=np.arange(-.7,.701,.025);core=abs(ns)<=max(.025,min(.04,d['width']*.2));flank=(abs(ns)>=d['width']/2+.08)&(abs(ns)<=d['width']/2+.14);ev=[]
|
||||
for read in readers:
|
||||
con,valid=strip(d['origin'],d['axis'],ts,ns,read);signal=np.median(con[:,core],axis=1);cut=max(15.,.35*float(np.median(signal)));e=dict(valid=float(valid[:,core].mean()),support=float((signal>cut).mean()),contrast=float(np.median(signal)),dark_flank=float((con[:,flank]<cut).mean()),flank_valid=float(valid[:,flank].mean()));ev.append(e)
|
||||
return len(ev)==2 and all(e['valid']>=.98 and e['support']>=.93 and e['contrast']>=22 and e['dark_flank']>=.85 and e['flank_valid']>=.95 for e in ev),ev
|
||||
|
||||
def join_continuous(p,current):
|
||||
"""Merge a newly observed extension with aligned neighboring linear paint."""
|
||||
d=describe(p)
|
||||
if d is None:return [],p
|
||||
o,u=d['origin'],d['axis'];n=np.array([-u[1],u[0]]);ids=[];pieces=[p];widths=[d['width']];axes=[u*d['length']];weights=[d['length']]
|
||||
for i,f in current.items():
|
||||
if f['properties'].get('subtype')!='linear_marking':continue
|
||||
q=shapely.force_2d(shape(f['geometry']));v=describe(q)
|
||||
if v is None or q.distance(p)>POLICY['max_join_gap_m']:continue
|
||||
axis=v['axis']*np.sign(v['axis']@u)
|
||||
if axis@u<np.cos(np.deg2rad(POLICY['max_join_angle_deg'])):continue
|
||||
# Measure the lateral displacement at the near endpoint, not a distant center.
|
||||
from shapely.ops import nearest_points
|
||||
near=np.array(nearest_points(q,p)[0].coords[0]);dist=abs((near-o)@n)
|
||||
if dist>max(d['width'],v['width'])/2+POLICY['max_join_offset_m']:continue
|
||||
if abs(d['width']-v['width'])>.08:continue
|
||||
ids.append(i);pieces.append(q);widths.append(v['width']);axes.append(axis*v['length']);weights.append(v['length'])
|
||||
if not ids:return [],p
|
||||
axis=np.sum(axes,axis=0);axis/=np.linalg.norm(axis);normal=np.array([-axis[1],axis[0]])
|
||||
centers=np.array([list(q.centroid.coords)[0]for q in pieces]);origin=np.average(centers,axis=0,weights=weights);xy=np.concatenate([shapely.get_coordinates(q)for q in pieces]);t=(xy-origin)@axis;width=float(np.average(widths,weights=weights))
|
||||
return ids,rectangle(origin,axis,float(t.min()),float(t.max()),width)
|
||||
|
||||
|
||||
def isolated_addition(p,current):
|
||||
"""Reject unresolved end-to-end seams, not a distinct parallel paint track."""
|
||||
candidate=describe(p)
|
||||
if candidate is None:return False
|
||||
for f in current.values():
|
||||
if f['properties'].get('subtype')!='linear_marking':continue
|
||||
q=shapely.force_2d(shape(f['geometry']))
|
||||
if p.distance(q)>POLICY['max_join_gap_m']:continue
|
||||
neighbor=describe(q)
|
||||
if neighbor is None:return False
|
||||
u=candidate['axis'];n=np.array([-u[1],u[0]])
|
||||
# No merge is attempted across a direction change. An actual intersection
|
||||
# is rejected by the transaction's unchanged overlap gate.
|
||||
if abs(u@neighbor['axis'])<np.cos(np.deg2rad(POLICY['max_join_angle_deg'])):continue
|
||||
from shapely.ops import nearest_points
|
||||
near=np.asarray(nearest_points(q,p)[0].coords[0])
|
||||
offset=abs((near-candidate['origin'])@n)
|
||||
if offset>max(candidate['width'],neighbor['width'])/2+POLICY['max_join_offset_m']:continue
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,102 @@
|
||||
"""One bounded observation graph per rhythm model, from existing 2-D pixels.
|
||||
|
||||
A globally measured ridge and each body's local ridge are observations, not
|
||||
interchangeable promises. A path exists only when all bodies and intervening
|
||||
gaps satisfy the original two-view predicates. No historical geometry enters.
|
||||
"""
|
||||
import numpy as np
|
||||
from beta_profiles import POLICY,fit_series,section_evidence,supported,corridor_dark
|
||||
from interval_profiles import rectangle
|
||||
from body_profiles import local_body,signal_at
|
||||
|
||||
|
||||
def alternatives(view,center,length,mode):
|
||||
observed=[]
|
||||
intervals=[ab for ab in view[mode]if abs((ab[0]+ab[1])/2-center)<=POLICY['max_phase_error_m']and abs(ab[1]-ab[0]-length)<=max(.2,.22*length)]
|
||||
if intervals:
|
||||
ab=min(intervals,key=lambda ab:abs((ab[0]+ab[1])/2-center))
|
||||
observed.append(dict(view=view,edges=ab,offset=view['offset'],width=view['width'],basis='row-ridge'))
|
||||
local=local_body(view,center,length,mode)
|
||||
if local is not None and not any(np.allclose(local['edges'],x['edges'],atol=1e-8)and abs(local['offset']-x['offset'])<1e-8 for x in observed):
|
||||
observed.append({**local,'basis':'body-ridge'})
|
||||
return observed
|
||||
|
||||
|
||||
def bodies(views,center,length,mode):
|
||||
out=[];options=[alternatives(v,center,length,mode)for v in views]
|
||||
for first in options[0]:
|
||||
for second in options[1]:
|
||||
samples=[first,second];edges=np.array([x['edges']for x in samples]);offsets=np.array([x['offset']for x in samples])
|
||||
if np.max(abs(edges[0]-edges[1]))>POLICY['max_edge_disagreement_m']or np.ptp(offsets)>POLICY['max_view_offset_disagreement_m']:continue
|
||||
lo,hi=edges.mean(0);middle=(lo+hi)/2;span=hi-lo
|
||||
proof=[section_evidence(x['view'],middle-span*.35,middle+span*.35)for x in samples]
|
||||
if not all(supported(e)for e in proof):continue
|
||||
out.append(dict(lo=float(lo),hi=float(hi),center=float(middle),offset=float(offsets.mean()),width=float(np.clip(np.median([x['width']for x in samples]),.075,.27)),samples=samples,proof=proof,model_center=center,
|
||||
displacement=float(sum((x['offset']-v['offset'])**2 for x,v in zip(samples,views)))))
|
||||
return out
|
||||
|
||||
|
||||
def gap(left,right,views,mode):
|
||||
if right['lo']-left['hi']<POLICY['min_gap_m']:return None
|
||||
evidence=[]
|
||||
for vi,view in enumerate(views):
|
||||
a,b=left['samples'][vi],right['samples'][vi]
|
||||
# Preserve a measured straight ridge exactly. For a displaced ridge,
|
||||
# sample the intervening path in the same previously loaded 2-D field.
|
||||
if a['basis']==b['basis']=='row-ridge':local=view
|
||||
else:
|
||||
fraction=np.clip((view['ts']-left['center'])/(right['center']-left['center']),0.,1.)
|
||||
local=signal_at(view,a['offset']+fraction*(b['offset']-a['offset']))
|
||||
e=section_evidence(local,left['hi']+.04,right['lo']-.04,False)
|
||||
if mode=='peak_intervals':
|
||||
paint=min(section_evidence(body['samples'][vi]['view'],body['center']-(body['hi']-body['lo'])*.3,body['center']+(body['hi']-body['lo'])*.3)['contrast']for body in [left,right])
|
||||
e['contrast_drop']=paint-e['contrast'];okay=e['valid']>=POLICY['min_valid']and e['contrast_drop']>=18 and e['contrast']<paint*.65
|
||||
else:okay=supported(e,False)
|
||||
if not okay:return None
|
||||
evidence.append(e)
|
||||
return evidence
|
||||
|
||||
|
||||
def observed_path(options,views,mode):
|
||||
if not options or any(not x for x in options):return None
|
||||
paths=[(b['displacement'],[b],[])for b in options[0]]
|
||||
for choices in options[1:]:
|
||||
next_paths=[]
|
||||
for right in choices:
|
||||
best=None
|
||||
for cost,history,proof in paths:
|
||||
evidence=gap(history[-1],right,views,mode)
|
||||
if evidence is None:continue
|
||||
candidate=(cost+right['displacement'],history+[right],proof+evidence)
|
||||
if best is None or candidate[0]<best[0]:best=candidate
|
||||
if best is not None:next_paths.append(best)
|
||||
paths=next_paths
|
||||
if not paths:return None
|
||||
return min(paths,key=lambda x:x[0])
|
||||
|
||||
|
||||
def discover(seed,views,fits=None):
|
||||
if views is None or len(views)!=2:return []
|
||||
origin,axis=seed['origin'],seed['axis'];width=float(np.clip(np.median([v['width']for v in views]),.075,.27));offset=float(np.mean([v['offset']for v in views]));cache={};candidates=[]
|
||||
for mode in ['intervals','peak_intervals']:
|
||||
for fit in (fits[mode] if fits is not None else fit_series(views[0][mode],seed,width,offset)):
|
||||
options=[]
|
||||
for p in fit['polygons']:
|
||||
center=float((np.asarray(p.centroid.coords[0])-origin)@axis);key=(mode,center,fit['length'])
|
||||
if key not in cache:cache[key]=bodies(views,center,fit['length'],mode)
|
||||
options.append(cache[key])
|
||||
selected=observed_path(options,views,mode)
|
||||
if selected is None:continue
|
||||
cost,observed,gaps=selected;lo,hi=observed[0]['lo'],observed[-1]['hi'];limits=[lo,hi];edge_evidence=[]
|
||||
for side,body in enumerate([observed[0],observed[-1]]):
|
||||
sign=-1 if side==0 else 1;end=lo if side==0 else hi
|
||||
for pad in np.arange(POLICY['max_family_edge_padding_m'],.049,-.025):
|
||||
evidence=[corridor_dark(x['view'],*sorted([end+sign*.04,end+sign*float(pad)]))for x in body['samples']]
|
||||
if all(supported(e,False)for e in evidence):limits[side]=end+sign*float(pad);edge_evidence.append(dict(side=side,padding=float(pad),views=evidence));break
|
||||
low=min(b['offset']-b['width']/2 for b in observed)-.08;high=max(b['offset']+b['width']/2 for b in observed)+.08
|
||||
domain=rectangle(origin,axis,limits[0],limits[1],high-low,(low+high)/2)
|
||||
polygons=[rectangle(origin,axis,b['lo'],b['hi'],b['width'],b['offset'])for b in observed]
|
||||
observations=[dict(center=b['center'],model_center=b['model_center'],edges=[v['edges']for v in b['samples']],offsets=[v['offset']for v in b['samples']],bases=[v['basis']for v in b['samples']])for b in observed]
|
||||
proof=[b['proof']for b in observed]
|
||||
candidates.append(dict(kind='periodic-row',mode=mode,polygons=polygons,domain=domain,origin=origin,axis=axis,width=float(np.median([b['width']for b in observed])),offset=offset,period=fit['period_m'],length=fit['length'],observations=observations,paint_evidence=[e for p in proof for e in p],gap_evidence=gaps,measured_body_evidence=proof,measured_gap_evidence=gaps,edge_evidence=edge_evidence,lo=lo,hi=hi,measurement_basis='one-observation-graph; actual-bodies-and-gaps',displacement=cost))
|
||||
return candidates
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Use observed dash edges with the original periodic-family evidence rules.
|
||||
|
||||
A fitted period describes the family; it does not supply replacement endpoints.
|
||||
The existing body/gap predicates are evaluated at the measured intervals before
|
||||
one complete candidate is returned. This is not the isolated-strip verifier.
|
||||
"""
|
||||
import numpy as np
|
||||
from interval_profiles import rectangle
|
||||
from beta_profiles import section_evidence,supported,POLICY
|
||||
|
||||
|
||||
def measured_rows(candidates,views):
|
||||
out=[];sections={}
|
||||
def evidence(lo,hi,bright=True):
|
||||
key=(float(lo),float(hi),bright)
|
||||
if key not in sections:sections[key]=[section_evidence(v,lo,hi,bright)for v in views]
|
||||
return sections[key]
|
||||
for candidate in candidates:
|
||||
if candidate['kind']!='periodic-row':
|
||||
out.append(candidate);continue
|
||||
polygons=[];proof=[];intervals=[];okay=True
|
||||
for observation in candidate['observations']:
|
||||
edges=np.asarray(observation['edges'],float)
|
||||
if edges.shape!=(2,2) or np.max(abs(edges[0]-edges[1]))>POLICY['max_edge_disagreement_m']:
|
||||
okay=False;break
|
||||
lo,hi=np.mean(edges,axis=0);length=hi-lo;center=(hi+lo)/2
|
||||
ev=evidence(center-length*.35,center+length*.35)
|
||||
if len(ev)!=2 or not all(supported(e)for e in ev):okay=False;break
|
||||
polygons.append(rectangle(candidate['origin'],candidate['axis'],lo,hi,candidate['width'],candidate['offset']))
|
||||
proof.append(ev);intervals.append((float(lo),float(hi)))
|
||||
if not okay or not polygons:continue
|
||||
gaps=[]
|
||||
for left,right in zip(intervals,intervals[1:]):
|
||||
if right[0]-left[1]<POLICY['min_gap_m']:okay=False;break
|
||||
for vi,v in enumerate(views):
|
||||
ev=dict(evidence(left[1]+.04,right[0]-.04,False)[vi])
|
||||
if candidate['mode']=='peak_intervals':
|
||||
def body(ab):
|
||||
c=(ab[0]+ab[1])/2;length=ab[1]-ab[0]
|
||||
return evidence(c-length*.3,c+length*.3)[vi]['contrast']
|
||||
paint=min(body(left),body(right));ev['contrast_drop']=paint-ev['contrast']
|
||||
passed=ev['valid']>=POLICY['min_valid']and ev['contrast_drop']>=18 and ev['contrast']<paint*.65
|
||||
else:passed=supported(ev,False)
|
||||
if not passed:okay=False;break
|
||||
gaps.append(ev)
|
||||
if not okay:break
|
||||
if not okay:continue
|
||||
observed_domain=rectangle(candidate['origin'],candidate['axis'],intervals[0][0],intervals[-1][1],candidate['width']+.16,candidate['offset'])
|
||||
domain=candidate['domain'].union(observed_domain)
|
||||
out.append({**candidate,'polygons':polygons,'domain':domain,'measured_body_evidence':proof,'measured_gap_evidence':gaps})
|
||||
return out
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Reuse identical observations within one axis measurement, then release them.
|
||||
|
||||
The ordinary and stroke-sized profile interpretations query the exact same
|
||||
points. Failed interpretation must not cause another image decode/projection.
|
||||
Keys include every coordinate bit; nearby but distinct measurements never alias.
|
||||
"""
|
||||
from collections import OrderedDict
|
||||
import hashlib
|
||||
import numpy as np
|
||||
|
||||
|
||||
class MeasurementRead:
|
||||
def __init__(self,reader,max_bytes=8*1024**2):
|
||||
self.reader=reader;self.limit=max_bytes;self.values=OrderedDict()
|
||||
self.bytes=0;self.hits=0;self.misses=0
|
||||
|
||||
def __call__(self,points,detailed=False):
|
||||
if detailed:return self.reader(points,detailed=True)
|
||||
a=np.ascontiguousarray(points)
|
||||
key=(a.shape,a.dtype.str,hashlib.sha256(a.view('uint8')).digest())
|
||||
if key in self.values:
|
||||
self.hits+=1;result,size=self.values.pop(key);self.values[key]=(result,size)
|
||||
return result
|
||||
self.misses+=1;result=self.reader(points)
|
||||
assert len(result)==2
|
||||
size=sum(v.nbytes for v in result)
|
||||
if size<=self.limit:
|
||||
while self.values and (self.bytes+size>self.limit or len(self.values)>=2):
|
||||
_,(_,removed)=self.values.popitem(last=False);self.bytes-=removed
|
||||
for value in result:value.setflags(write=False)
|
||||
self.values[key]=(result,size);self.bytes+=size
|
||||
return result
|
||||
|
||||
|
||||
class FrameReads:
|
||||
"""Bounded exact camera frames for immutable configuration admission."""
|
||||
def __init__(self,loader,maximum=16):
|
||||
self.loader=loader;self.maximum=maximum;self.values=OrderedDict()
|
||||
self.hits=0;self.misses=0
|
||||
|
||||
def __call__(self,origin,axis):
|
||||
a,b=np.asarray(origin),np.asarray(axis)
|
||||
key=(a.shape,a.dtype.str,a.tobytes(),b.shape,b.dtype.str,b.tobytes())
|
||||
if key in self.values:
|
||||
self.hits+=1;value=self.values.pop(key);self.values[key]=value;return value
|
||||
self.misses+=1;readers,used=self.loader(origin,axis)
|
||||
value=([MeasurementRead(reader) for reader in readers],used)
|
||||
while len(self.values)>=self.maximum:self.values.popitem(last=False)
|
||||
self.values[key]=value
|
||||
return value
|
||||
|
||||
def report(self):
|
||||
return dict(frame_hits=self.hits,frame_misses=self.misses,maximum_frames=self.maximum,
|
||||
maximum_sample_bytes=self.maximum*2*8*1024**2,lifetime='one admission process')
|
||||
|
||||
|
||||
def qualify():
|
||||
calls=[]
|
||||
def reader(p):
|
||||
calls.append(p.copy());return np.repeat(p[:,:1],3,axis=1),np.ones(len(p),bool)
|
||||
cached=MeasurementRead(reader,1024)
|
||||
a=np.array([[1.,2.],[3.,4.]])
|
||||
first=cached(a);second=cached(a.copy())
|
||||
assert len(calls)==1 and first is second
|
||||
shifted=a.copy();shifted[0,0]=np.nextafter(shifted[0,0],2.)
|
||||
cached(shifted)
|
||||
assert len(calls)==2,'Distinct measurement was merged'
|
||||
assert cached.bytes<=cached.limit
|
||||
cached(np.zeros((1000,2)))
|
||||
assert cached.bytes<=cached.limit,'Oversized query exceeded cache budget'
|
||||
assert not first[0].flags.writeable and not first[1].flags.writeable
|
||||
frames=FrameReads(lambda o,u:([reader,reader],[{},{}]),maximum=1)
|
||||
origin=np.zeros(2);axis=np.array([1.,0.])
|
||||
assert frames(origin,axis) is frames(origin.copy(),axis.copy())
|
||||
frames(origin+1,axis)
|
||||
assert len(frames.values)==1 and frames.hits==1
|
||||
print('MEASUREMENT_READ_CONTRACT_OK',flush=True)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Experimental whole-object evidence, without admission threshold changes.
|
||||
|
||||
Each branch must first have its own visible paint body. Another branch may
|
||||
explain a bright flank only inside its measured polygon. Remaining exterior
|
||||
samples still have to be dark and observed. This module creates no geometry.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import shapely
|
||||
from beta_profiles import describe
|
||||
from interval_profiles import strip
|
||||
from marking_rules import POLICY
|
||||
|
||||
|
||||
def measure(p, readers):
|
||||
d = describe(p)
|
||||
if d is None:
|
||||
return None
|
||||
ts = np.arange(-d["length"] / 2 + 0.04, d["length"] / 2 - 0.04, 0.025)
|
||||
ns = np.arange(-0.7, 0.701, 0.025)
|
||||
core = abs(ns) <= max(0.025, min(0.04, d["width"] * 0.2))
|
||||
body = abs(ns) <= d["width"] / 2
|
||||
flank = (abs(ns) >= d["width"] / 2 + 0.08) & (abs(ns) <= d["width"] / 2 + 0.14)
|
||||
if not len(ts) or not body.any() or not flank.any():
|
||||
return None
|
||||
normal = np.array([-d["axis"][1], d["axis"][0]])
|
||||
xy = d["origin"] + ts[:, None, None] * d["axis"] + ns[None, :, None] * normal
|
||||
body_points = xy[:, body].reshape(-1, 2)
|
||||
# OpenCV's fitted rectangle is float32. Its boundary is not the polygon's
|
||||
# authority: a rounded endpoint just outside the actual body is context.
|
||||
inside = shapely.intersects_xy(p, body_points[:, 0], body_points[:, 1])
|
||||
if not inside.any():
|
||||
return None
|
||||
rows, bodies, sides = [], [], []
|
||||
for read in readers:
|
||||
con, valid = strip(d["origin"], d["axis"], ts, ns, read)
|
||||
signal = np.median(con[:, core], axis=1)
|
||||
cut = max(15.0, 0.35 * float(np.median(signal)))
|
||||
row = dict(
|
||||
valid=float(valid[:, core].mean()),
|
||||
support=float((signal > cut).mean()),
|
||||
contrast=float(np.median(signal)),
|
||||
dark_flank=float((con[:, flank] < cut).mean()),
|
||||
flank_valid=float(valid[:, flank].mean()),
|
||||
)
|
||||
rows.append(row)
|
||||
bodies.append(
|
||||
dict(valid=valid[:, body].ravel()[inside], paint=(con[:, body] > cut).ravel()[inside])
|
||||
)
|
||||
sides.append(dict(valid=valid[:, flank].ravel(), dark=(con[:, flank] < cut).ravel()))
|
||||
# Exact legacy metric reconstruction is checked in qualification. The body
|
||||
# condition is additional, not a substitute for the existing central test.
|
||||
legacy = len(rows) == 2 and all(
|
||||
r["valid"] >= 0.98
|
||||
and r["support"] >= 0.93
|
||||
and r["contrast"] >= 22
|
||||
and r["dark_flank"] >= 0.85
|
||||
and r["flank_valid"] >= 0.95
|
||||
for r in rows
|
||||
)
|
||||
body_ok = len(rows) == 2 and all(
|
||||
r["valid"] >= POLICY["min_valid"]
|
||||
and r["support"] >= POLICY["min_paint_support"]
|
||||
and r["contrast"] >= POLICY["min_contrast"]
|
||||
and b["valid"].mean() >= POLICY["min_valid"]
|
||||
and b["paint"].mean() >= POLICY["min_paint_support"]
|
||||
for r, b in zip(rows, bodies, strict=True)
|
||||
)
|
||||
return dict(
|
||||
polygon=p,
|
||||
description=d,
|
||||
legacy=legacy,
|
||||
body_ok=body_ok,
|
||||
legacy_evidence=rows,
|
||||
body_points=body_points[inside],
|
||||
flank_points=xy[:, flank].reshape(-1, 2),
|
||||
bodies=bodies,
|
||||
flanks=sides,
|
||||
body_evidence=[
|
||||
dict(valid=float(b["valid"].mean()), support=float(b["paint"].mean())) for b in bodies
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def relation(a, b):
|
||||
"""A localized, measured intersection; no synthetic bridge or shape list."""
|
||||
da, db = describe(a), describe(b)
|
||||
if da is None or db is None:
|
||||
return None
|
||||
if abs(da["axis"] @ db["axis"]) >= np.cos(np.deg2rad(POLICY["max_join_angle_deg"])):
|
||||
return None
|
||||
shared = a.intersection(b)
|
||||
if shared.area <= POLICY["max_overlap_m2"]:
|
||||
return None
|
||||
for d in [da, db]:
|
||||
cap = d["width"] + POLICY["retained_paint_tolerance_m"]
|
||||
if 2 * cap >= d["length"]:
|
||||
return None
|
||||
extent = (shapely.get_coordinates(shared) - d["origin"]) @ d["axis"]
|
||||
# Broad coincident alternatives cannot masquerade as a local junction.
|
||||
if np.ptp(extent) > 2 * cap:
|
||||
return None
|
||||
joined = a.union(b)
|
||||
return shared if joined.geom_type == "Polygon" and joined.is_valid else None
|
||||
|
||||
|
||||
def connection_supported(members, shared):
|
||||
proof = []
|
||||
for m in members:
|
||||
points = m["body_points"]
|
||||
selected = shapely.intersects_xy(shared, points[:, 0], points[:, 1])
|
||||
if not selected.any():
|
||||
return False, proof
|
||||
for evidence in m["bodies"]:
|
||||
row = dict(
|
||||
samples=int(selected.sum()),
|
||||
valid=float(evidence["valid"][selected].mean()),
|
||||
support=float(evidence["paint"][selected].mean()),
|
||||
)
|
||||
proof.append(row)
|
||||
return all(
|
||||
r["valid"] >= POLICY["min_valid"] and r["support"] >= POLICY["min_paint_support"]
|
||||
for r in proof
|
||||
), proof
|
||||
|
||||
|
||||
def check(members):
|
||||
if len(members) < 2 or not all(m["body_ok"] for m in members):
|
||||
return False, dict(reason="unsupported-member-body")
|
||||
proof = []
|
||||
for i, m in enumerate(members):
|
||||
others = shapely.union_all([x["polygon"] for j, x in enumerate(members) if j != i])
|
||||
points = m["flank_points"]
|
||||
exterior = ~shapely.intersects_xy(others, points[:, 0], points[:, 1])
|
||||
if not exterior.any():
|
||||
return False, dict(reason="unmeasured-exterior")
|
||||
for original, side in zip(m["legacy_evidence"], m["flanks"], strict=True):
|
||||
row = dict(
|
||||
flank_valid=original["flank_valid"],
|
||||
external_valid=float(side["valid"][exterior].mean()),
|
||||
external_dark=float(side["dark"][exterior].mean()),
|
||||
explained_samples=int((~exterior).sum()),
|
||||
external_samples=int(exterior.sum()),
|
||||
)
|
||||
proof.append(row)
|
||||
passed = all(
|
||||
r["flank_valid"] >= 0.95
|
||||
and r["external_valid"] >= 0.95
|
||||
and r["external_dark"] >= POLICY["min_dark_flank"]
|
||||
for r in proof
|
||||
)
|
||||
return passed, dict(
|
||||
reason="observed-body-and-exterior" if passed else "unsupported-exterior", views=proof
|
||||
)
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Packaging-invariant diagnostic evidence on a fixed world lattice.
|
||||
|
||||
This measures the set union, not object counts. It never changes geometry,
|
||||
admission or confidence. Unknown observations cannot become positive evidence.
|
||||
The sampler and world origin are independent of the proposed partition.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from collections import Counter
|
||||
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import box
|
||||
|
||||
VERSION = "fixed-world-object-evidence-v1"
|
||||
CELL = 0.04
|
||||
TILE = 3.0
|
||||
HALO = 1.0
|
||||
CONTEXT = 0.15
|
||||
MAX_TILES = 20000
|
||||
|
||||
|
||||
def tile_ids(geometry):
|
||||
ids = set()
|
||||
for p in getattr(geometry, "geoms", [geometry]):
|
||||
if p.is_empty:
|
||||
continue
|
||||
lo = np.floor(np.array(p.bounds[:2]) / TILE).astype(int)
|
||||
hi = np.floor(np.array(p.bounds[2:]) / TILE).astype(int)
|
||||
if (hi[0] - lo[0] + 1) * (hi[1] - lo[1] + 1) > MAX_TILES:
|
||||
raise ValueError("sampling-budget")
|
||||
for x in range(lo[0], hi[0] + 1):
|
||||
for y in range(lo[1], hi[1] + 1):
|
||||
if p.intersects(box(x * TILE, y * TILE, (x + 1) * TILE, (y + 1) * TILE)):
|
||||
ids.add((int(x), int(y)))
|
||||
if len(ids) > MAX_TILES:
|
||||
raise ValueError("sampling-budget")
|
||||
return sorted(ids)
|
||||
|
||||
|
||||
def grid(key, halo=False):
|
||||
n = round(TILE / CELL)
|
||||
h = round(HALO / CELL) if halo else 0
|
||||
ix = key[0] * n + np.arange(-h, n + h)
|
||||
iy = key[1] * n + np.arange(-h, n + h)
|
||||
xx, yy = np.meshgrid(ix, iy)
|
||||
return np.c_[xx.ravel(), yy.ravel()], np.c_[
|
||||
(xx.ravel() + 0.5) * CELL, (yy.ravel() + 0.5) * CELL
|
||||
]
|
||||
|
||||
|
||||
def counts(mask, evidence):
|
||||
physical = np.asarray(evidence["physical"], bool)
|
||||
road = np.asarray(evidence["road"], bool)
|
||||
paint = np.asarray(evidence["paint"], bool)
|
||||
assert physical.shape == road.shape == paint.shape == (2, len(mask))
|
||||
known = physical.all(axis=0)
|
||||
surface = known & road.all(axis=0)
|
||||
positive = paint.all(axis=0)
|
||||
flags = dict(
|
||||
samples=np.ones(len(mask), bool),
|
||||
physical_observed=known,
|
||||
road_observed=surface,
|
||||
paint_supported=surface & positive,
|
||||
observed_nonpaint=surface & ~paint.any(axis=0),
|
||||
view_disagreement=surface & (paint[0] != paint[1]),
|
||||
outside_road_observed=known & ~road.all(axis=0),
|
||||
unknown_physical=~known,
|
||||
)
|
||||
return {k: int((v & mask).sum()) for k, v in flags.items()}
|
||||
|
||||
|
||||
def inspect(polygons, sampler):
|
||||
body = shapely.union_all([shapely.force_2d(p) for p in polygons])
|
||||
if not body.is_valid:
|
||||
raise ValueError("invalid-geometry")
|
||||
surroundings = body.buffer(CONTEXT).difference(body)
|
||||
totals = dict(body=Counter(), context=Counter())
|
||||
digest = hashlib.sha256()
|
||||
keys = tile_ids(body.union(surroundings))
|
||||
for key in keys:
|
||||
ids, points = grid(key)
|
||||
evidence = sampler(key)
|
||||
for name, geometry in [("body", body), ("context", surroundings)]:
|
||||
mask = shapely.intersects_xy(geometry, points[:, 0], points[:, 1])
|
||||
# A partition boundary inside a union is never a second sample.
|
||||
if name == "context":
|
||||
mask &= ~shapely.intersects_xy(body, points[:, 0], points[:, 1])
|
||||
totals[name].update(counts(mask, evidence))
|
||||
digest.update(name.encode())
|
||||
digest.update(np.asarray(ids[mask], dtype="<i8").tobytes())
|
||||
for field in ["physical", "road", "paint"]:
|
||||
digest.update(np.asarray(evidence[field], bool)[:, mask].tobytes())
|
||||
result = {}
|
||||
for name, count in totals.items():
|
||||
values = dict(count)
|
||||
denominator = values.get("samples", 0)
|
||||
values["paint_supported_fraction"] = (
|
||||
values.get("paint_supported", 0) / denominator if denominator else None
|
||||
)
|
||||
result[name] = values
|
||||
return dict(
|
||||
version=VERSION,
|
||||
**result,
|
||||
evidence_signature=digest.hexdigest(),
|
||||
# Ring/component ordering must not change floating summation order.
|
||||
geometry_area_m2=float(shapely.normalize(body).area),
|
||||
tiles=len(keys),
|
||||
cell_m=CELL,
|
||||
origin_xy=[0.0, 0.0],
|
||||
context_m=CONTEXT,
|
||||
admission_changed=False,
|
||||
metric_accuracy_measured=False,
|
||||
complete_recall_measured=False,
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Byte-bounded observation reuse for one container's ordered admission phase."""
|
||||
from collections import OrderedDict
|
||||
import time
|
||||
|
||||
|
||||
class ObservationCache:
|
||||
def __init__(self,loader,max_bytes):
|
||||
if type(max_bytes)is not int or max_bytes<=0:raise ValueError('Invalid observation memory budget')
|
||||
self.loader=loader;self.limit=max_bytes;self.values=OrderedDict();self.bytes=0
|
||||
self.hits=0;self.misses=0;self.evictions=0;self.peak_bytes=0;self.load_seconds=0.
|
||||
|
||||
def __call__(self,key):
|
||||
if key in self.values:
|
||||
self.hits+=1;value,size=self.values.pop(key);self.values[key]=(value,size);return value
|
||||
self.misses+=1;start=time.monotonic();value=self.loader(key);self.load_seconds+=time.monotonic()-start
|
||||
size=sum(array.nbytes for array in value)
|
||||
if size<=self.limit:
|
||||
while self.values and self.bytes+size>self.limit:
|
||||
_,(_,removed)=self.values.popitem(last=False);self.bytes-=removed;self.evictions+=1
|
||||
self.values[key]=(value,size);self.bytes+=size;self.peak_bytes=max(self.peak_bytes,self.bytes)
|
||||
return value
|
||||
|
||||
def report(self):
|
||||
return dict(hits=self.hits,misses=self.misses,evictions=self.evictions,peak_cached_bytes=self.peak_bytes,
|
||||
maximum_bytes=self.limit,load_seconds=self.load_seconds,lifetime='one admission process; no disk cache')
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Plan both required render footprints from the initial observed ground.
|
||||
|
||||
No detected object, prior map, semantic score or failed check is an input.
|
||||
The existing terrain bootstrap is unchanged; all high-resolution views are
|
||||
scheduled before the first high-resolution render.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import copy,json
|
||||
import numpy as np
|
||||
|
||||
POLICY=dict(sample_m=1.,camera_grid_m=10.,usable_half_width_m=27.,
|
||||
view_width_m=60.,required_views=2,max_additional_views=80)
|
||||
|
||||
def complete_coverage(points,centers,policy=POLICY):
|
||||
points=np.asarray(points,float).reshape(-1,2)
|
||||
centers=np.asarray(centers,float).reshape(-1,2)
|
||||
if not np.isfinite(points).all() or not np.isfinite(centers).all():
|
||||
raise ValueError('Nonfinite coverage geometry')
|
||||
if not len(points):raise ValueError('No observed-ground coverage targets')
|
||||
points=np.unique(points,axis=0)
|
||||
half=policy['usable_half_width_m'];required=policy['required_views']
|
||||
counts=(abs(points[:,None,:]-centers[None,:,:]).max(2)<=half).sum(1)
|
||||
before=counts.copy();step=policy['camera_grid_m']
|
||||
candidates=np.unique(np.round(points/step)*step,axis=0)
|
||||
candidates=np.asarray([c for c in candidates if not np.any(np.max(abs(centers-c),axis=1)<1e-6)])
|
||||
result=[]
|
||||
while np.any(counts<required):
|
||||
if len(result)>=policy['max_additional_views']:raise ValueError('Initial observation budget exceeded')
|
||||
if not len(candidates):raise ValueError('Cannot provide distinct observation footprints')
|
||||
covered=abs(candidates[:,None,:]-points[None,:,:]).max(2)<=half
|
||||
gains=(covered&(counts<required)).sum(1);i=int(np.argmax(gains))
|
||||
if gains[i]==0:raise ValueError('Uncovered initial ground domain')
|
||||
center=candidates[i].copy();result.append(dict(center=center.tolist(),new_coverage_samples=int(gains[i])))
|
||||
counts+=covered[i];candidates=np.delete(candidates,i,axis=0)
|
||||
return result,dict(target_samples=len(points),initial_two_view_samples=int((before>=required).sum()),
|
||||
planned_two_view_samples=int((counts>=required).sum()),minimum_views=int(counts.min()),
|
||||
additional_views=len(result),unknown_ground_inferred=False,object_input=False)
|
||||
|
||||
def plan(survey,index):
|
||||
survey=Path(survey);points=[]
|
||||
for tile in index['tiles']:
|
||||
path=survey/tile['id']/'surface-atlas.npz'
|
||||
if not path.is_file():continue
|
||||
with np.load(path)as z:
|
||||
depth=z['z'];cell=float(z['cell_m']);low=z['bounds'][0];stride=max(1,round(POLICY['sample_m']/cell))
|
||||
rr,cc=np.where(np.isfinite(depth[::stride,::stride]));rr*=stride;cc*=stride
|
||||
points.append(np.c_[low[0]+(cc+.5)*cell,low[1]+(depth.shape[0]-rr-.5)*cell])
|
||||
if not points:raise ValueError('Missing bootstrap observations')
|
||||
centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in index['tiles']])
|
||||
additions,report=complete_coverage(np.concatenate(points),centers)
|
||||
tiles=[];jobs={}
|
||||
for i,row in enumerate(additions):
|
||||
center=np.asarray(row['center']);nearest=index['tiles'][int(np.argmin(np.linalg.norm(centers-center,axis=1)))]
|
||||
job=copy.deepcopy(json.loads((survey/nearest['id']/'job.json').read_text()))
|
||||
name=f'primary-support-{i:03d}';bounds=[(center-30).tolist(),(center+30).tolist()]
|
||||
top=next(v for v in job['views']if v['id']=='top');delta=center-np.asarray(top['eye'][:2])
|
||||
top['eye'][:2]=center.tolist();top['target'][:2]=(np.asarray(top['target'][:2])+delta).tolist()
|
||||
job['bounds_xy']=bounds;jobs[name]=job
|
||||
tiles.append(dict(id=name,status='planned',bounds_xy=bounds,role='initial-two-view-support',**row))
|
||||
return tiles,jobs,dict(schema='missioncore.initial-observation-coverage/v1',policy=POLICY,**report)
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Bounded independent native-tile work; no map or cross-tile state."""
|
||||
from pathlib import Path
|
||||
import hashlib,json,time
|
||||
import numpy as np,cv2
|
||||
from shapely.geometry import mapping
|
||||
from scipy.ndimage import distance_transform_edt
|
||||
from layer_common import sample
|
||||
from fit_scene import world
|
||||
from search_views import SearchViews
|
||||
from primary_line_observations import extract
|
||||
from paint_observations import collect as paint_observations
|
||||
from catalog_observations import collect as catalog_observations
|
||||
from compact_observations import collect as compact_observations
|
||||
from crossing_discovery import primitives
|
||||
|
||||
|
||||
def initialize():
|
||||
global views,labels,low,high,road,inside,outside
|
||||
cv2.setNumThreads(2)
|
||||
cv2.setRNGSeed(2026)
|
||||
with np.load('/evidence_plan/fields.npz')as z:
|
||||
labels=z['labels'];low,high=z['bounds']
|
||||
road=labels==1
|
||||
inside=distance_transform_edt(road)*.1
|
||||
outside=distance_transform_edt(~road)*.1
|
||||
tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
views=SearchViews(tiles,labels,low,high,None)
|
||||
|
||||
|
||||
def collect_tile(tile):
|
||||
name=tile['id'];t0=time.monotonic()
|
||||
g=views.geometry(name);rgb,vehicle=views.inputs(name);size=rgb.shape[0];mpp=60/size
|
||||
def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g)
|
||||
yy,xx=np.mgrid[:1200,:1200];points=world(np.c_[xx.ravel(),yy.ravel()],g)
|
||||
allowed1200=(sample(inside,points,low,high)>.25).reshape(1200,1200)&(vehicle<.2)&(g['alpha']>.65)
|
||||
allowed=cv2.resize(allowed1200.astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0
|
||||
stages={};tic=time.monotonic()
|
||||
obs,rec=extract(rgb,allowed,xy,name,mpp)
|
||||
stages['linear']=time.monotonic()-tic;tic=time.monotonic()
|
||||
path=Path('/evidence_plan/evidence')/(name+'.npz')
|
||||
source=hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
with np.load(path)as z:marking=z['road marking'].astype('float32');cross=z['crosswalk'].astype('float32')
|
||||
pc,cc=paint_observations(rgb,vehicle,g,marking,cross,road,low,high,tile,road_dist=outside)
|
||||
paint=[dict(geometry=mapping(p),properties=props)for p,props in pc]
|
||||
crossbars=[dict(geometry=mapping(p),properties=props)for p,props in cc]
|
||||
stages['appearance']=time.monotonic()-tic;tic=time.monotonic()
|
||||
glyphs=catalog_observations(rgb,vehicle,g,labels,low,high,name)
|
||||
stages['catalog']=time.monotonic()-tic;tic=time.monotonic()
|
||||
compact=compact_observations(rgb,vehicle,g,labels,low,high,name)
|
||||
stages['compact']=time.monotonic()-tic;tic=time.monotonic()
|
||||
seeds=primitives(rgb,cross,vehicle,g,labels,low,high)
|
||||
stages['crossing']=time.monotonic()-tic
|
||||
report=dict(tile=name,seconds=time.monotonic()-t0,detectors=stages,linear=len(obs),paint=len(pc),crossbars=len(cc))
|
||||
return dict(lines=obs,paint=paint,crossbars=crossbars,glyphs=glyphs,compact=compact,seeds=seeds,report=report,source=source)
|
||||
|
||||
|
||||
def ordered_tiles(tiles,workers=4):
|
||||
"""At most eight submitted tiles; collect in the original source order."""
|
||||
if type(workers)is not int or not 1<=workers<=4:
|
||||
raise ValueError('Observation workers must be an integer from one to four')
|
||||
if workers==1:
|
||||
initialize()
|
||||
for tile in tiles:yield collect_tile(tile)
|
||||
return
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from multiprocessing import get_context
|
||||
from collections import deque
|
||||
pending=deque();source=iter(tiles)
|
||||
with ProcessPoolExecutor(max_workers=workers,mp_context=get_context('spawn'),initializer=initialize)as pool:
|
||||
for _ in range(workers*2):
|
||||
tile=next(source,None)
|
||||
if tile is None:break
|
||||
pending.append(pool.submit(collect_tile,tile))
|
||||
while pending:
|
||||
result=pending.popleft().result()
|
||||
tile=next(source,None)
|
||||
if tile is not None:pending.append(pool.submit(collect_tile,tile))
|
||||
yield result
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Preserve measured coordinates when there is no geometry to subtract.
|
||||
|
||||
Fitting another float32 rectangle is not an identity operation in world
|
||||
coordinates. It can shift sampling across a pixel/threshold boundary even
|
||||
when no existing paint occupies the proposed body. Actual fragmentation
|
||||
still uses the original exclusion distance and minimum-section policy.
|
||||
"""
|
||||
|
||||
from beta_profiles import describe
|
||||
from marking_rules import POLICY
|
||||
from marking_rules import missing_parts as fragmented_parts
|
||||
|
||||
|
||||
def missing_parts(polygon, existing):
|
||||
description = describe(polygon)
|
||||
if description is None:
|
||||
return []
|
||||
occupied = polygon.intersection(existing.buffer(0.10))
|
||||
if occupied.is_empty:
|
||||
return [polygon] if description["length"] >= POLICY["min_continuous_section_m"] else []
|
||||
return fragmented_parts(polygon, existing)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""One systematic acquisition: parallel-ray RGB and native depth/opacity."""
|
||||
from pathlib import Path
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import gc,json,time,math,os
|
||||
import numpy as np,torch,cv2
|
||||
from plyfile import PlyData
|
||||
from PIL import Image
|
||||
from gsplat import rasterization
|
||||
from mapping import camera,digest
|
||||
from coordinate_cache import transformed
|
||||
from ortho_terrain import from_survey,sample
|
||||
from spatial_index import SpatialIndex
|
||||
from orthographic_colour import colours
|
||||
from initial_views import plan as plan_coverage
|
||||
from array_archive import save as save_arrays
|
||||
|
||||
cv2.setNumThreads(1)
|
||||
S=Path('/base_survey');O=Path('/survey');E=Path('/evidence');P=Path('/input');R=Path('/run')
|
||||
cfg=json.loads((R/'config.json').read_text());method=cfg['method'];scene=os.environ['ORTHO_SCENE'];started=time.monotonic()
|
||||
N=R/'native-geometry'
|
||||
for d in [O,E,N,R/'diagnostics']:d.mkdir(exist_ok=True)
|
||||
trajectory=cfg['scenes'][scene]['trajectory'];trajectory=R/trajectory if trajectory else None
|
||||
field,route=from_survey(S,trajectory)
|
||||
save_arrays(R/'terrain-reference.npz',**field)
|
||||
(R/'terrain-report.json').write_text(json.dumps(route,indent=2))
|
||||
request=json.loads((S/'request.json').read_text());(O/'request.json').write_text(json.dumps(request))
|
||||
source=P/request['source']['ply'];assert digest(source)==request['source']['sha256']
|
||||
T=np.asarray(request['source']['source_to_world'])
|
||||
data=PlyData.read(source,mmap='r')['vertex'].data;world=transformed(data,T,str(source))
|
||||
relative=np.empty(len(data),np.float32)
|
||||
for begin in range(0,len(data),250000):
|
||||
xyz=world[begin:begin+250000];relative[begin:begin+len(xyz)]=xyz[:,2]-sample(field,xyz[:,:2])
|
||||
spatial=SpatialIndex(world,relative,method['lower_height_m'],method['context_height_m'])
|
||||
index=json.loads((S/'tile-index.json').read_text());records=[];native_records=[]
|
||||
additional,planned_jobs,coverage_report=plan_coverage(S,index)
|
||||
# The structural index is immutable; supplemental paint views live only in
|
||||
# the coverage manifest and never replace road/facade observers.
|
||||
(R/'observation-coverage.json').write_text(json.dumps(dict(**coverage_report,complete=False,tiles=additional),indent=2))
|
||||
native_n=method['render_pixels'];pending=[]
|
||||
|
||||
def persist(name,mode,a,v,view,k,begin,count):
|
||||
v[:,:,:3]+=1-a[:,:,None];im=np.uint8(np.clip(v[:,:,:3],0,1)*255)
|
||||
high=E/(name+'.'+mode+'.png');Image.fromarray(im).save(high,compress_level=1)
|
||||
small=cv2.resize(im,(1200,1200),interpolation=cv2.INTER_AREA);ak=k.copy();ak[:2,:]*=1200/native_n
|
||||
compatibility=dict(depth=cv2.resize(v[:,:,3],(1200,1200),interpolation=cv2.INTER_AREA),
|
||||
alpha=cv2.resize(a,(1200,1200),interpolation=cv2.INTER_AREA),view=view,intrinsics=ak)
|
||||
if mode=='context':
|
||||
Image.fromarray(small).save(O/name/'top.png',compress_level=1)
|
||||
save_arrays(O/name/'top.geometry.npz',**compatibility)
|
||||
else:
|
||||
Image.fromarray(small).save(E/(name+'.ground-dc.png'),compress_level=1)
|
||||
save_arrays(E/(name+'.ground-dc.geometry.npz'),**compatibility)
|
||||
native=N/(name+'.'+mode+'.npz')
|
||||
save_arrays(native,depth=v[:,:,3],alpha=a,view=view,intrinsics=k,compatibility_resolution=1200)
|
||||
rgb_hash=digest(high)
|
||||
return dict(tile=name,mode=mode,selected_splats=count,opaque_fraction=float((a>.8).mean()),
|
||||
sha256=rgb_hash,seconds=time.monotonic()-begin),dict(tile=name,mode=mode,file=native.name,
|
||||
sha256=digest(native),native_size=native_n,rgb_sha256=rgb_hash)
|
||||
|
||||
def finish_one():
|
||||
record,native=pending.pop(0).result();records.append(record);native_records.append(native)
|
||||
(R/'render-report.json').write_text(json.dumps(records,indent=2))
|
||||
(N/'native-geometry.json').write_text(json.dumps(dict(complete=False,records=native_records)))
|
||||
print('OBSERVATION',record['tile'],record['mode'],round(record['seconds'],2),flush=True)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4,thread_name_prefix='observation-writer')as writer:
|
||||
for tile in index['tiles']+additional:
|
||||
old=S/tile['id']/'job.json'
|
||||
if tile['id'] not in planned_jobs and not old.exists():continue
|
||||
assert __import__('shutil').disk_usage(R).free>8*2**30,'Qualification free-disk floor reached'
|
||||
name=tile['id'];folder=O/name;folder.mkdir(exist_ok=True);job=planned_jobs[tile['id']] if tile['id'] in planned_jobs else json.loads(old.read_text())
|
||||
top=next(v for v in job['views']if v['id']=='top');bounds=np.asarray(job['bounds_xy']);top['size']=[native_n,native_n]
|
||||
indices=spatial.query(np.asarray([bounds[0]-10,bounds[1]+10]))
|
||||
if not len(indices):tile['status']='no-ground-after-cut';continue
|
||||
d=data[indices].copy();dz=relative[indices];del indices
|
||||
for mode,upper in [('context',method['context_height_m']),('ground',method['ground_height_m'])]:
|
||||
if len(pending)>=4:finish_one()
|
||||
selected=d[dz<=upper]
|
||||
if not len(selected):raise ValueError('Incomplete ground observation')
|
||||
begin=time.monotonic()
|
||||
def tensor(names, values=selected):return torch.tensor(np.column_stack([values[n]for n in names]),device='cuda',dtype=torch.float32)
|
||||
means=tensor(['x','y','z']);quats=tensor([f'rot_{i}'for i in range(4)])
|
||||
scales=tensor([f'scale_{i}'for i in range(3)]).exp();opacity=tensor(['opacity']).squeeze(-1).sigmoid()
|
||||
dc=tensor([f'f_dc_{i}'for i in range(3)])[:,None,:]
|
||||
rest=sorted([n for n in d.dtype.names if n.startswith('f_rest_')],key=lambda n:int(n.split('_')[-1]))
|
||||
sh=torch.cat([dc,tensor(rest).reshape(len(selected),3,-1).transpose(1,2)],dim=1)if rest else dc
|
||||
degree=int(math.sqrt(sh.shape[1]))-1;view,k=camera(top)
|
||||
matrix=torch.tensor(view@T,device='cuda',dtype=torch.float32)
|
||||
# The structural/context observer retains its qualified colour
|
||||
# contract. Parallel-ray photometry belongs to the ground observer.
|
||||
rgb=colours(sh,matrix,degree) if mode=='ground' else sh
|
||||
render_degree=None if mode=='ground' else degree
|
||||
with torch.inference_mode():
|
||||
rendered,alpha,_=rasterization(means,quats,scales,opacity,rgb,matrix[None],
|
||||
torch.tensor(k,device='cuda')[None],native_n,native_n,sh_degree=render_degree,
|
||||
camera_model='ortho',render_mode='RGB+ED',packed=True)
|
||||
a=alpha[0,:,:,0].cpu().numpy();v=rendered[0].cpu().numpy()
|
||||
pending.append(writer.submit(persist,name,mode,a,v,view,k,begin,len(selected)))
|
||||
del means,quats,scales,opacity,dc,sh,rgb,rendered,alpha,a,v,selected
|
||||
del d,dz;gc.collect()
|
||||
top['size']=[1200,1200];(folder/'job.json').write_text(json.dumps(job));tile['status']='surveyed'
|
||||
while pending:finish_one()
|
||||
count=sum(t['status']=='surveyed'for t in index['tiles']+additional)
|
||||
(R/'observation-coverage.json').write_text(json.dumps(dict(**coverage_report,complete=True,tiles=additional,native_records=[]),indent=2))
|
||||
assert len(native_records)==count*2
|
||||
(O/'tile-index.json').write_text(json.dumps(index))
|
||||
(N/'native-geometry.json').write_text(json.dumps(dict(version='native-systematic-geometry-v1',complete=True,
|
||||
records=native_records,tiles=sum(t['status']=='surveyed'for t in index['tiles']),source_sha256=request['source']['sha256'],
|
||||
terrain_sha256=digest(R/'terrain-reference.npz'),photometry=dict(ground='parallel-optical-axis-SH',context='qualified-camera-centre-SH'),
|
||||
writer_workers=4,writer_queue_limit=4,array_compression='lossless-deflate-1',manual_rois=[],seconds=time.monotonic()-started),indent=2))
|
||||
(R/'render-summary.json').write_text(json.dumps(dict(scene=scene,source_splats=len(data),rendered_tiles=count,
|
||||
native_pixel_m=60/native_n,seconds=time.monotonic()-started,trajectory=route,manual_rois=[],
|
||||
native_depth_retained=True,additional_render_passes=0,photometry=dict(ground='parallel-optical-axis-SH',context='qualified-camera-centre-SH')),indent=2))
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Keep the evidence footprint fixed across replacements within one fresh run.
|
||||
|
||||
The tolerance belongs to the original observed paint, not to each edit in a
|
||||
chain. No baseline or previous-run geometry is loaded here.
|
||||
"""
|
||||
import numpy as np
|
||||
import shapely
|
||||
from marking_rules import POLICY,validate_removed
|
||||
|
||||
|
||||
class PaintConservation:
|
||||
def __init__(self):
|
||||
self.footprints={}
|
||||
|
||||
def inherited(self,ids,current,geometry):
|
||||
return shapely.union_all([self.footprints.get(i,geometry(current[i])) for i in ids])
|
||||
|
||||
def validate(self,ids,current,geometry,new,candidate,readers):
|
||||
old=self.inherited(ids,current,geometry)
|
||||
removed=old.difference(new.buffer(POLICY['retained_paint_tolerance_m']))
|
||||
if not removed.is_empty:
|
||||
normal=np.array([-candidate['axis'][1],candidate['axis'][0]])
|
||||
offsets=(shapely.get_coordinates(removed)-candidate['origin'])@normal
|
||||
if np.max(abs(offsets))>.7:
|
||||
return False,dict(reason='ancestral-paint-outside-measurement')
|
||||
passed,evidence=validate_removed(old,new,candidate,readers)
|
||||
return passed,dict(reason='fixed-observation-footprint',views=evidence)
|
||||
|
||||
def committed(self,ids,current_before,geometry,features):
|
||||
inherited=self.inherited(ids,current_before,geometry)
|
||||
complete=shapely.union_all([inherited]+[geometry(f) for f in features])
|
||||
for i in ids:self.footprints.pop(i,None)
|
||||
for f in features:
|
||||
# A split transfers only the local footprint to each child. Its
|
||||
# preservation was checked jointly before the transaction committed.
|
||||
self.footprints[f['id']]=complete.intersection(geometry(f).buffer(POLICY['max_join_gap_m']))
|
||||
@@ -0,0 +1,50 @@
|
||||
from pathlib import Path
|
||||
import numpy as np, cv2, shapely
|
||||
from shapely.geometry import Polygon
|
||||
from scipy.ndimage import distance_transform_edt
|
||||
from layer_common import sample
|
||||
from fit_scene import world
|
||||
|
||||
def collect(im,vehicle,g,marking,cross,road,low,high,tile,road_dist=None,*,span_m=60.0,retain_uncertain=False,valid=None):
|
||||
# Offline proposal study only: retaining uncertain context never admits an object.
|
||||
# Defaults preserve the production search and support gates.
|
||||
if span_m<=0:raise ValueError("span_m must be positive")
|
||||
paint_candidates=[];cross_candidates=[];name=tile['id'];cell=.1
|
||||
if road_dist is None:road_dist=distance_transform_edt(~road)*cell
|
||||
size=im.shape[0];mpp=span_m/size;small=lambda a:cv2.resize(a.astype('float32'),(size,size),interpolation=cv2.INTER_LINEAR)
|
||||
marking=small(marking);cross=small(cross);vehicles=cv2.dilate((small(vehicle)>.25).astype('uint8'),np.ones((max(3,int(.25/mpp)),)*2,np.uint8))>0
|
||||
hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV);gray=cv2.cvtColor(im,cv2.COLOR_RGB2GRAY);contrast=gray.astype('float32')-cv2.GaussianBlur(gray.astype('float32'),(0,0),.35/mpp)
|
||||
paint=((hsv[:,:,1]<85)&(gray>115)&(contrast>9))|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>55)&(gray>100)&(contrast>5))
|
||||
yy,xx=np.mgrid[:1200,:1200];points=world(np.c_[xx.ravel(),yy.ravel()],g)
|
||||
road_patch=cv2.resize(sample(road.astype('uint8'),points,low,high).reshape(1200,1200),(size,size),interpolation=cv2.INTER_NEAREST)>0
|
||||
strong=((hsv[:,:,1]<70)&(gray>130)&(contrast>12))|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>55)&(gray>100)&(contrast>5))
|
||||
channels=[('semantic-paint-v1',strong&((marking>.3)|(cross>.3))&~vehicles),
|
||||
('appearance-paint-v1',paint&(road_patch|retain_uncertain)&~vehicles)]
|
||||
physical=np.ones((size,size),bool) if valid is None else small(valid)>.65
|
||||
for contract,candidate in channels:
|
||||
candidate=candidate&physical
|
||||
candidate=cv2.morphologyEx(candidate.astype('uint8'),cv2.MORPH_CLOSE,np.ones((max(3,int(.04/mpp)),)*2,np.uint8))
|
||||
candidate[~physical]=0
|
||||
contours,hier=cv2.findContours(candidate,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
|
||||
if hier is None:continue
|
||||
def xy_native(p):return world((np.asarray(p)+.5)*1200/size-.5,g)
|
||||
for i,c in enumerate(contours):
|
||||
if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.06:continue
|
||||
rect=cv2.minAreaRect(c);short,long=sorted(rect[1]);short*=mpp;long*=mpp
|
||||
if short<.045 or long<.35 or short>5:continue
|
||||
ring=cv2.approxPolyDP(c,.035/mpp,True)[:,0];holes=[];j=hier[0,i,2]
|
||||
while j>=0:
|
||||
if cv2.contourArea(contours[j])*mpp*mpp>.03:holes.append(xy_native(cv2.approxPolyDP(contours[j],.035/mpp,True)[:,0]))
|
||||
j=hier[0,j,0]
|
||||
poly=shapely.make_valid(Polygon(xy_native(ring),holes))
|
||||
if poly.geom_type!='Polygon':continue
|
||||
coords=np.array(poly.exterior.coords);supported=np.mean(sample(road_dist,coords,low,high)<.75)
|
||||
if supported<.5 and not retain_uncertain:continue
|
||||
rxy=np.rint(rect[0]).astype(int);rxy=np.clip(rxy,0,size-1);is_cross=cross[rxy[1],rxy[0]]>.3
|
||||
if is_cross and .18<short<1.2 and 1.0<long<12 and long/short>2 and poly.area/(short*long)>.55:
|
||||
box=Polygon(xy_native(cv2.boxPoints(rect)));cross_candidates.append((box,dict(source_tile=name,subtype='crosswalk',method='parametric-rectangle')))
|
||||
else:
|
||||
x,y,bw,bh=cv2.boundingRect(c);patch=np.zeros((bh,bw),np.uint8);cv2.drawContours(patch,[c-np.array([[[x,y]]])],-1,1,-1)
|
||||
values=marking[y:y+bh,x:x+bw][patch>0]
|
||||
paint_candidates.append((poly,dict(source_tile=name,proposal_contract=contract,semantic_support=float(np.mean(values)),semantic_peak=float(np.quantile(values,.9)))))
|
||||
return paint_candidates,cross_candidates
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Template hypotheses in metric object coordinates; never site coordinates."""
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import Polygon,LineString
|
||||
from shapely.ops import unary_union
|
||||
from shapely.affinity import rotate,translate
|
||||
from scipy.optimize import minimize
|
||||
from road_glyph_presets import arrow
|
||||
|
||||
def template(kind,L,W,stroke):
|
||||
if kind!='letter_A':return arrow(kind,L,W,stroke)
|
||||
# A is an original parametric preset. Arrows use the attributed SVG library.
|
||||
outer=LineString([(0,-W/2),(L,0),(0,W/2)]).buffer(stroke/2,cap_style=2,join_style=3)
|
||||
bar=LineString([(L*.3,-W*.35),(L*.3,W*.35)]).buffer(stroke/2,cap_style=2)
|
||||
return unary_union([outer,bar])
|
||||
|
||||
def fit_symbol(p,heading=None,diagnostics=None,allowed_kinds=None):
|
||||
if p.geom_type!='Polygon' or p.area<.25:return None
|
||||
points=np.array(p.exterior.coords)[:,:2];rect=cv2.minAreaRect(points.astype('float32'));corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));u=edges[k]/np.linalg.norm(edges[k]);L=np.linalg.norm(edges[k]);W=min(rect[1]);origin=np.array(rect[0]);ang=np.arctan2(u[1],u[0]);fill=p.area/(L*W)
|
||||
if not (1.2<L<9 and .35<W<3 and L/W>1.2 and .09<fill<.75):return None
|
||||
# A fixed-resolution local evidence patch avoids manipulating full scene pixels.
|
||||
cell=.04;lo=np.array(p.bounds[:2])-.6;hi=np.array(p.bounds[2:])+.6;shape=np.ceil((hi-lo)/cell).astype(int)[::-1]
|
||||
if max(shape)>350:return None
|
||||
target=np.zeros(shape,np.uint8)
|
||||
def draw(poly):
|
||||
out=np.zeros(shape,np.uint8)
|
||||
for part in ([poly] if poly.geom_type=='Polygon' else getattr(poly,'geoms',[])):
|
||||
if part.geom_type!='Polygon' or part.is_empty:continue
|
||||
cv2.fillPoly(out,[np.rint((np.array(part.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
|
||||
for hole in part.interiors:cv2.fillPoly(out,[np.rint((np.array(hole.coords)[:,:2]-lo)/cell).astype('int32')],0)
|
||||
return out
|
||||
target=draw(p);expanded=cv2.dilate(target,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
|
||||
# The counter supplies a strong object identity cue, independent of a noisy
|
||||
# semantic mask. A bounded 8 cm closing tolerates small wear breaks.
|
||||
closed=p.buffer(.08).buffer(-.08)
|
||||
counters=[Polygon(h)for part in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if part.geom_type=='Polygon'for h in part.interiors]
|
||||
has_counter=any(h.area>.05*L*W for h in counters)
|
||||
variants=['letter_A']if has_counter else ['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow'];best=None
|
||||
if heading is not None:ang=float(np.arctan2(heading[1],heading[0]))
|
||||
for kind in variants:
|
||||
if allowed_kinds is not None and kind not in allowed_kinds:continue
|
||||
for flip in [0,np.pi]:
|
||||
a=ang+flip;uu=np.array([np.cos(a),np.sin(a)]);base=origin-uu*L/2
|
||||
x0=np.array([base[0],base[1],a,L,W,.16]);bounds=[(base[0]-.4,base[0]+.4),(base[1]-.4,base[1]+.4),(a-.16,a+.16),(L*.85,L*1.15),(W*.75,W*1.25),(.08,.32)]
|
||||
def polygon(x):
|
||||
m=template(kind,x[3],x[4],x[5]);m=rotate(m,x[2],origin=(0,0),use_radians=True);return translate(m,x[0],x[1])
|
||||
def loss(x):
|
||||
m=draw(polygon(x));wide=cv2.dilate(m,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
|
||||
coverage=(m&expanded).sum()/max(m.sum(),1);recall=(wide&target).sum()/max(target.sum(),1)
|
||||
overlap=(m&target).sum()/max((m|target).sum(),1)
|
||||
return 1-(.6*2*coverage*recall/max(coverage+recall,1e-6)+.4*overlap)+.03*abs(x[3]/L-1)
|
||||
score=loss(x0)
|
||||
if kind!='letter_A' and (W<.60 or W/x0[5]<3.5):continue
|
||||
# A worn letter may have an open counter; missing topology is not a veto.
|
||||
if score>.8:continue
|
||||
fit=minimize(loss,x0,method='Powell',bounds=bounds,options=dict(maxiter=25,xtol=.004,ftol=.004));m=polygon(fit.x);r=draw(m)
|
||||
coverage=float((r&expanded).sum()/max(r.sum(),1));recall=float((cv2.dilate(r,np.ones((5,5),np.uint8))&target).sum()/max(target.sum(),1));f1=2*coverage*recall/max(coverage+recall,1e-6);overlap=float((r&target).sum()/max((r|target).sum(),1));score=.6*f1+.4*overlap
|
||||
if diagnostics is not None:diagnostics.append(dict(kind=kind,coverage=coverage,recall=recall,score=score,overlap=overlap,counter=has_counter,parameters=fit.x.tolist()))
|
||||
if kind=='letter_A':
|
||||
x=fit.x;bar=LineString([(x[3]*.3,-x[4]*.30),(x[3]*.3,x[4]*.30)]).buffer(x[5]/2,cap_style=2)
|
||||
bar=translate(rotate(bar,x[2],origin=(0,0),use_radians=True),x[0],x[1]);support=draw(bar)
|
||||
if (support&expanded).sum()/max(support.sum(),1)<.6:continue
|
||||
# Positive shape overlap alone confuses arrow heads and triangular signs
|
||||
# with A. Its counter is negative evidence and must stay largely unpainted.
|
||||
holes=unary_union([Polygon(h)for part in ([m]if m.geom_type=='Polygon'else m.geoms)if part.geom_type=='Polygon'for h in part.interiors])
|
||||
core=holes.buffer(-.08)
|
||||
mask=draw(core)
|
||||
if mask.sum()<8 or (mask&expanded).sum()/mask.sum()>.15:continue
|
||||
elif kind.startswith('straight_') and kind!='straight_arrow':
|
||||
# A compound arrow needs its lateral branch, even if a straight arrow
|
||||
# alone matches most of the template area.
|
||||
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
|
||||
yy,xx=np.mgrid[:r.shape[0],:r.shape[1]];xy=np.stack([lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]],axis=-1);side=xy@n
|
||||
# Artwork is bbox-centered; use the outer quarter on the branch side.
|
||||
sign=1 if 'left'in kind else -1
|
||||
branch=(r>0)&(side*sign>x[4]*.24)
|
||||
if branch.sum()<5 or (branch&expanded).sum()/branch.sum()<.8:continue
|
||||
longitudinal=xy@u;head=(r>0)&(longitudinal>x[3]*.8)
|
||||
if head.sum()<5 or (head&expanded).sum()/head.sum()<.85:continue
|
||||
elif kind in ['left_arrow','right_arrow']:
|
||||
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
|
||||
yy,xx=np.nonzero(target);xy=np.c_[lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]];longitudinal=xy@u;side=xy@n
|
||||
front=side[longitudinal>x[3]*.72];tail=side[longitudinal<x[3]*.32];sign=1 if kind=='left_arrow'else -1
|
||||
if len(front)<5 or len(tail)<5 or sign*(np.mean(front)-np.mean(tail))<.22*x[4]:continue
|
||||
if coverage>=.72 and recall>=.86 and (best is None or score>best[1]):best=(m,score,kind,recall,fit.x.tolist())
|
||||
if best and best[1]>=.80:return best
|
||||
return None
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Admit an observed pair under the unchanged body/dark-context thresholds.
|
||||
|
||||
The companion is measured paint, so it is not an asphalt flank. Both external
|
||||
flanks and the separator must be dark; both complete bodies must be supported.
|
||||
No inferred companion, source-map geometry or fallback threshold is accepted.
|
||||
"""
|
||||
import numpy as np,shapely
|
||||
from interval_profiles import resolve_pair,strip
|
||||
from beta_profiles import describe
|
||||
from marking_rules import POLICY
|
||||
|
||||
def evidence(p,companion,readers):
|
||||
d=describe(p)
|
||||
if d is None:return False,[]
|
||||
n=np.array([-d['axis'][1],d['axis'][0]])
|
||||
other=describe(companion)
|
||||
if other is None or abs(d['axis']@other['axis'])<np.cos(np.deg2rad(3)):return False,[]
|
||||
off=float((other['origin']-d['origin'])@n);sign=1 if off>0 else -1
|
||||
near=d['width']/2+.025;far=abs(off)-other['width']/2-.025
|
||||
if far-near<.04:return False,[]
|
||||
ts=np.arange(-d['length']/2+.04,d['length']/2-.04,.025)
|
||||
ns=np.arange(-.7,.701,.025)
|
||||
core=abs(ns)<=max(.025,min(.04,d['width']*.2))
|
||||
outer=(ns*sign<=-d['width']/2-.08)&(ns*sign>=-d['width']/2-.14)
|
||||
separator=(ns*sign>=near)&(ns*sign<=far)
|
||||
if not len(ts)or not outer.any()or separator.sum()<2:return False,[]
|
||||
rows=[]
|
||||
for read in readers:
|
||||
con,valid=strip(d['origin'],d['axis'],ts,ns,read)
|
||||
signal=np.median(con[:,core],axis=1);cut=max(15.,.35*float(np.median(signal)))
|
||||
rows.append(dict(valid=float(valid[:,core].mean()),support=float((signal>cut).mean()),
|
||||
contrast=float(np.median(signal)),dark_flank=float((con[:,outer]<cut).mean()),
|
||||
flank_valid=float(valid[:,outer].mean()),dark_separator=float((con[:,separator]<cut).mean()),
|
||||
separator_valid=float(valid[:,separator].mean())))
|
||||
passed=len(rows)==2 and all(r['valid']>=POLICY['min_valid'] and r['support']>=POLICY['min_paint_support']
|
||||
and r['contrast']>=POLICY['min_contrast'] and r['dark_flank']>=POLICY['min_dark_flank']
|
||||
and r['flank_valid']>=.95 and r['dark_separator']>=POLICY['min_dark_flank'] and r['separator_valid']>=.95 for r in rows)
|
||||
return passed,rows
|
||||
|
||||
def proposal(seed_polygon,readers):
|
||||
primary=resolve_pair(seed_polygon,readers[0])
|
||||
if primary is None:return None
|
||||
secondary=resolve_pair(seed_polygon,readers[1])
|
||||
if secondary is None:return None
|
||||
output=[];proof=[];tracks=set()
|
||||
for i,track in enumerate(primary['tracks']):
|
||||
companions=primary['tracks'][1-i]['polygons']
|
||||
for p,kind in track['polygons']:
|
||||
matches=[q for t in secondary['tracks']for q,k in t['polygons']if k==kind and p.intersection(q).area/max(p.union(q).area,1e-9)>=.65]
|
||||
if not matches:continue
|
||||
companion=min((q for q,k in companions),key=lambda q:q.distance(p))
|
||||
passed,ev=evidence(p,companion,readers)
|
||||
if passed:output.append(p);proof.append(dict(kind=kind,views=ev));tracks.add(i)
|
||||
if len(output)<2 or len(tracks)!=2:return None
|
||||
return dict(polygons=output,origin=primary['origin'],axis=primary['axis'],domain=primary['domain'],
|
||||
width=float(np.median([t['width']for t in primary['tracks']])),evidence=proof)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Pre-plan a uniform visible-ground grid and compact seeds, independent of maps.
|
||||
|
||||
Camera choices and visibility thresholds match prepare_topdown. Evaluation is
|
||||
grouped by source image so native depth is decoded once per camera rank group.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
import json,time,os
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from fit_scene import world,project
|
||||
from ground_observations import GroundObservations,POLICY,sha
|
||||
|
||||
def schedule_uniform(obs):
|
||||
bounds=np.asarray([t['bounds_xy']for t in obs.tiles]);low,high=bounds[:,0].min(0),bounds[:,1].max(0)
|
||||
step,width=POLICY['stride_m'],POLICY['window_m'];origin=np.floor(low/step)*step
|
||||
offset=np.arange(-step/2+.25,step/2,.5);ox,oy=np.meshgrid(offset,offset);samples=np.c_[ox.ravel(),oy.ravel()]
|
||||
cells=[]
|
||||
for ix in range(int(np.ceil((high[0]-origin[0])/step))):
|
||||
for iy in range(int(np.ceil((high[1]-origin[1])/step))):
|
||||
center=origin+(np.array([ix,iy])+.5)*step;choices=[]
|
||||
for k in np.argsort(np.linalg.norm(obs.centers-center,axis=1),kind='stable'):
|
||||
if np.linalg.norm(obs.centers[k]-center)>43:continue
|
||||
name=obs.tiles[k]['id'];g=obs.camera(name)
|
||||
uv=project(center+np.array([[-1,-1],[1,-1],[1,1],[-1,1]])*width/2,g)
|
||||
if uv.min()<10 or uv.max()>=1190:continue
|
||||
choices.append((name,uv))
|
||||
cells.append(dict(id=f'ground-{ix:04d}-{iy:04d}',center=center,choices=choices,reason='no-covering-observation'))
|
||||
# Evaluate visibility once per source image. Camera ordering and the
|
||||
# first admissible choice remain exactly the qualified planner's order.
|
||||
by_tile=defaultdict(list)
|
||||
for i,c in enumerate(cells):
|
||||
for rank,(name,uv)in enumerate(c['choices']):by_tile[name].append((i,rank))
|
||||
fractions={}
|
||||
for name,items in sorted(by_tile.items()):
|
||||
points=np.concatenate([cells[i]['center']+samples for i,rank in items])
|
||||
values=obs.surface(name,points).reshape(len(items),len(samples)).mean(axis=1)
|
||||
fractions.update({(i,rank):float(value)for (i,rank),value in zip(items,values)})
|
||||
scheduled={}
|
||||
for i,c in enumerate(cells):
|
||||
for rank,(name,uv)in enumerate(c['choices']):
|
||||
fraction=fractions[i,rank]
|
||||
c.update(reason='insufficient-observed-ground',observed_core_fraction=fraction)
|
||||
if fraction<POLICY['core_fraction']:continue
|
||||
scheduled[i]=dict(id=c['id'],source_tile=name,uv=uv.tolist(),proposal=dict(source='observed-ground-grid'))
|
||||
c.update(reason='scheduled',source_tile=name)
|
||||
break
|
||||
ledger=[{k:(v.tolist()if isinstance(v,np.ndarray)else v)for k,v in c.items()if k!='choices'}for c in cells]
|
||||
return [scheduled[i]for i in sorted(scheduled)],ledger
|
||||
|
||||
def prepare(out='/out'):
|
||||
out=Path(out);folder=out/'symbol-patches';folder.mkdir(exist_ok=True);start=time.monotonic()
|
||||
obs=GroundObservations()
|
||||
if obs.native is None:raise ValueError('Primary symbols require the first-pass native observation set')
|
||||
inventory=obs.inventory();planned,ledger=schedule_uniform(obs)
|
||||
centers=[]
|
||||
for seed in sorted(json.loads((out/'compact-seeds.json').read_text()),key=lambda s:(s['center'][0],s['center'][1],s['source'])):
|
||||
center=np.asarray(seed['center'])
|
||||
if any(np.linalg.norm(center-c)<.65 for c in centers):continue
|
||||
centers.append(center)
|
||||
for k in np.argsort(np.linalg.norm(obs.centers-center,axis=1),kind='stable'):
|
||||
name=obs.tiles[k]['id'];uv=project(center+np.array([[-1,-1],[1,-1],[1,1],[-1,1]])*1.5,obs.camera(name))
|
||||
if uv.min()<10 or uv.max()>=1190:continue
|
||||
planned.append(dict(id=f'compact-{len(centers)-1:04d}',source_tile=name,uv=uv.tolist(),proposal=seed));break
|
||||
by_tile=defaultdict(list)
|
||||
for i,p in enumerate(planned):by_tile[p['source_tile']].append((i,p))
|
||||
patches={}
|
||||
for name,items in sorted(by_tile.items()):
|
||||
rgb=obs.rgb(name);size=rgb.shape[0];g=obs.camera(name)
|
||||
for i,p in items:
|
||||
native=(np.asarray(p['uv'])+.5)*size/1200-.5
|
||||
x0,y0=np.floor(native.min(0)).astype(int);x1,y1=np.ceil(native.max(0)).astype(int)
|
||||
crop=rgb[y0:y1,x0:x1];path=folder/(p['id']+'.png');Image.fromarray(crop).save(path,compress_level=1)
|
||||
corners=world((np.array([[x0,y0],[x1,y0],[x1,y1],[x0,y1]])+.5)*1200/size-.5,g)
|
||||
patches[i]=dict(id=p['id'],source_tile=name,box_native=[int(x0),int(y0),int(x1),int(y1)],native_size=size,
|
||||
world_corners=corners.tolist(),width_px=crop.shape[1],height_px=crop.shape[0],mpp=60/size,
|
||||
sha256=sha(path),proposal=p['proposal'])
|
||||
print('PATCH_TILE',name,len(items),flush=True)
|
||||
manifest=dict(scene=os.environ['SCENE'],patches=[patches[i]for i in range(len(planned))],policy=POLICY,
|
||||
compact_policy=dict(window_m=3.,separation_m=.65),version='primary-visible-ground-symbols-v2',manual_rois=[],
|
||||
observation_snapshot=inventory['snapshot'],selection='uniform observed ground and first-pass compact topology',
|
||||
perspective_mask_input=False,seconds=time.monotonic()-start)
|
||||
(out/'symbol-patches.json').write_text(json.dumps(manifest,indent=2))
|
||||
(out/'ground-observation-inventory.json').write_text(json.dumps(inventory,indent=2))
|
||||
(out/'coverage-ledger.json').write_text(json.dumps(dict(cells=ledger,policy=POLICY,inferred_coverage=False),indent=2))
|
||||
print('PREPARED',len(patches),'SECONDS',time.monotonic()-start,flush=True)
|
||||
|
||||
if __name__=='__main__':prepare()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Form physical paint components once, retaining the exact positive union.
|
||||
|
||||
Overlapping views and primary channels may describe the same paint repeatedly.
|
||||
Union removes that multiplicity before selecting axes. It adds no buffer, hull,
|
||||
closing operation or filled hole. Raw observations remain the scoring evidence;
|
||||
these components only propose axes for the unchanged two-view admission.
|
||||
"""
|
||||
import shapely
|
||||
from shapely.geometry import shape
|
||||
from component_axis import preferred
|
||||
|
||||
|
||||
def collect(records):
|
||||
polygons=[shapely.force_2d(shape(r['geometry'])) for r in records]
|
||||
merged=shapely.union_all(polygons)
|
||||
components=list(shapely.get_parts(merged)) if not merged.is_empty else []
|
||||
components=[p for p in components if p.geom_type=='Polygon' and not p.is_empty]
|
||||
components.sort(key=lambda p:(*p.bounds,p.wkb_hex))
|
||||
seeds=[s for p in components if (s:=preferred(p)) is not None]
|
||||
return seeds,dict(raw_components=len(polygons),physical_components=len(components),axis_seeds=len(seeds),
|
||||
added_geometry=False,positive_area_m2=float(merged.area),selection='exact-positive-union-before-axis-measurement')
|
||||
|
||||
|
||||
def qualify():
|
||||
import numpy as np
|
||||
from shapely.geometry import box,mapping,Polygon
|
||||
def rows(items):return [dict(geometry=mapping(p))for p in items]
|
||||
p=box(0,0,3,.12);q=box(1,0,4,.12);other=box(0,.2,4,.32)
|
||||
seeds,proof=collect(rows([p,p,q,other]))
|
||||
assert proof['raw_components']==4 and proof['physical_components']==2 and len(seeds)==2
|
||||
assert abs(proof['positive_area_m2']-p.union(q).union(other).area)<1e-10
|
||||
reversed_seeds,reversed_proof=collect(rows([other,q,p,p]))
|
||||
assert proof==reversed_proof
|
||||
for a,b in zip(seeds,reversed_seeds):
|
||||
for key in ['origin','axis','length','width']:np.testing.assert_array_equal(a[key],b[key])
|
||||
hole=Polygon([(0,0),(4,0),(4,1),(0,1)],holes=[[(1,.2),(3,.2),(3,.8),(1,.8)]])
|
||||
_,proof=collect(rows([hole,hole]));assert abs(proof['positive_area_m2']-hole.area)<1e-10
|
||||
assert collect([])[0]==[]
|
||||
print('PRIMARY_COMPONENT_CONTRACT_OK',flush=True)
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Immutable evidence from all primary paint channels, before assembly.
|
||||
|
||||
Connected paint contours and independently measured line-strip proposals are
|
||||
separate detectors. Absence from one channel cannot veto the other. The union
|
||||
is scored on one physical lattice; overlap never earns a second reward. These
|
||||
observations rank only configurations which already passed admission.
|
||||
"""
|
||||
|
||||
def collect(appearance,lines):
|
||||
records=list(appearance)
|
||||
for row in lines:
|
||||
if not row.get('source_tile'):raise ValueError('Primary strip lacks source provenance')
|
||||
records.append(dict(geometry=row['polygon'],properties=dict(source_tile=row['source_tile'],proposal_contract='primary-observed-line-strip')))
|
||||
return records
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Primary contour decomposition; legacy arrow extraction stays byte-locked."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
from line_reconstruction import observation
|
||||
|
||||
def extract(rgb,allowed,xy,source,mpp):
|
||||
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
|
||||
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.6/mpp)//2*2+1,)*2)
|
||||
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel)
|
||||
white=(hsv[:,:,1]<100)&(gray>100);yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>50)&(gray>100)
|
||||
binary=((ridge>12)&(white|yellow)&allowed).astype('uint8')
|
||||
binary=cv2.morphologyEx(binary,cv2.MORPH_CLOSE,np.ones((3,3),np.uint8))
|
||||
cc,_=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);records=[]
|
||||
for c in cc:
|
||||
if cv2.contourArea(c)*mpp*mpp<.02:continue
|
||||
o=observation(xy(c[:,0]),source);L,W=o['L'],o['W'];area=cv2.contourArea(c)*mpp*mpp
|
||||
if .26<L<65 and .045<W<.45 and L/W>2.0 and area/(L*W)>.48:records.append(o)
|
||||
from connected_ridges import branches
|
||||
for box in branches(c,binary,mpp):
|
||||
records.append(observation(xy(box),source,'connected-ridge-branch'))
|
||||
# Connected stop lines/crossing remnants must not erase long thin strips.
|
||||
lines=cv2.HoughLinesP(binary,1,np.pi/720,threshold=max(25,int(1.5/mpp)),minLineLength=2.8/mpp,maxLineGap=.10/mpp)
|
||||
if lines is not None:
|
||||
for x1,y1,x2,y2 in lines[:,0]:
|
||||
a=np.array([x1,y1],float);b=np.array([x2,y2],float);u=b-a;L=np.linalg.norm(u);u/=L;n=np.array([-u[1],u[0]])
|
||||
ts=np.arange(0,L, max(1,.1/mpp));ns=np.arange(-.22/mpp,.22/mpp+1);uv=a+ts[:,None,None]*u+ns[None,:,None]*n
|
||||
val=cv2.remap(binary,uv[:,:,0].astype('float32'),uv[:,:,1].astype('float32'),cv2.INTER_NEAREST);cnt=val.sum(1)
|
||||
good=(cnt>=.04/mpp)&(cnt<=.30/mpp)
|
||||
if np.mean(good)<.80:continue
|
||||
gaps=np.flatnonzero(np.diff(np.r_[False,~good,False].astype('int8')))
|
||||
if len(gaps) and max(gaps[1::2]-gaps[::2])*.1>.25:continue
|
||||
offsets=np.divide(val@ns,cnt,out=np.zeros(len(cnt)),where=cnt>0);points=a+ts[good,None]*u+offsets[good,None]*n
|
||||
fit=cv2.fitLine(points.astype('float32'),cv2.DIST_HUBER,0,.001,.001).ravel();u=fit[:2];origin=fit[2:];n=np.array([-u[1],u[0]])
|
||||
if np.quantile(abs((points-origin)@n),.90)*mpp>.045:continue
|
||||
width=float(np.median(cnt[good])*mpp);t=(points-origin)@u;box=origin+np.array([[t.min(),-width/(2*mpp)],[t.max(),-width/(2*mpp)],[t.max(),width/(2*mpp)],[t.min(),width/(2*mpp)]])@np.stack([u,n]);o=observation(xy(box),source,'hough-ridge')
|
||||
if o['L']>2.7:records.append(o)
|
||||
return records,dict(raw_components=len(cc),linear_observations=len(records))
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Prove batch camera selection equals the existing complete-strip predicate."""
|
||||
from pathlib import Path
|
||||
import json,time
|
||||
import numpy as np,shapely
|
||||
from search_views import SearchViews
|
||||
from row_evidence import choose_owners,POLICY
|
||||
from fit_scene import project
|
||||
|
||||
def run():
|
||||
with np.load('/evidence_plan/fields.npz') as z:labels=z['labels'];low,high=z['bounds']
|
||||
tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles'] if t['status']=='surveyed']
|
||||
views=SearchViews(tiles,labels,low,high,shapely.GeometryCollection())
|
||||
random=np.random.default_rng(20261018);cases=[]
|
||||
for i in range(120):
|
||||
origin=views.centers[i%len(views.centers)]+random.uniform(-30,30,2)
|
||||
theta=random.uniform(-np.pi,np.pi);axis=np.array([np.cos(theta),np.sin(theta)])
|
||||
cases.append((origin,axis,np.arange(-random.uniform(.5,30),random.uniform(.5,30),.025)))
|
||||
old=[];started=time.monotonic()
|
||||
for origin,axis,ts in cases:
|
||||
n=np.array([-axis[1],axis[0]]);centers=origin+ts[:,None]*axis
|
||||
distance=np.linalg.norm(centers[:,None,:]-views.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool)
|
||||
for i,tile in enumerate(views.tiles):
|
||||
a=project(centers-POLICY['coverage_half_width_m']*n,views.geometry(tile['id']))
|
||||
b=project(centers+POLICY['coverage_half_width_m']*n,views.geometry(tile['id']))
|
||||
uv=np.concatenate([a,b],axis=1);m=POLICY['coverage_margin_px'];coverage[:,i]=(uv.min(1)>=m)&(uv.max(1)<1200-m)
|
||||
old.append(choose_owners(distance,coverage))
|
||||
reference_seconds=time.monotonic()-started;started=time.monotonic()
|
||||
for args,expected in zip(cases,old):assert np.array_equal(views.strip_owners(*args),expected)
|
||||
report=dict(cases=len(cases),camera_pairs=sum(len(v) for v in old),reference_seconds=reference_seconds,batch_seconds=time.monotonic()-started,identical=True)
|
||||
Path('/out/camera-ownership.json').write_text(json.dumps(report,indent=2));print('OWNERSHIP',report,flush=True)
|
||||
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,28 @@
|
||||
import numpy as np
|
||||
from shapely.geometry import Polygon
|
||||
from interval_profiles import rectangle
|
||||
from component_axis import from_component,preferred
|
||||
from stroke_seeds import from_component as previous
|
||||
|
||||
|
||||
def run():
|
||||
o=np.array([300.,-20.]);u=np.array([1.,0.])
|
||||
for width in [.12,.8]:
|
||||
p=rectangle(o,u,-1.5,1.5,width);before,after=previous(p),from_component(p)
|
||||
assert before.keys()==after.keys()
|
||||
for key in ['origin','axis','length','width']:np.testing.assert_array_equal(before[key],after[key])
|
||||
p=Polygon(np.array([[0.,0.],[.03,0.],[.03,.1],[.7,.1],[.7,.23],[0.,.23]])+o)
|
||||
measured=from_component(p)
|
||||
assert measured is not None and abs(measured['axis'][1])<.08
|
||||
assert from_component(Polygon([[0,0],[1,0],[1,1],[0,1]]))is None
|
||||
assert from_component(Polygon())is None
|
||||
chosen=preferred(p)
|
||||
for key in ['origin','axis','length','width']:np.testing.assert_array_equal(chosen[key],measured[key])
|
||||
for sample in [rectangle(o,u,-1.5,1.5,.12),Polygon([[0,0],[1,0],[1,1],[0,1]]),Polygon()]:
|
||||
a=from_component(sample);expected=a if a is not None else previous(sample);actual=preferred(sample)
|
||||
if expected is None:assert actual is None
|
||||
else:
|
||||
for key in ['origin','axis','length','width']:np.testing.assert_array_equal(actual[key],expected[key])
|
||||
from primary_components import qualify
|
||||
qualify()
|
||||
print('COMPONENT_AXIS_CONTRACT_OK',flush=True)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Bounded real-image batch API, numerical and throughput qualification."""
|
||||
import sys,time,json,hashlib,gc
|
||||
from pathlib import Path
|
||||
import numpy as np,torch,cv2
|
||||
from PIL import Image
|
||||
sys.path.insert(0,'/release/simulation/ai-polygon/sam3-research')
|
||||
from qualify import load_exact,sha
|
||||
import sam3.model_builder as builder
|
||||
from sam3.model.sam3_image_processor import Sam3Processor
|
||||
from batched_concepts import ConceptDecoder
|
||||
from cached_text_processor import CachedTextProcessor
|
||||
|
||||
def run():
|
||||
torch.set_num_threads(3);cv2.setNumThreads(3)
|
||||
spec=json.loads(Path('/release/simulation/ai-polygon/sam3-research/large-model.json').read_text());assets=Path('/assets')
|
||||
for n,h in spec['files'].items():assert sha(assets/n)==h
|
||||
builder._load_checkpoint=load_exact
|
||||
model=builder.build_sam3_image_model(bpe_path='/source/assets/bpe_simple_vocab_16e6.txt.gz',checkpoint_path=str(assets/next(iter(spec['files']))),load_from_HF=False,enable_segmentation=True,enable_inst_interactivity=False,compile=False,text_encoder_type=spec['text_encoder'],text_encoder_context_length=16,device='cuda')
|
||||
stock=Sam3Processor(model,device='cuda',confidence_threshold=.30)
|
||||
cached=CachedTextProcessor(model,device='cuda',confidence_threshold=.30)
|
||||
decoder=ConceptDecoder(stock,batch_size=3)
|
||||
manifest=json.loads(Path('/symbolplan/symbol-patches.json').read_text());patches=manifest['patches']
|
||||
selected=[patches[i]for i in np.linspace(0,len(patches)-1,min(10,len(patches)),dtype=int)]
|
||||
prompts=['road','sidewalk','vehicle','road marking','crosswalk','arrow'];rows=[]
|
||||
def serial(processor,image):
|
||||
result={}
|
||||
with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):
|
||||
state=processor.set_image(image)
|
||||
for prompt in prompts:
|
||||
state=processor.set_text_prompt(prompt,state)
|
||||
result[prompt]=dict(masks=state['masks'].reshape(-1,image.height,image.width).cpu().numpy().copy(),scores=state['scores'].float().cpu().numpy().reshape(-1).copy())
|
||||
return result
|
||||
def differences(a,b):
|
||||
rows=[]
|
||||
for prompt in prompts:
|
||||
x,y=a[prompt],b[prompt]
|
||||
same_count=len(x['scores'])==len(y['scores']);delta=float(np.max(abs(x['scores']-y['scores'])))if same_count and len(x['scores'])else 0. if same_count else None
|
||||
total=x['masks'].size if same_count else 0
|
||||
different=int(np.count_nonzero(x['masks']!=y['masks']))if same_count else None
|
||||
rows.append(dict(prompt=prompt,control_instances=len(x['scores']),candidate_instances=len(y['scores']),max_score_delta=delta,mask_changed_pixels=different,mask_compared_pixels=total))
|
||||
return rows
|
||||
for i,patch in enumerate(selected):
|
||||
p=Path('/symbolplan/symbol-patches')/(patch['id']+'.png');assert sha(p)==patch['sha256']
|
||||
with Image.open(p)as image:
|
||||
image=image.convert('RGB');image.thumbnail((1024,1024),Image.Resampling.LANCZOS)
|
||||
torch.cuda.synchronize();begin=time.monotonic();a=serial(stock,image);torch.cuda.synchronize();serial_s=time.monotonic()-begin
|
||||
begin=time.monotonic();b=serial(cached,image);torch.cuda.synchronize();cached_s=time.monotonic()-begin
|
||||
torch.cuda.reset_peak_memory_stats();begin=time.monotonic();c=decoder(image,prompts);torch.cuda.synchronize();batch_s=time.monotonic()-begin
|
||||
rows.append(dict(id=patch['id'],source_sha256=sha(p),serial_seconds=serial_s,cached_seconds=cached_s,batch_seconds=batch_s,peak_cuda_bytes=torch.cuda.max_memory_allocated(),cached=differences(a,b),batch=differences(a,c)))
|
||||
print('CONCEPT_CHECK',i+1,round(serial_s,3),round(cached_s,3),round(batch_s,3),flush=True)
|
||||
gc.collect()
|
||||
result=dict(model=spec,rows=rows,confidence_threshold=.30,mask_threshold=.5,presence_score_used=True,interpolation='bilinear-align_corners_false',cached_text_encodes=cached.text_encodes,cached_text_requests=cached.text_requests,batch_decoder_calls=decoder.decoder_calls,batch_size=3,performance_rows_exclude_first=1)
|
||||
Path('/out/concept-qualification.json').write_text(json.dumps(result,indent=2))
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Convergence, negative evidence and input-preservation checks for one fit."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from crossing_fit import rectangle_info,joint_rectangles
|
||||
|
||||
|
||||
def observations(width_outlier=False):
|
||||
rng=np.random.default_rng(271)
|
||||
origin=np.array([1000.,-500.]);theta=1.38
|
||||
axis=np.array([np.cos(theta),np.sin(theta)]);normal=np.array([-axis[1],axis[0]])
|
||||
result=[]
|
||||
for i,center in enumerate([-3.1,-2.,-.9,.1,2.1,3.2]):
|
||||
width=2.3 if width_outlier and i==2 else .52+(.008 if i%2 else 0.)
|
||||
lo=-2.+.02*center;hi=lo+4.+.005*center
|
||||
corners=np.array([[lo,center-width/2],[hi,center-width/2],[hi,center+width/2],[lo,center+width/2]])
|
||||
p=origin+corners[:,0,None]*axis+corners[:,1,None]*normal
|
||||
p+=rng.normal(0,.003,p.shape)
|
||||
p=np.r_[p,p[:1]]
|
||||
box,c,u,v=rectangle_info(p)
|
||||
result.append(dict(id=str(i),points=p,box=box,center=c,u=u,v=v))
|
||||
return result
|
||||
|
||||
|
||||
def run():
|
||||
measured=observations()
|
||||
before=[r['points'].copy()for r in measured]
|
||||
result,report=joint_rectangles(measured)
|
||||
assert report['optimizer_success'] and report['optimizer_evaluations']<80
|
||||
assert report['boundary_residual_p95_m']<.02
|
||||
assert [r['id']for r in result]==[r['id']for r in measured]
|
||||
for r,p in zip(measured,before):np.testing.assert_array_equal(r['points'],p)
|
||||
_,negative=joint_rectangles(observations(width_outlier=True))
|
||||
assert negative['boundary_residual_p95_m']>.15,'Incompatible observed width passed the unchanged gate'
|
||||
evidence=dict(passed=True,well_conditioned=report,incompatible_family=negative,
|
||||
input_geometry_unchanged=True,no_inferred_stripes=True,boundary_gate_m=.15)
|
||||
Path('/out/crossing-fit-qualification.json').write_text(json.dumps(evidence,indent=2))
|
||||
print('CROSSING_FIT_QUALIFIED',json.dumps(evidence),flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Fresh family atomicity and spatial ownership, independent of map names."""
|
||||
import numpy as np
|
||||
from interval_profiles import rectangle
|
||||
from family_ownership import FamilyOwnership,admitted_domain,unowned_bodies
|
||||
|
||||
|
||||
def run():
|
||||
state=FamilyOwnership();features=[dict(id='a'),dict(id='b'),dict(id='c')]
|
||||
state.committed([],features,True)
|
||||
assert not state.allows(['a']) and not state.allows(['a','b'])
|
||||
assert state.allows(['a','b','c']) and state.allows(['unrelated'])
|
||||
state.committed(['a','b','c'],[dict(id='replacement')],False)
|
||||
assert state.allows(['replacement']) and not state.members and not state.owners
|
||||
o=np.zeros(2);u=np.array([1.,0.]);polygons=[rectangle(o,u,x,x+.4,.12)for x in range(4)]
|
||||
row=dict(origin=o,axis=u,domain=rectangle(o,u,-.1,3.5,.28))
|
||||
domain=admitted_domain(row,polygons[:2])
|
||||
assert abs(domain.bounds[2]-1.4)<1e-9
|
||||
assert unowned_bodies(polygons,[domain])==polygons[2:]
|
||||
false_gap=rectangle(o,u,.6,.9,.12)
|
||||
assert not unowned_bodies([false_gap],[domain])
|
||||
assert abs(admitted_domain(row,polygons).bounds[2]-3.4)<1e-9
|
||||
print('FAMILY_OWNERSHIP_CONTRACT_OK',flush=True)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Synthetic invariants for coverage and paired-object evidence."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from observation_coverage import complete_coverage,POLICY
|
||||
from interval_profiles import rectangle
|
||||
from paired_markings import proposal,evidence
|
||||
from marking_rules import isolated_addition
|
||||
from shapely.geometry import mapping
|
||||
|
||||
def run():
|
||||
points=np.array([[0.,0.],[25.,0.],[50.,0.],[75.,0.]])
|
||||
centers=np.array([[0.,0.],[40.,0.],[80.,0.]])
|
||||
frozen=(points.copy(),centers.copy())
|
||||
additions,report=complete_coverage(points,centers)
|
||||
allcenters=np.r_[centers,np.array([r['center']for r in additions])]
|
||||
assert np.all((abs(points[:,None]-allcenters).max(2)<=POLICY['usable_half_width_m']).sum(1)>=2)
|
||||
assert np.array_equal(points,frozen[0])and np.array_equal(centers,frozen[1])
|
||||
assert complete_coverage(points,centers)==(additions,report)
|
||||
none,_=complete_coverage(points,allcenters);assert none==[]
|
||||
try:complete_coverage([[float('nan'),0]],centers)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('Nonfinite points admitted')
|
||||
o=np.array([0.,0.]);u=np.array([1.,0.])
|
||||
a=rectangle(o,u,-2.5,2.5,.12,-.18);b=rectangle(o,u,-2.5,2.5,.12,.18)
|
||||
def sampler(*,single=False,fill_gap=False,missing=False):
|
||||
def read(xy):
|
||||
bright=((abs(xy[:,1]+.18)<=.06)|((abs(xy[:,1]-.18)<=.06)&(not single)))&(abs(xy[:,0])<3)
|
||||
if fill_gap:bright|=(abs(xy[:,1])<.12)&(abs(xy[:,0])<3)
|
||||
rgb=np.repeat(np.where(bright,210,55).astype('uint8')[:,None],3,axis=1)
|
||||
return rgb,np.full(len(xy),not missing)
|
||||
return read
|
||||
read=sampler();ok,_=evidence(a,b,[read,read]);assert ok,'Observed pair rejected'
|
||||
assert proposal(a,[read,read]) is not None,'Pair interpretation failed'
|
||||
assert proposal(a,[sampler(single=True)]*2)is None,'Invented companion'
|
||||
assert not evidence(a,b,[read,sampler(missing=True)])[0],'Missing second observation admitted'
|
||||
assert not evidence(a,b,[sampler(fill_gap=True)]*2)[0],'Filled separator admitted'
|
||||
existing=lambda p:dict(neighbor=dict(geometry=mapping(p),properties=dict(subtype='linear_marking')))
|
||||
assert isolated_addition(a,existing(b)),'Parallel track mistaken for end seam'
|
||||
seam=rectangle(o,u,2.6,5.,.12,-.18)
|
||||
assert not isolated_addition(a,existing(seam)),'Unresolved collinear seam admitted'
|
||||
result=dict(passed=True,coverage=dict(deterministic=True,inputs_unchanged=True,distinct_views=True),
|
||||
paired=dict(real_pair=True,invented_companion_rejected=True,unknown_view_rejected=True,bright_separator_rejected=True))
|
||||
Path('/out/initial-observation-qualification.json').write_text(json.dumps(result,indent=2))
|
||||
print('INITIAL_OBSERVATIONS_QUALIFIED',json.dumps(result),flush=True)
|
||||
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Compare reordered planning to a frozen qualified selection on real pixels."""
|
||||
from pathlib import Path
|
||||
import json,time
|
||||
import numpy as np
|
||||
from prepare_primary_symbols import schedule_uniform
|
||||
from ground_observations import GroundObservations
|
||||
|
||||
started=time.monotonic();obs=GroundObservations()
|
||||
planned,ledger=schedule_uniform(obs)
|
||||
reference=json.loads(Path('/reference-symbols/symbol-patches.json').read_text())
|
||||
expected={p['id']:p for p in reference['patches']}
|
||||
assert {p['id']for p in planned}==set(expected)
|
||||
for p in planned:
|
||||
old=expected[p['id']]
|
||||
assert p['source_tile']==old['source_tile']
|
||||
native=(np.asarray(p['uv'])+.5)*old['native_size']/1200-.5
|
||||
low=np.floor(native.min(0)).astype(int);high=np.ceil(native.max(0)).astype(int)
|
||||
assert np.array_equal(np.r_[low,high],old['box_native'])
|
||||
report=dict(passed=True,windows=len(planned),same_source_tile=True,same_native_crop=True,
|
||||
visibility_threshold_unchanged=True,seconds=time.monotonic()-started)
|
||||
Path('/out/primary-plan-qualification.json').write_text(json.dumps(report,indent=2))
|
||||
print(json.dumps(report),flush=True)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Measured graph must preserve straight evidence and reject unsupported paths."""
|
||||
import numpy as np
|
||||
from scipy.ndimage import gaussian_filter1d
|
||||
from measured_row_graph import discover
|
||||
from interval_profiles import rectangle
|
||||
|
||||
|
||||
def run():
|
||||
seed=dict(origin=np.zeros(2),axis=np.array([1.,0.]),length=4.8,width=.12)
|
||||
centers=np.array([-2.,-1.,.14,1.,2.]);intervals=[(float(c-.15),float(c+.15))for c in centers]
|
||||
ts=np.arange(-2.5,2.501,.025);ns=np.arange(-.7,.701,.025)
|
||||
def profile(missing=False,bright_gaps=False,edge_shift=0.,offsets=None):
|
||||
offsets=np.zeros(5)if offsets is None else offsets
|
||||
field=np.zeros((len(ts),len(ns)))
|
||||
for (a,b),offset in zip(intervals,offsets):field[(ts>=a+edge_shift)&(ts<=b+edge_shift)]=100*(abs(ns-offset)<=.06)
|
||||
if bright_gaps:field[(ts>=intervals[0][0])&(ts<=intervals[-1][1])]=100*(abs(ns)<=.06)
|
||||
signal=gaussian_filter1d(np.median(field[:,abs(ns)<=.026],axis=1),1)
|
||||
return dict(ts=ts,ns=ns,contrast=field,allowed=np.full(field.shape,not missing,bool),signal=signal,valid=np.full(len(ts),not missing,bool),cut=35.,level=100.,offset=0.,width=.12,intervals=[(a+edge_shift,b+edge_shift)for a,b in intervals],peak_intervals=[])
|
||||
largest=lambda rows:max([len(r['polygons'])for r in rows]+[0])
|
||||
data=[profile(),profile()];new=discover(seed,data)
|
||||
assert largest(new)==5
|
||||
actual=max(new,key=lambda r:len(r['polygons']))
|
||||
expected=[rectangle(seed['origin'],seed['axis'],a,b,.12)for a,b in intervals]
|
||||
assert all(a.equals_exact(b,1e-8)for a,b in zip(expected,actual['polygons'])),'Measured straight bodies changed'
|
||||
assert not discover(seed,[profile(),profile(missing=True)])
|
||||
assert not discover(seed,[profile(bright_gaps=True)]*2)
|
||||
assert not discover(seed,[profile(),profile(edge_shift=.25)])
|
||||
offsets=np.array([-.1,-.1,0.,.1,.1]);rows=discover(seed,[profile(offsets=offsets)]*2)
|
||||
assert largest(rows)==5,'No valid path through observed displaced bodies'
|
||||
actual=max(rows,key=lambda r:len(r['polygons']))
|
||||
np.testing.assert_allclose([p.centroid.y for p in actual['polygons']],offsets,atol=.025)
|
||||
assert not discover(seed,[profile(offsets=np.full(5,-.1)),profile(offsets=np.full(5,.1))]),'Incompatible view tracks were combined'
|
||||
print('OBSERVATION_GRAPH_CONTRACT_OK',flush=True)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Measured axis and paint-preserving ownership contracts."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import numpy as np
|
||||
from shapely.geometry import mapping
|
||||
from interval_profiles import rectangle
|
||||
from stroke_axis import measure
|
||||
from finite_strokes import replacement
|
||||
from marking_rules import check_strip
|
||||
|
||||
|
||||
def image(angle=0,missing=False,extra=False,half_length=.45,sigma=.055):
|
||||
axis=np.array([np.cos(angle),np.sin(angle)]);normal=np.array([-axis[1],axis[0]])
|
||||
def read(xy):
|
||||
t=xy@axis;n=xy@normal
|
||||
signal=100*np.exp(-.5*(n/sigma)**2)/(1+np.exp(np.clip((abs(t)-half_length)/.015,-50,50)))
|
||||
if extra:signal=np.maximum(signal,90*((abs(xy[:,0])<.15)&(xy[:,1]>.12)&(xy[:,1]<.25)))
|
||||
rgb=np.repeat(np.clip(70+signal[:,None],0,255),3,axis=1).astype('uint8')
|
||||
return rgb,np.full(len(xy),not missing,dtype=bool)
|
||||
return read
|
||||
|
||||
|
||||
def run():
|
||||
seed=dict(origin=np.zeros(2),axis=np.array([1.,0.]),length=.9,width=.12)
|
||||
angle=np.deg2rad(11)
|
||||
corrected,report=measure(seed,[image(angle),image(angle)])
|
||||
assert report['reason']=='measured' and abs(report['angle_change_degrees']-11)<1
|
||||
assert np.array_equal(seed['axis'],[1.,0.])
|
||||
rejected,reason=measure(seed,[image(angle),image(angle,missing=True)])
|
||||
assert rejected is seed and reason['reason']!='measured'
|
||||
p=rectangle(np.zeros(2),np.array([1.,0.]),-.45,.45,.12)
|
||||
candidate=dict(polygons=[p],origin=np.zeros(2),axis=np.array([1.,0.]))
|
||||
feature=lambda poly:dict(id='fragment',geometry=mapping(poly),properties=dict(**{'class':'road_marking'},subtype='linear_marking'))
|
||||
current={'fragment':feature(rectangle(np.zeros(2),np.array([1.,0.]),-.3,.3,.12))}
|
||||
okay,ev=check_strip(p,[image(),image()]);assert okay
|
||||
ids,positive=replacement(candidate,current,[image(),image()]);assert ids==['fragment']
|
||||
protruding=rectangle(np.zeros(2),np.array([1.,0.]),-.15,.15,.12,offset=.19)
|
||||
old=p.union(protruding);current={'fragment':feature(old)}
|
||||
ids,negative=replacement(candidate,current,[image(extra=True),image(extra=True)])
|
||||
assert ids is None and negative['reason']=='positive-or-unobserved-removed-paint'
|
||||
ids,unknown=replacement(candidate,current,[image(missing=True),image(missing=True)])
|
||||
assert ids is None
|
||||
from measured_rows import measured_rows
|
||||
lengths=[.35,.55,.75];centers=[0.,1.2,2.4]
|
||||
row=dict(kind='periodic-row',mode='intervals',domain=rectangle(np.zeros(2),np.array([1.,0.]),-.5,3.,.3),origin=np.zeros(2),axis=np.array([1.,0.]),width=.12,offset=0.,
|
||||
polygons=[rectangle(np.zeros(2),np.array([1.,0.]),c-.25,c+.25,.12)for c in centers],
|
||||
observations=[dict(edges=[[c-L/2,c+L/2],[c-L/2,c+L/2]])for c,L in zip(centers,lengths)])
|
||||
def measured_image(missing=False):
|
||||
def read(xy):
|
||||
bright=np.zeros(len(xy),bool)
|
||||
for c,L in zip(centers,lengths):bright|=(abs(xy[:,0]-c)<=L/2)&(abs(xy[:,1])<=.06)
|
||||
rgb=np.repeat(np.where(bright,200,50).astype('uint8')[:,None],3,axis=1)
|
||||
valid=np.ones(len(xy),bool)
|
||||
if missing:valid[abs(xy[:,0]-centers[1])<.15]=False
|
||||
return rgb,valid
|
||||
return read
|
||||
from beta_profiles import profiles
|
||||
row_seed=dict(origin=np.zeros(2),axis=np.array([1.,0.]),length=6.,width=.12)
|
||||
actual=measured_rows([row],profiles(row_seed,[measured_image()]*2))
|
||||
assert len(actual)==1 and len(actual[0]['polygons'])==3
|
||||
np.testing.assert_allclose([p.bounds[2]-p.bounds[0]for p in actual[0]['polygons']],lengths)
|
||||
rejected=measured_rows([row],profiles(row_seed,[measured_image(),measured_image(missing=True)]))
|
||||
assert not rejected,'A missing second view entered the measured family'
|
||||
from paint_conservation import PaintConservation
|
||||
geometry=lambda f:__import__('shapely').geometry.shape(f['geometry'])
|
||||
proof=dict(origin=np.zeros(2),axis=np.array([1.,0.]))
|
||||
readers=[image(half_length=.8),image(half_length=.8)]
|
||||
from marking_rules import validate_removed
|
||||
# Three permitted local shifts cannot accumulate beyond the original
|
||||
# positive paint footprint, even though each last-to-next check passes.
|
||||
wide=lambda x:rectangle(np.zeros(2),np.array([1.,0.]),-.8+x,.8+x,.3)
|
||||
conservation=PaintConservation();objects={'first':dict(id='first',geometry=mapping(wide(0)),properties={})}
|
||||
successor=dict(id='second',geometry=mapping(wide(.05)),properties={})
|
||||
conservation.committed(['first'],objects,geometry,[successor]);objects={'second':successor}
|
||||
third=dict(id='third',geometry=mapping(wide(.10)),properties={})
|
||||
conservation.committed(['second'],objects,geometry,[third]);objects={'third':third}
|
||||
assert validate_removed(wide(.10),wide(.15),proof,readers)[0]
|
||||
assert not conservation.validate(['third'],objects,geometry,wide(.15),proof,readers)[0]
|
||||
from stroke_seeds import from_component
|
||||
broad=rectangle(np.zeros(2),np.array([1.,0.]),-1.5,1.5,.8)
|
||||
proposal=from_component(broad);assert proposal is not None and proposal['width']>.35
|
||||
assert from_component(rectangle(np.zeros(2),np.array([1.,0.]),-.4,.4,.8))is None
|
||||
import stroke_observations as measurement
|
||||
import shapely
|
||||
class Views:
|
||||
def __init__(self,read):self.read=read
|
||||
def readers(self,origin,axis):return [self.read,self.read],[{},{}]
|
||||
measurement.protected=shapely.GeometryCollection()
|
||||
measurement.views=Views(image(half_length=1.4))
|
||||
small={**seed,'length':1.7}
|
||||
measured=measurement.observe(small)
|
||||
runs=[r for r in measured['candidates']if r['kind']=='observed-continuous']
|
||||
assert any(r['polygons'][0].length>5.4 for r in runs),'Observed body was clipped to its seed'
|
||||
assert any(check_strip(r['polygons'][0],[image(half_length=1.4)]*2)[0]for r in runs)
|
||||
measurement.views=Views(image(half_length=1.4,sigma=.3))
|
||||
assert not measurement.observe(proposal)['candidates'],'Broad paint was admitted as a thin line'
|
||||
measurement.views=Views(image(missing=True,half_length=1.4))
|
||||
assert not measurement.observe(small)['candidates']
|
||||
from stroke_inventory import deduplicate
|
||||
from line_reconstruction import observation
|
||||
short=rectangle(np.zeros(2),np.array([1.,0.]),-.3,.3,.12)
|
||||
long=rectangle(np.zeros(2),np.array([1.,0.]),-2.,2.,.12)
|
||||
inputs=[observation(np.asarray(p.exterior.coords),str(i))for i,p in enumerate([short,long,short])]
|
||||
kept=deduplicate(inputs)
|
||||
assert len(kept)==2 and any(r['L']<1 for r in kept)and any(r['L']>3 for r in kept)
|
||||
evidence=dict(passed=True,axis=report,retained_fragment=positive,positive_removed=negative,missing_view=unknown,whole_body_unclipped=True,broad_proposal_not_admitted=True)
|
||||
Path('/out/stroke-contract.json').write_text(json.dumps(evidence,indent=2))
|
||||
print('STROKE_CONTRACT_OK',json.dumps(evidence),flush=True)
|
||||
|
||||
if __name__=='__main__':run()
|
||||
|
||||
from qualify_family_ownership import run as qualify_family_ownership
|
||||
qualify_family_ownership()
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Use the qualified shared search/admission contract on primary observations."""
|
||||
from pathlib import Path
|
||||
import hashlib,json
|
||||
from reconstruct_topdown import run
|
||||
|
||||
if __name__=='__main__':
|
||||
root=Path(__file__).parent
|
||||
for name,digest in json.loads((root/'arrow-contract-lock.json').read_text())['files'].items():
|
||||
if hashlib.sha256((root/name).read_bytes()).hexdigest()!=digest:
|
||||
raise ValueError('Qualified arrow source changed: '+name)
|
||||
if not Path('/native_geometry/native-geometry.json').is_file():
|
||||
raise ValueError('Native geometry must be captured by the initial survey')
|
||||
run()
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Resolve finite image strokes before fitting complete repeated marking rows."""
|
||||
from pathlib import Path
|
||||
import os,json,time,hashlib,collections
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import shape,mapping
|
||||
from shapely.ops import transform
|
||||
from layer_common import O,S,sample,feature
|
||||
from search_views import SearchViews
|
||||
from discovery_rules import unpack,uncovered
|
||||
from beta_profiles import describe,discover,section_evidence,profiles,corridor_dark,supported
|
||||
from beta_profiles import POLICY as PROFILE_POLICY
|
||||
from marking_profiles import diagnose_profiles
|
||||
from line_reconstruction import rows
|
||||
from interval_profiles import rectangle,runs
|
||||
from marking_rules import VERSION,POLICY,plan_replacement,validate_removed,join_continuous,isolated_addition
|
||||
from gost_catalog import assess_dash
|
||||
from paired_markings import proposal as paired_proposal
|
||||
from finite_strokes import replacement as finite_replacement
|
||||
from observed_geometry import missing_parts
|
||||
from stroke_seeds import from_component
|
||||
from paint_conservation import PaintConservation
|
||||
from family_ownership import FamilyOwnership,admitted_domain,unowned_bodies
|
||||
|
||||
|
||||
def measured_width(p):
|
||||
# Metadata describes the admitted polygon, including short legitimate dashes.
|
||||
# Proposal-size predicates must never be reused as a metadata parser.
|
||||
coordinates=np.asarray(shapely.force_2d(p).minimum_rotated_rectangle.exterior.coords)
|
||||
return float(np.min(np.linalg.norm(np.diff(coordinates,axis=0),axis=1)))
|
||||
|
||||
|
||||
def main():
|
||||
cv2.setNumThreads(3);start=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']}
|
||||
poly=lambda f:shapely.force_2d(shape(f['geometry']))
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
|
||||
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
protected=shapely.union_all([poly(f).convex_hull for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
|
||||
views=SearchViews(tiles,labels,low,high,protected)
|
||||
proposal_path=Path('/searchplan/search-proposals.json');proposals=json.loads(proposal_path.read_text());records=[unpack(r)for r in proposals['lines']]
|
||||
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
|
||||
joint_mode=os.environ.get('STROKE_ASSEMBLY','joint')=='joint'
|
||||
existing_geometry=None;existing_calls=0;existing_builds=0
|
||||
def existing():
|
||||
nonlocal existing_geometry,existing_calls,existing_builds
|
||||
existing_calls+=1
|
||||
# Joint configuration collection keeps current immutable until select().
|
||||
# Reuse that exact ordered union, with no refit, rounding or reordering.
|
||||
# Greedy control can mutate current, so it retains the original evaluation.
|
||||
if not joint_mode or existing_geometry is None:
|
||||
existing_geometry=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking'])
|
||||
existing_builds+=1
|
||||
return existing_geometry
|
||||
conservation=PaintConservation();ownership=FamilyOwnership()
|
||||
transactions=[];accepted_domains=[];candidates=[];paired=[];stats=collections.Counter();seen=[];admission_trace=[]
|
||||
seeds=[from_component(r['polygon'])for r in records]
|
||||
seeds +=[from_component(poly(f))for f in old['features']if f['properties'].get('subtype')=='linear_marking']
|
||||
for row in rows(records):
|
||||
if len(row['records'])<3:continue
|
||||
o,u=row['origin'],row['axis'];ts=(row['points']-o)@u;L=float(np.ptp(ts))
|
||||
if 1<L<70:seeds.append(dict(origin=o+(ts.min()+ts.max())/2*u,axis=u,length=L,width=.12))
|
||||
# Every primary appearance component can propose a thin stroke. Proposal
|
||||
# selection cannot discard a candidate merely because a larger unverified
|
||||
# outline overlaps it. The existing evidence gates still decide admission.
|
||||
appearance=json.loads(Path('/primary/observations.json').read_text())['paint']
|
||||
# One canonical axis per raw component. The expanded two-estimator bank
|
||||
# remains archived for causal evaluation, not a second production search.
|
||||
from primary_components import collect as primary_components
|
||||
appearance_seeds,axis_plan=primary_components(appearance)
|
||||
seeds += appearance_seeds
|
||||
(O/'primary-axis-plan.json').write_text(json.dumps(axis_plan,indent=2))
|
||||
print('PRIMARY_AXES',axis_plan,flush=True)
|
||||
seeds=[s for s in seeds if s is not None]
|
||||
for s in seeds:s['original_seed']=True
|
||||
unique={}
|
||||
for seed in seeds:
|
||||
u=seed['axis'];u=u if u[0]>0 or (u[0]==0 and u[1]>=0) else -u
|
||||
key=tuple(np.round(np.r_[seed['origin'],u,seed['length'],seed['width']],6))
|
||||
unique.setdefault(key,seed)
|
||||
seeds=list(unique.values())
|
||||
from stroke_observations import ordered
|
||||
ordered_seeds=sorted(seeds,key=lambda r:(int(np.argmin(np.linalg.norm(views.centers-r['origin'],axis=1))),not r.get('original_seed',True),-r['length']))
|
||||
import gzip,pickle
|
||||
identity_paths=[baseline,proposal_path,Path('/primary/observations.json'),Path('/evidence_plan/fields.npz'),S/'tile-index.json',Path('/ortho/observation-coverage.json'),Path('/ortho/native-geometry/native-geometry.json')]
|
||||
observation_identity={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in identity_paths if p.is_file()}
|
||||
measurement_modules=['stroke_observations.py','row_discovery.py','stroke_seeds.py','component_axis.py','primary_components.py','measured_rows.py','measured_row_graph.py','body_profiles.py','beta_profiles.py','marking_profiles.py','interval_profiles.py','measurement_reads.py','observation_cache.py','row_evidence.py','search_views.py','fit_scene.py','layer_common.py','discovery_evidence.py','paired_markings.py','marking_rules.py']
|
||||
observation_identity['measurement_sources']={name:hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest() for name in measurement_modules}
|
||||
seed_plan=[dict(origin=r['origin'].tolist(),axis=r['axis'].tolist(),length=r['length'],width=r['width'],original=r.get('original_seed',True)) for r in ordered_seeds]
|
||||
observation_identity['seed_plan']=hashlib.sha256(json.dumps(seed_plan,sort_keys=True,allow_nan=False).encode()).hexdigest()
|
||||
bank_identity=hashlib.sha256(json.dumps(observation_identity,sort_keys=True).encode()).hexdigest()
|
||||
bank_path=os.environ.get('STROKE_BANK_INPUT')
|
||||
if bank_path:
|
||||
# Internal frozen observation artifact from this Gaussian run only.
|
||||
bank=pickle.loads(gzip.decompress(Path(bank_path).read_bytes()))
|
||||
assert bank['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest()
|
||||
assert bank['observation_identity']==bank_identity, 'Observation bank belongs to different inputs'
|
||||
paired,candidates,seen,stats=bank['paired'],bank['candidates'],bank['seen'],collections.Counter(bank['stats'])
|
||||
else:
|
||||
for si,observation in enumerate(ordered(ordered_seeds,int(os.environ.get('STROKE_WORKERS','4')))):
|
||||
stats.update(observation['stats']);domain=observation['domain']
|
||||
if domain is None:continue
|
||||
seen.append(domain)
|
||||
legacy_suppressed=any(domain.intersection(shapely.union_all(r['polygons'])).area>=domain.area*.98 for r in paired if r.get('original_bank',True))
|
||||
for pair in observation['paired']:
|
||||
pair['original_bank']=pair.get('original_bank',True) and not legacy_suppressed
|
||||
paired.append(pair)
|
||||
candidates.extend(observation['candidates'])
|
||||
if si%80==0:print('PROFILE',si+1,len(seeds),'CANDIDATES',len(candidates),flush=True)
|
||||
bank=dict(observation_identity=bank_identity,observation_inputs=observation_identity,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),paired=paired,candidates=candidates,seen=seen,stats=dict(stats))
|
||||
(O/'measured-bank.pkl.gz').write_bytes(gzip.compress(pickle.dumps(bank,protocol=5),compresslevel=1))
|
||||
if os.environ.get('STROKE_BANK_ONLY')=='1':return
|
||||
if os.environ.get('STROKE_BANK','expanded')=='original':
|
||||
candidates=[r for r in candidates if r.get('original_bank',True)]
|
||||
paired=[r for r in paired if r.get('original_bank',True)]
|
||||
configurations=[]
|
||||
|
||||
# Measurement workers have exited; reuse immutable pixels during ordered
|
||||
# admission without repeatedly decoding distant tiles after each candidate.
|
||||
from observation_cache import ObservationCache
|
||||
admission_pixels=ObservationCache(views.inputs,6*1024**3)
|
||||
views.inputs=admission_pixels
|
||||
from measurement_reads import FrameReads
|
||||
admission_frames=FrameReads(views.readers)
|
||||
views.readers=admission_frames
|
||||
|
||||
def commit(r,ids,polys,operation,evidence):
|
||||
if not polys:return False
|
||||
if not ownership.allows(ids):stats['partial-measured-family-veto']+=1;return False
|
||||
before=[current[i]for i in ids];a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all(polys)
|
||||
if b.intersection(protected).area>.005:return False
|
||||
if a.symmetric_difference(b).area<.015:return False
|
||||
if ids:
|
||||
readers,_=views.readers(r['origin'],r['axis'])
|
||||
retained,lineage=conservation.validate(ids,current,poly,b,r,readers)
|
||||
if not retained:stats['ancestral-positive-paint-veto']+=1;return False
|
||||
evidence={**evidence,'conservation':lineage}
|
||||
rest=existing() if not ids else shapely.union_all([poly(f)for i,f in current.items()if i not in ids and f['properties']['class']=='road_marking'])
|
||||
if b.intersection(rest).area>.005:return False
|
||||
fs=[]
|
||||
family_hash=hashlib.sha256(b.wkb).hexdigest()[:20]
|
||||
for p in polys:
|
||||
body_width=measured_width(p)
|
||||
props=dict(subtype='linear_marking',line_kind='dashed'if r['kind']=='periodic-row'else'observed-continuous',method=VERSION,source_ids=ids,source_tiles=r['source_tiles'],width_m=body_width,family_id=family_hash,standard_compliance='not_assessed',observed_paint=True)
|
||||
if r['kind']=='periodic-row':
|
||||
measured_length=float(np.ptp((shapely.get_coordinates(p)-r['origin'])@r['axis']))
|
||||
props.update(period_m=r['period'],dash_length_m=measured_length,family_dash_length_m=r['length'],standard_assessment=assess_dash(measured_length,r['period'],body_width))
|
||||
else:props['endpoint_authority']='two-view-dark-endpoints' if r['kind']=='observed-finite' else 'observed_window_not_physical_end'
|
||||
fs.append(feature(lift(p),'road_marking',**props))
|
||||
if len(set(f['id']for f in fs))!=len(fs)or any(f['id']in current and f['id']not in ids for f in fs):return False
|
||||
if joint_mode:
|
||||
configurations.append(dict(kind=operation,source_ids=list(ids),output_ids=[f['id'] for f in fs],before=before,after=fs,
|
||||
evidence=evidence,source_tiles=r['source_tiles'],source_views=r['source_views'],profile_mode=r['profile_mode'],family_id=family_hash,
|
||||
bounds_xy=b.union(a).bounds,domain=mapping(admitted_domain(r,polys)) if r['kind']=='periodic-row' else None,
|
||||
atomic_family=r['kind'] in {'periodic-row','observed-pair'}))
|
||||
return True
|
||||
conservation.committed(ids,current,poly,fs)
|
||||
ownership.committed(ids,fs,r['kind']in {'periodic-row','observed-pair'})
|
||||
for i in ids:del current[i]
|
||||
for f in fs:current[f['id']]=f
|
||||
transactions.append(dict(kind=operation,source_ids=ids,output_ids=[f['id']for f in fs],before=before,after=fs,bounds_xy=b.union(a).bounds,evidence=evidence,source_tiles=r['source_tiles'],source_views=r['source_views'],profile_mode=r['profile_mode'],family_id=family_hash))
|
||||
if r['kind']=='periodic-row':accepted_domains.append(admitted_domain(r,polys))
|
||||
print('EDIT',len(transactions),operation,len(ids),'->',len(fs),flush=True);return True
|
||||
|
||||
# Admit complete adjacent tracks as a joint object. A measured companion is
|
||||
# checked with its dark separator and outer edge, never mistaken for asphalt.
|
||||
for r in sorted(paired,key=lambda r:-sum(p.area for p in r['polygons'])):
|
||||
plan=plan_replacement(r,current)
|
||||
if plan is not None:
|
||||
ids,polys=plan;readers,used=views.readers(r['origin'],r['axis'])
|
||||
retained,removed=validate_removed(shapely.union_all([poly(current[i])for i in ids]),shapely.union_all(polys),r,readers)
|
||||
if retained and commit(r,ids,polys,'whole-observed-pair',dict(pair=r['evidence'],removed=removed)):continue
|
||||
commit(r,[],[p for p in r['polygons']if uncovered(p,existing())],'observed-pair-additions',dict(pair=r['evidence']))
|
||||
|
||||
# Prefer complete measured families. A family may replace old fragments only
|
||||
# when every removed paint sample is either retained or visibly dark in both views.
|
||||
for r in sorted(candidates,key=lambda r:(r['kind']!='periodic-row',-len(r['polygons']))):
|
||||
if r['kind']!='periodic-row':continue
|
||||
overlaps_measured_family=any(r['domain'].intersection(d).area>.005 for d in accepted_domains)
|
||||
ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],observations=r['observations'],measured_bodies=r['measured_body_evidence'],measured_gaps=r['measured_gap_evidence'])
|
||||
plan=None if overlaps_measured_family else plan_replacement(r,current)
|
||||
if plan is not None:
|
||||
ids,polys=plan;readers,used=views.readers(r['origin'],r['axis']);okay,removed=validate_removed(shapely.union_all([poly(current[i])for i in ids]),shapely.union_all(polys),r,readers)
|
||||
if okay and commit(r,ids,polys,'whole-periodic-family',{**ev,'removed':removed}):continue
|
||||
stats['family-replacement-veto']+=1
|
||||
# Keep positive additions even when a pre-existing erroneous outline cannot
|
||||
# safely be removed. Protected or overlapping paint is never stacked twice.
|
||||
polygons=[p for p in unowned_bodies(r['polygons'],accepted_domains)if uncovered(p,existing())]
|
||||
commit(r,[],polygons,'observed-periodic-additions',ev)
|
||||
# Finite measured objects replace fragments atomically after the same strip
|
||||
# checks and explicit conservation of all removed positive paint.
|
||||
from marking_rules import check_strip
|
||||
for r in sorted(candidates,key=lambda r:-sum(p.area for p in r['polygons'])):
|
||||
if r['kind']!='observed-finite':continue
|
||||
p=r['polygons'][0]
|
||||
readers,used=views.readers(r['origin'],r['axis']);okay,ev=check_strip(p,readers)
|
||||
trace=dict(geometry=mapping(p),strip_passed=okay,strip=ev,source_tiles=r['source_tiles'])
|
||||
admission_trace.append(trace)
|
||||
if not okay:stats['finite-strip-veto']+=1;trace['reason']='strip';continue
|
||||
evidence=dict(profile=r['paint_evidence'],strip=ev,endpoints=r['edge_evidence'])
|
||||
if p.intersection(existing()).area>.005:
|
||||
ids,removed=finite_replacement(r,current,readers);trace['replacement']=removed
|
||||
if ids is not None and commit(r,ids,[p],'whole-observed-finite-stroke',{**evidence,'removed':removed}):trace['reason']='replaced';continue
|
||||
trace['reason']='ownership';stats['finite-ownership-veto']+=1;continue
|
||||
if isolated_addition(p,current):
|
||||
trace['reason']='added'if commit(r,[],[p],'observed-finite-stroke',evidence)else'transaction'
|
||||
else:stats['finite-seam-veto']+=1;trace['reason']='seam'
|
||||
for r in sorted(candidates,key=lambda r:-sum(p.area for p in r['polygons'])):
|
||||
if r['kind']!='observed-continuous':continue
|
||||
whole=r['polygons'][0]
|
||||
if whole.intersection(existing()).area>.005:
|
||||
readers,used=views.readers(r['origin'],r['axis']);whole_ok,whole_ev=check_strip(whole,readers)
|
||||
if whole_ok:
|
||||
ids,removed=finite_replacement(r,current,readers)
|
||||
if ids is not None and commit(r,ids,[whole],'whole-observed-continuous-stroke',dict(profile=r['paint_evidence'],strip=whole_ev,removed=removed)):continue
|
||||
for p in missing_parts(whole,existing()):
|
||||
# Recheck the entire admitted strip, with dark flanks, in two per-point mosaics.
|
||||
from marking_rules import check_strip
|
||||
readers,used=views.readers(r['origin'],r['axis']);okay,ev=check_strip(p,readers)
|
||||
if okay:
|
||||
ids,joined=join_continuous(p,current)
|
||||
if ids:
|
||||
joined_ok,joined_ev=check_strip(joined,readers);a=shapely.union_all([poly(current[i])for i in ids]);retained,removed=validate_removed(a,joined,r,readers)
|
||||
if joined_ok and retained:commit(r,ids,[joined],'observed-continuous-extension',dict(profile=r['paint_evidence'],strip=joined_ev,removed=removed))
|
||||
else:stats['continuous-join-veto']+=1
|
||||
elif isolated_addition(p,current):commit(r,[],[p],'observed-continuous-addition',dict(profile=r['paint_evidence'],strip=ev))
|
||||
else:stats['unresolved-seam-veto']+=1
|
||||
else:stats['strip-veto']+=1
|
||||
joint_report=None
|
||||
if joint_mode:
|
||||
from joint_assembly import select
|
||||
from primary_evidence import collect as primary_evidence
|
||||
from connected_configurations import compose
|
||||
junctions,junction_report=compose(configurations,lift)
|
||||
configurations.extend(junctions)
|
||||
current,transactions,joint_report=select(old,configurations,primary_evidence(appearance,proposals['lines']))
|
||||
joint_report['connected_junctions']=junction_report
|
||||
(O/'configuration-bank.json').write_text(json.dumps(configurations,allow_nan=False))
|
||||
(O/'joint-selection.json').write_text(json.dumps(joint_report,indent=2,allow_nan=False))
|
||||
result={**old,'features':list(current.values()),'marking_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'marking-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False))
|
||||
report=dict(scene=os.environ['SCENE'],baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),proposal_sha256=hashlib.sha256(proposal_path.read_bytes()).hexdigest(),policy=POLICY,policy_version=VERSION,manual_rois=[],point_clouds=False,seconds=time.monotonic()-start,profiled_axes=len(seen),profile_stats=dict(stats),candidate_pairs=len(paired),candidate_families=sum(r['kind']=='periodic-row'for r in candidates),transactions=len(transactions),stages=dict(collections.Counter(r['kind']for r in transactions)),removed_objects=sum(len(r['before'])for r in transactions),output_objects=sum(len(r['after'])for r in transactions),net_objects=len(result['features'])-len(old['features']))
|
||||
report['assembly_contract']=dict(version='immutable-measured-configurations-v1',mode='joint' if joint_mode else 'greedy-control',bank=os.environ.get('STROKE_BANK','expanded'),source_observations_immutable=True,old_control_as_input=False)
|
||||
report['existing_geometry_reuse']=dict(calls=existing_calls,builds=existing_builds,maximum_retained_unions=1,joint_only=True)
|
||||
report['admission_pixel_cache']=admission_pixels.report()
|
||||
report['admission_frames']=admission_frames.report()
|
||||
(O/'finite-stroke-admission.json').write_text(json.dumps(admission_trace,allow_nan=False))
|
||||
(O/'marking-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Validate measured family geometry before selecting overlapping hypotheses.
|
||||
|
||||
The original candidate generation and all admission predicates are retained.
|
||||
Only the ordering of measurement versus suppression changes. No new image read
|
||||
or recovery traversal is introduced.
|
||||
"""
|
||||
import numpy as np
|
||||
from beta_profiles import POLICY,fit_series,section_evidence,supported,corridor_dark
|
||||
from interval_profiles import rectangle
|
||||
from measured_rows import measured_rows
|
||||
|
||||
def discover(seed,views,retain_alternatives=False):
|
||||
"""Measured dashes, regular spacing, observed gap and transition endpoints."""
|
||||
if views is None:return []
|
||||
o,u=seed['origin'],seed['axis'];offset=float(np.mean([v['offset']for v in views]));width=float(np.clip(np.median([v['width']for v in views]),.075,.27));candidates=[]
|
||||
fitted={mode:fit_series(views[0][mode],seed,width,offset) for mode in ['intervals','peak_intervals']}
|
||||
for mode in ['intervals','peak_intervals']:
|
||||
for fit in fitted[mode]:
|
||||
# Both mosaics must locate actual stroke edges, including a worn
|
||||
# continuous underlay. A model alone cannot supply a missing run.
|
||||
observations=[];evidence=[];okay=True
|
||||
for p in fit['polygons']:
|
||||
c=float((np.array(p.centroid.coords[0])-o)@u);L=fit['length'];matched=[]
|
||||
for v in views:
|
||||
opts=[ab for ab in v[mode]if abs((ab[0]+ab[1])/2-c)<=POLICY['max_phase_error_m']and abs((ab[1]-ab[0])-L)<=max(.2,.22*L)]
|
||||
if not opts:okay=False;break
|
||||
ab=min(opts,key=lambda ab:abs((ab[0]+ab[1])/2-c));ev=section_evidence(v,c-L*.35,c+L*.35)
|
||||
if not supported(ev):okay=False;break
|
||||
matched.append(ab);evidence.append(ev)
|
||||
if not okay:break
|
||||
if max(abs(matched[0][i]-matched[1][i])for i in [0,1])>POLICY['max_edge_disagreement_m']:okay=False;break
|
||||
observations.append(dict(center=c,edges=matched))
|
||||
if not okay:continue
|
||||
centers=[r['center']for r in observations];gap_evidence=[]
|
||||
for a,b in zip(centers,centers[1:]):
|
||||
lo=a+fit['length']/2+.04;hi=b-fit['length']/2-.04
|
||||
for v in views:
|
||||
ev=section_evidence(v,lo,hi,False)
|
||||
# A visible low floor is allowed only with an independently
|
||||
# identified high-contrast peak rhythm in both images.
|
||||
if mode=='peak_intervals':
|
||||
paint=min(section_evidence(v,a-fit['length']*.3,a+fit['length']*.3)['contrast'],section_evidence(v,b-fit['length']*.3,b+fit['length']*.3)['contrast'])
|
||||
ev['contrast_drop']=paint-ev['contrast'];ok=ev['valid']>=POLICY['min_valid']and ev['contrast_drop']>=18 and ev['contrast']<paint*.65
|
||||
else:ok=supported(ev,False)
|
||||
if not ok:okay=False;break
|
||||
gap_evidence.append(ev)
|
||||
if not okay:break
|
||||
if not okay:continue
|
||||
# Only the observed first-to-last stroke span may replace old paint.
|
||||
# Exterior transitions are handled separately with their own evidence.
|
||||
lo=centers[0]-fit['length']/2;hi=centers[-1]+fit['length']/2
|
||||
# Include only positively dark exterior slivers. This avoids tiny
|
||||
# leftover caps while never erasing a real neighboring solid start.
|
||||
edges=[];limits=[lo,hi]
|
||||
for side,end in enumerate([lo,hi]):
|
||||
sign=-1 if side==0 else 1
|
||||
for pad in np.arange(POLICY['max_family_edge_padding_m'],.049,-.025):
|
||||
ev=[corridor_dark(v,*sorted([end+sign*.04,end+sign*float(pad)]))for v in views]
|
||||
if all(supported(e,False)for e in ev):
|
||||
limits[side]=end+sign*float(pad);edges.append(dict(side=side,padding=float(pad),views=ev));break
|
||||
domain=rectangle(o,u,limits[0],limits[1],width+.16,offset)
|
||||
candidates.append(dict(kind='periodic-row',mode=mode,polygons=fit['polygons'],domain=domain,origin=o,axis=u,width=width,offset=offset,period=fit['period_m'],length=fit['length'],observations=observations,paint_evidence=evidence,gap_evidence=gap_evidence,edge_evidence=edges,lo=lo,hi=hi))
|
||||
candidates=measured_rows(candidates,views)
|
||||
accepted=[]
|
||||
for r in sorted(candidates,key=lambda x:-len(x['polygons'])):
|
||||
if any(r['domain'].intersection(q['domain']).area>.01 for q in accepted):continue
|
||||
accepted.append(r)
|
||||
chosen={id(r) for r in accepted}
|
||||
for r in candidates:r['original_bank']=id(r) in chosen
|
||||
if retain_alternatives:
|
||||
from measured_row_graph import discover as graph_candidates
|
||||
alternatives=graph_candidates(seed,views,fits=fitted)
|
||||
for r in alternatives:r['original_bank']=False
|
||||
return candidates+alternatives
|
||||
return accepted
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Read accepted extra Gaussian renders without copying or mutating them."""
|
||||
from pathlib import Path
|
||||
import json,numpy as np,cv2
|
||||
from functools import lru_cache
|
||||
from PIL import Image
|
||||
from discovery_evidence import DiscoveryViews
|
||||
from fit_scene import project,world
|
||||
|
||||
def warp_semantic(field,source_uv,dest_uv,size):
|
||||
H=cv2.getPerspectiveTransform(np.asarray(source_uv,'float32'),np.asarray(dest_uv,'float32'))
|
||||
return cv2.warpPerspective(field.astype('float32'),H,(size,size),flags=cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT,borderValue=0)
|
||||
|
||||
class SearchViews(DiscoveryViews):
|
||||
def __init__(self,tiles,*args):
|
||||
self.root=Path('/coverage_base/coverage')
|
||||
extra=json.loads((self.root/'manifest.json').read_text())['tiles'] if (self.root/'manifest.json').exists() else []
|
||||
planned=Path('/ortho/observation-coverage.json')
|
||||
initial=json.loads(planned.read_text()) if planned.exists() else dict(complete=True,tiles=[])
|
||||
if not initial['complete']:raise ValueError('Incomplete initial observation coverage')
|
||||
self.initial={t['id']for t in initial['tiles']}
|
||||
tiles=list(tiles)+initial['tiles']
|
||||
self.additional={t['id']for t in extra};self.original=list(tiles)
|
||||
super().__init__(tiles+extra,*args)
|
||||
|
||||
@lru_cache(maxsize=128)
|
||||
def geometry(self,name):
|
||||
if name in self.additional:
|
||||
with np.load(self.root/name/'top.geometry.npz')as z:return dict(z)
|
||||
return super().geometry(name)
|
||||
|
||||
@lru_cache(maxsize=12)
|
||||
def inputs(self,name):
|
||||
if name not in self.additional:return super().inputs(name)
|
||||
with np.load(self.root/name/'vehicle.npz')as z:vehicle=z['vehicle'].astype('float32')
|
||||
return np.asarray(Image.open(self.root/name/'ground.png').convert('RGB')),vehicle
|
||||
|
||||
def semantics(self,name,size):
|
||||
if name not in self.additional:
|
||||
with np.load(Path('/evidence_plan/evidence')/(name+'.npz'))as z:
|
||||
return cv2.resize(z['road marking'].astype('float32'),(size,size))
|
||||
tile=next(t for t in self.tiles if t['id']==name);center=np.mean(tile['bounds_xy'],axis=0)
|
||||
original=min(self.original,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center))['id']
|
||||
dst=np.array([[0,0],[size-1,0],[size-1,size-1],[0,size-1]],float)
|
||||
xy=world((dst+.5)*1200/size-.5,self.geometry(name))
|
||||
with np.load(Path('/evidence_plan/evidence')/(original+'.npz'))as z:field=z['road marking'].astype('float32')
|
||||
uv=(project(xy,self.geometry(original))+.5)*field.shape[0]/1200-.5
|
||||
return warp_semantic(field,uv,dst,size)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Frozen SAM3 concept segmentation on geometry-selected native patches."""
|
||||
from pathlib import Path
|
||||
import sys,json,time,hashlib,gc
|
||||
import numpy as np,cv2,torch
|
||||
from PIL import Image
|
||||
sys.path.insert(0,'/release/simulation/ai-polygon/sam3-research')
|
||||
from qualify import load_exact,sha
|
||||
import sam3.model_builder as builder
|
||||
from sam3.model.sam3_image_processor import Sam3Processor
|
||||
from batched_concepts import ConceptDecoder
|
||||
O=Path('/out');start=time.monotonic();torch.set_num_threads(3);cv2.setNumThreads(3)
|
||||
d=json.loads(Path('/release/simulation/ai-polygon/sam3-research/large-model.json').read_text());assets=Path('/assets')
|
||||
for n,h in d['files'].items():assert sha(assets/n)==h
|
||||
builder._load_checkpoint=load_exact
|
||||
model=builder.build_sam3_image_model(bpe_path='/source/assets/bpe_simple_vocab_16e6.txt.gz',checkpoint_path=str(assets/next(iter(d['files']))),load_from_HF=False,enable_segmentation=True,enable_inst_interactivity=False,compile=False,text_encoder_type=d['text_encoder'],text_encoder_context_length=16,device='cuda')
|
||||
processor=Sam3Processor(model,device='cuda',confidence_threshold=.30);decoder=ConceptDecoder(processor,batch_size=3)
|
||||
prompts=['bicycle','bike symbol','arrow','letter A','bicycle road marking'];class_ids=[0,0,1,2,0];manifest=json.loads((O/'symbol-patches.json').read_text());folder=O/'symbol-masks';folder.mkdir(exist_ok=True);records=[]
|
||||
for p in manifest['patches']:
|
||||
image_path=O/'symbol-patches'/(p['id']+'.png');assert sha(image_path)==p['sha256'];im=Image.open(image_path).convert('RGB');masks=[];scores=[];classes=[]
|
||||
selected=list(zip(prompts,class_ids))
|
||||
if p.get('proposal',{}).get('source')=='paint-topology':selected=[(prompt,ci)for prompt,ci in selected if ci==0]
|
||||
predictions=decoder(im,[prompt for prompt,_ in selected])
|
||||
for prompt,ci in selected:
|
||||
for m,s in zip(predictions[prompt]['masks'],predictions[prompt]['scores']):
|
||||
if m.sum()*p['mpp']**2<.03:continue
|
||||
masks.append(m.astype('uint8'));scores.append(float(s));classes.append(ci)
|
||||
if masks:
|
||||
dst=folder/(p['id']+'.npz');np.savez_compressed(dst,masks=np.asarray(masks),scores=np.asarray(scores),classes=np.asarray(classes));digest=sha(dst)
|
||||
else:digest=None
|
||||
records.append(dict(id=p['id'],detections=len(masks),scores=scores,classes=classes,sha256=digest));print('SEMANTIC',len(records),'/',len(manifest['patches']),p['id'],list(zip(classes,[round(s,3)for s in scores])),flush=True)
|
||||
(O/'symbol-semantics.json').write_text(json.dumps(dict(model=d,prompts=prompts,class_ids=class_ids,class_labels=['bicycle','arrow','letter_A'],threshold=.30,patch_manifest_sha256=sha(O/'symbol-patches.json'),records=records,seconds=time.monotonic()-start,manual_rois=[]),indent=2));im.close()
|
||||
if len(records)%64==0:gc.collect()
|
||||
(O/'symbol-semantics.json').write_text(json.dumps(dict(model=d,prompts=prompts,class_ids=class_ids,class_labels=['bicycle','arrow','letter_A'],threshold=.30,patch_manifest_sha256=sha(O/'symbol-patches.json'),records=records,seconds=time.monotonic()-start,manual_rois=[],decoder_batches=decoder.decoder_calls,text_encodings=decoder.text_encodings,concept_batch_size=3,cuda_peak_allocated_bytes=torch.cuda.max_memory_allocated(),host_peak_rss_bytes=__import__('resource').getrusage(__import__('resource').RUSAGE_SELF).ru_maxrss*1024),indent=2))
|
||||
print('SEMANTICS COMPLETE',len(records),'SECONDS',time.monotonic()-start,flush=True)
|
||||
@@ -0,0 +1,150 @@
|
||||
"""One image embedding per exact survey window, shared across class requests.
|
||||
|
||||
A source view, crop, resize, opacity gate and threshold define a request. Only
|
||||
identical requests share inference. Consumers retain their own raster assembly.
|
||||
No final map, fitted object or scene identity participates in this schedule.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from ortho_windows import merge_instances, windows
|
||||
from PIL import Image
|
||||
|
||||
|
||||
@dataclass
|
||||
class Request:
|
||||
kind: str
|
||||
raster_box: tuple
|
||||
image_box: tuple
|
||||
prompts: list = field(default_factory=list)
|
||||
consumers: list = field(default_factory=list)
|
||||
|
||||
|
||||
def schedule(method, alphas, sizes):
|
||||
"""Union exact legacy schedules without equating different scale policies."""
|
||||
jobs = [
|
||||
("coarse", "context", 60, 60, method["prompts"]),
|
||||
(
|
||||
"medium",
|
||||
"context",
|
||||
method["context_width_m"],
|
||||
method["context_step_m"],
|
||||
method["prompts"],
|
||||
),
|
||||
("detail", "ground", method["detail_width_m"], method["detail_step_m"], method["prompts"]),
|
||||
("building", "context", 30, 20, ["building"]),
|
||||
("markings", "ground", 15, 10, ["road marking", "crosswalk"]),
|
||||
]
|
||||
requests = {}
|
||||
counts = {}
|
||||
for consumer, kind, width, step, prompts in jobs:
|
||||
counts[consumer] = dict(accepted=0, skipped=0)
|
||||
alpha = alphas[kind]
|
||||
if alpha.shape != (1200, 1200):
|
||||
raise ValueError("Expected calibrated 1200-pixel opacity")
|
||||
for x, y, w, h in windows(60, width, step):
|
||||
box = tuple(np.rint(np.array([x, y, x + w, y + h]) * 20).astype(int))
|
||||
x0, y0, x1, y1 = box
|
||||
if (alpha[y0:y1, x0:x1] > 0.7).mean() < 0.04:
|
||||
counts[consumer]["skipped"] += 1
|
||||
continue
|
||||
counts[consumer]["accepted"] += 1
|
||||
image_box = tuple(
|
||||
np.rint(np.array([x, y, x + w, y + h]) * sizes[kind] / 60).astype(int)
|
||||
)
|
||||
key = (kind, box, image_box)
|
||||
req = requests.setdefault(key, Request(kind, box, image_box))
|
||||
req.consumers.append((consumer, tuple(prompts)))
|
||||
for prompt in prompts:
|
||||
if prompt not in req.prompts:
|
||||
req.prompts.append(prompt)
|
||||
return list(requests.values()), counts
|
||||
|
||||
|
||||
def predict_planes(processor, image, prompts):
|
||||
"""Same concepts and masks, decoded in bounded batches on one embedding."""
|
||||
from batched_concepts import ConceptDecoder
|
||||
if not hasattr(processor, '_concept_decoder'):
|
||||
processor._concept_decoder = ConceptDecoder(processor, batch_size=3)
|
||||
predictions = processor._concept_decoder(image, prompts)
|
||||
result = {}
|
||||
for prompt in prompts:
|
||||
plane = np.zeros((image.height, image.width), np.float32)
|
||||
for mask, score in zip(predictions[prompt]['masks'], predictions[prompt]['scores'], strict=True):
|
||||
np.maximum(plane, np.where(mask, score, 0), out=plane)
|
||||
result[prompt] = plane
|
||||
return result
|
||||
|
||||
|
||||
def infer_tile(method, images, alphas, predict):
|
||||
if method["prompts"] != ["road", "sidewalk", "vehicle"] or method["model_threshold"] != 0.3:
|
||||
raise ValueError("Joint survey requires the qualified common prompt/threshold contract")
|
||||
if any(im.width != im.height for im in images.values()):
|
||||
raise ValueError("Expected square orthographic observation")
|
||||
requests, counts = schedule(method, alphas, {k: im.width for k, im in images.items()})
|
||||
canvases = {}
|
||||
for req in requests:
|
||||
x0, y0, x1, y1 = req.raster_box
|
||||
with images[req.kind].crop(req.image_box) as crop:
|
||||
crop.thumbnail((1024, 1024), Image.Resampling.LANCZOS)
|
||||
planes = predict(crop, req.prompts)
|
||||
scaled = {
|
||||
p: cv2.resize(planes[p], (x1 - x0, y1 - y0), interpolation=cv2.INTER_AREA)
|
||||
for p in req.prompts
|
||||
}
|
||||
for consumer, prompts in req.consumers:
|
||||
canvas = canvases.setdefault(consumer, {})
|
||||
for prompt in prompts:
|
||||
if prompt not in canvas:
|
||||
canvas[prompt] = np.zeros((1200, 1200), np.float32)
|
||||
target = canvas[prompt]
|
||||
merge_instances(target, scaled[prompt], x0, y0)
|
||||
|
||||
# Empty/unknown input is an all-zero observation, not a fabricated class.
|
||||
def plane(consumer, prompt):
|
||||
value = canvases.get(consumer, {}).get(prompt)
|
||||
return np.zeros((1200, 1200), np.float32) if value is None else value
|
||||
|
||||
context = np.asarray([plane("coarse", p) for p in method["prompts"]])
|
||||
medium = np.asarray([plane("medium", p) for p in method["prompts"]])
|
||||
detail = np.asarray([plane("detail", p) for p in method["prompts"]])
|
||||
normal = np.maximum(context, medium)
|
||||
combined = np.maximum(normal, detail)
|
||||
combined[2] = normal[2]
|
||||
combined[:, ~(np.maximum(alphas["context"], alphas["ground"]) > 0.5)] = 0
|
||||
road, sidewalk, vehicle = combined
|
||||
normal_out = {
|
||||
"roadway": road,
|
||||
"sidewalk": sidewalk,
|
||||
"vehicle": vehicle,
|
||||
"road marking": np.zeros_like(road),
|
||||
"crosswalk": np.zeros_like(road),
|
||||
}
|
||||
ground_out = {
|
||||
**normal_out,
|
||||
"roadway": detail[0],
|
||||
"sidewalk": detail[1],
|
||||
"vehicle": np.zeros_like(road),
|
||||
}
|
||||
layers = {}
|
||||
for consumer, kind, prompts in [
|
||||
("building", "context", ["building"]),
|
||||
("markings", "ground", ["road marking", "crosswalk"]),
|
||||
]:
|
||||
for prompt in prompts:
|
||||
value = plane(consumer, prompt)
|
||||
value[alphas[kind] < 0.5] = 0
|
||||
layers[prompt] = value.astype("float16")
|
||||
return (
|
||||
normal_out,
|
||||
ground_out,
|
||||
layers,
|
||||
{
|
||||
"consumers": counts,
|
||||
"image_encodings": len(requests),
|
||||
"separate_image_encodings": sum(x["accepted"] for x in counts.values()),
|
||||
"prompt_decodes": sum(len(r.prompts) for r in requests),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Shared first-pass surface/paint/building evidence; no map mutation."""
|
||||
|
||||
import gc
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from semantic_survey import infer_tile, predict_planes
|
||||
|
||||
|
||||
def run():
|
||||
sys.path.insert(0, "/release/simulation/ai-polygon/sam3-research")
|
||||
import sam3.model_builder as builder
|
||||
from qualify import load_exact, sha
|
||||
from sam3.model.sam3_image_processor import Sam3Processor
|
||||
|
||||
survey, evidence, run_root = Path("/survey"), Path("/evidence"), Path("/run")
|
||||
inputs_root = Path(os.environ.get("SURVEY_EVIDENCE_INPUT", "/evidence"))
|
||||
layer_root = Path("/layers/evidence")
|
||||
layer_root.mkdir(exist_ok=True, parents=True)
|
||||
(evidence / "road-prompt").mkdir(exist_ok=True)
|
||||
config = json.loads((run_root / "config.json").read_text())
|
||||
method = config["method"]
|
||||
if method["prompts"] != ["road", "sidewalk", "vehicle"] or method["model_threshold"] != 0.3:
|
||||
raise ValueError("Unqualified common inference threshold/prompts")
|
||||
model_spec = json.loads(
|
||||
Path("/release/simulation/ai-polygon/sam3-research/large-model.json").read_text()
|
||||
)
|
||||
assets = Path("/assets")
|
||||
for name, expected in model_spec["files"].items():
|
||||
assert sha(assets / name) == expected, "Semantic model digest changed"
|
||||
builder._load_checkpoint = load_exact
|
||||
torch.set_num_threads(3)
|
||||
cv2.setNumThreads(3)
|
||||
model = builder.build_sam3_image_model(
|
||||
bpe_path="/source/assets/bpe_simple_vocab_16e6.txt.gz",
|
||||
checkpoint_path=str(assets / next(iter(model_spec["files"]))),
|
||||
load_from_HF=False,
|
||||
enable_segmentation=True,
|
||||
enable_inst_interactivity=False,
|
||||
compile=False,
|
||||
text_encoder_type=model_spec["text_encoder"],
|
||||
text_encoder_context_length=16,
|
||||
device="cuda",
|
||||
)
|
||||
processor = Sam3Processor(model, device="cuda", confidence_threshold=0.3)
|
||||
started = time.monotonic()
|
||||
records, layer_records, schedules = [], [], []
|
||||
index = json.loads((survey / "tile-index.json").read_text())
|
||||
tiles = [t for t in index["tiles"] if t["status"] == "surveyed"]
|
||||
(run_root / "semantic-survey.json").write_text(json.dumps({"complete": False}))
|
||||
for tile in tiles:
|
||||
name = tile["id"]
|
||||
begin = time.monotonic()
|
||||
with np.load(survey / name / "top.geometry.npz") as g:
|
||||
context_alpha = g["alpha"]
|
||||
with np.load(inputs_root / (name + ".ground-dc.geometry.npz")) as g:
|
||||
ground_alpha = g["alpha"]
|
||||
with (
|
||||
Image.open(inputs_root / (name + ".context.png")) as a,
|
||||
Image.open(inputs_root / (name + ".ground.png")) as b,
|
||||
):
|
||||
images = {"context": a.convert("RGB"), "ground": b.convert("RGB")}
|
||||
try:
|
||||
normal, ground, layers, schedule = infer_tile(
|
||||
method,
|
||||
images,
|
||||
{"context": context_alpha, "ground": ground_alpha},
|
||||
lambda image, prompts: predict_planes(processor, image, prompts),
|
||||
)
|
||||
np.savez_compressed(evidence / (name + ".normal.npz"), **normal)
|
||||
np.savez_compressed(evidence / (name + ".ground.npz"), **ground)
|
||||
np.savez_compressed(
|
||||
evidence / "road-prompt" / (name + ".normal.npz"), road=normal["roadway"]
|
||||
)
|
||||
np.savez_compressed(
|
||||
evidence / "road-prompt" / (name + ".ground.npz"), road=ground["roadway"]
|
||||
)
|
||||
np.savez_compressed(layer_root / (name + ".npz"), **layers)
|
||||
road_area = (normal["roadway"] > 0.35) & (normal["sidewalk"] <= normal["roadway"])
|
||||
side_area = (normal["sidewalk"] > 0.4) & (normal["sidewalk"] > normal["roadway"])
|
||||
preview = np.asarray(images["context"].resize((1200, 1200)), dtype=np.float32).copy()
|
||||
preview[road_area] = 0.55 * preview[road_area] + 0.45 * np.array([65, 130, 225])
|
||||
preview[side_area] = 0.55 * preview[side_area] + 0.45 * np.array([25, 220, 145])
|
||||
Image.fromarray(np.uint8(preview)).save(evidence / (name + ".semantic.jpg"), quality=94)
|
||||
finally:
|
||||
for image in images.values():
|
||||
image.close()
|
||||
inputs = {
|
||||
kind: sha(inputs_root / (name + "." + kind + ".png")) for kind in ["context", "ground"]
|
||||
}
|
||||
seconds = time.monotonic() - begin
|
||||
counts = schedule["consumers"]
|
||||
records.append(
|
||||
dict(
|
||||
tile=name,
|
||||
windows=[counts[k]["accepted"] for k in ["coarse", "medium", "detail"]],
|
||||
skipped=[counts[k]["skipped"] for k in ["coarse", "medium", "detail"]],
|
||||
road_pixels=int(road_area.sum()),
|
||||
side_pixels=int(side_area.sum()),
|
||||
seconds=seconds,
|
||||
source_hashes=list(inputs.values()),
|
||||
joint_timing=True,
|
||||
)
|
||||
)
|
||||
layer_records.append(
|
||||
dict(
|
||||
tile=name,
|
||||
windows=sum(counts[k]["accepted"] for k in ["building", "markings"]),
|
||||
seconds=seconds,
|
||||
joint_timing=True,
|
||||
inputs=inputs,
|
||||
sha256=sha(layer_root / (name + ".npz")),
|
||||
pixels={p: int((x > 0.3).sum()) for p, x in layers.items()},
|
||||
)
|
||||
)
|
||||
schedules.append(dict(tile=name, **schedule))
|
||||
(run_root / "segmentation-report.json").write_text(json.dumps(records, indent=2))
|
||||
(layer_root / "report.json").write_text(
|
||||
json.dumps(
|
||||
dict(
|
||||
model=model_spec,
|
||||
records=layer_records,
|
||||
manual_rois=[],
|
||||
shared_policy=True,
|
||||
seconds=time.monotonic() - started,
|
||||
joint_timing=True,
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
print(
|
||||
"SHARED_SEMANTICS",
|
||||
len(records),
|
||||
"/",
|
||||
len(tiles),
|
||||
name,
|
||||
schedule["separate_image_encodings"],
|
||||
"->",
|
||||
schedule["image_encodings"],
|
||||
round(seconds, 2),
|
||||
flush=True,
|
||||
)
|
||||
gc.collect()
|
||||
from coverage_semantics import carry
|
||||
carry(survey, evidence, layer_root, run_root)
|
||||
(run_root / "segmentation-summary.json").write_text(
|
||||
json.dumps(
|
||||
dict(
|
||||
scene=os.environ["ORTHO_SCENE"],
|
||||
method=method,
|
||||
model=model_spec,
|
||||
tiles=len(records),
|
||||
windows=sum(sum(r["windows"]) for r in records),
|
||||
seconds=time.monotonic() - started,
|
||||
manual_rois=[],
|
||||
joint_timing=True,
|
||||
score_interpretation="model scores, not calibrated probabilities",
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
(run_root / "semantic-survey.json").write_text(
|
||||
json.dumps(
|
||||
dict(
|
||||
schema="missioncore.shared-semantic-survey/v1",
|
||||
complete=True,
|
||||
records=schedules,
|
||||
source_index_sha256=sha(survey / "tile-index.json"),
|
||||
config_sha256=sha(run_root / "config.json"),
|
||||
model=model_spec,
|
||||
seconds=time.monotonic() - started,
|
||||
image_encodings=sum(x["image_encodings"] for x in schedules),
|
||||
separate_image_encodings=sum(x["separate_image_encodings"] for x in schedules),
|
||||
prompt_decodes=sum(x["prompt_decodes"] for x in schedules),
|
||||
decoder_batches=processor._concept_decoder.decoder_calls if hasattr(processor,"_concept_decoder")else 0,
|
||||
text_encodings=processor._concept_decoder.text_encodings if hasattr(processor,"_concept_decoder")else 0,
|
||||
concept_batch_size=3,
|
||||
map_input=False,
|
||||
new_renders=0,
|
||||
repeated_detection=False,
|
||||
),
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Reconcile observed surface rings with existing physical boundary geometry.
|
||||
|
||||
No detection, bridge search, contour completion or historical map input. Each
|
||||
replacement uses a bounded monotone interval of one admitted road boundary.
|
||||
Unknown raster cells and inferred road spans cannot justify a replacement.
|
||||
Unmatched ring edges remain coverage edges, never promoted to physical curbs.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import LineString, Point, Polygon
|
||||
from shapely.ops import substring, polygonize
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EdgePolicy:
|
||||
# Association window inherited from the former proximity-only link.
|
||||
max_displacement: float = .6
|
||||
sample_step: float = .1
|
||||
min_run_length: float = 1.
|
||||
ambiguity_margin: float = .1
|
||||
min_tangent_cosine: float = .8
|
||||
|
||||
|
||||
def _points(line, step):
|
||||
t = np.linspace(0, line.length, max(2, int(np.ceil(line.length/step))+1))
|
||||
return t, shapely.get_coordinates(shapely.line_interpolate_point(line, t))
|
||||
|
||||
|
||||
def _ring(coords, roads, classify, inferred, policy, audit=None, valid_ring=None):
|
||||
def known(xy):
|
||||
return np.isin(classify(xy), [1,2])
|
||||
# Keep every original corner. Uniform global resampling would cut corners.
|
||||
xy = np.asarray(coords)[:, :2]
|
||||
points = []
|
||||
for a, b in zip(xy[:-1], xy[1:]):
|
||||
n = max(1, int(np.ceil(np.linalg.norm(b-a)/policy.sample_step)))
|
||||
points.extend(a+(b-a)*np.arange(n)[:, None]/n)
|
||||
points = np.asarray(points+[points[0]])
|
||||
mid = (points[:-1]+points[1:])/2
|
||||
tangent = np.diff(points, axis=0)
|
||||
lengths = np.linalg.norm(tangent, axis=1)
|
||||
tangent /= np.maximum(lengths[:, None], 1e-12)
|
||||
n = len(mid)
|
||||
if not roads or not n:
|
||||
return xy, []
|
||||
mp = shapely.points(mid)
|
||||
distances = np.asarray([shapely.distance(g, mp) for g in roads])
|
||||
order = np.argsort(distances, axis=0, kind='stable')
|
||||
choice = order[0]
|
||||
best = distances[choice, np.arange(n)]
|
||||
allowed = best <= policy.max_displacement
|
||||
# Match a road/sidewalk interface, never a nearby facade, grass strip,
|
||||
# raster coverage cap or two edges belonging to the same surface.
|
||||
normal = np.c_[-tangent[:,1], tangent[:,0]]
|
||||
a = classify(mid + normal*policy.sample_step*3)
|
||||
b = classify(mid - normal*policy.sample_step*3)
|
||||
allowed &= ((a == 1) & (b == 2)) | ((a == 2) & (b == 1))
|
||||
if len(roads) > 1:
|
||||
allowed &= distances[order[1], np.arange(n)]-best >= policy.ambiguity_margin
|
||||
for i, road in enumerate(roads):
|
||||
ix = np.flatnonzero(allowed & (choice == i))
|
||||
if not len(ix):
|
||||
continue
|
||||
station = shapely.line_locate_point(road, mp[ix])
|
||||
near = shapely.get_coordinates(shapely.line_interpolate_point(road, station))
|
||||
a = shapely.get_coordinates(shapely.line_interpolate_point(road, np.maximum(station-.2, 0)))
|
||||
b = shapely.get_coordinates(shapely.line_interpolate_point(road, np.minimum(station+.2, road.length)))
|
||||
direction = b-a
|
||||
direction /= np.maximum(np.linalg.norm(direction, axis=1)[:, None], 1e-12)
|
||||
ok = abs(np.sum(direction*tangent[ix], axis=1)) >= policy.min_tangent_cosine
|
||||
# A nearest endpoint cannot anchor an interval beyond observed extent.
|
||||
ok &= (station > 1e-6) & (station < road.length-1e-6)
|
||||
# The entire displacement ribbon must be observed road or sidewalk.
|
||||
for f in np.linspace(0, 1, max(2, int(np.ceil(policy.max_displacement/policy.sample_step))+1)):
|
||||
ok &= known(mid[ix]*(1-f)+near*f)
|
||||
for start, end in inferred[i]:
|
||||
ok &= ~((station >= start-policy.sample_step) & (station <= end+policy.sample_step))
|
||||
allowed[ix] &= ok
|
||||
if audit is not None:audit.append(dict(event='associations',ring_length=float(lengths.sum()),eligible_m=float(lengths[allowed].sum())))
|
||||
choice[~allowed] = -1
|
||||
# Rotate so a cyclic run is not accidentally split at ring serialization.
|
||||
changes = np.flatnonzero(choice != np.roll(choice, 1))
|
||||
if len(changes):
|
||||
k = int(changes[0]);points = np.vstack([points[k:-1],points[:k],points[k]])
|
||||
choice = np.roll(choice, -k);lengths = np.roll(lengths, -k)
|
||||
cuts = np.r_[0, np.flatnonzero(choice[1:] != choice[:-1])+1, n]
|
||||
out = [points[0]];bindings = []
|
||||
for a, b in zip(cuts[:-1], cuts[1:]):
|
||||
i = int(choice[a]);original = points[a:b+1]
|
||||
if i < 0 or lengths[a:b].sum() < policy.min_run_length:
|
||||
out.extend(original[1:]);continue
|
||||
road = roads[i]
|
||||
stations = shapely.line_locate_point(road, shapely.points(original))
|
||||
delta = np.diff(stations)
|
||||
if not (np.all(delta >= -1e-8) or np.all(delta <= 1e-8)):
|
||||
out.extend(original[1:]);continue
|
||||
start, end = float(stations[0]), float(stations[-1])
|
||||
if abs(end-start) < policy.min_run_length:
|
||||
out.extend(original[1:]);continue
|
||||
shared = substring(road, start, end)
|
||||
# The whole interval is checked; a short unseen span cannot disappear
|
||||
# between sampled associations. No inferred span may become observed.
|
||||
lo, hi = sorted([start,end])
|
||||
if any(max(lo,s) < min(hi,e) for s,e in inferred[i]):
|
||||
out.extend(original[1:]);continue
|
||||
old = LineString(original)
|
||||
if old.hausdorff_distance(shared) > policy.max_displacement+1e-8:
|
||||
out.extend(original[1:]);continue
|
||||
_, samples = _points(shared, policy.sample_step)
|
||||
if not np.all(known(samples)):
|
||||
out.extend(original[1:]);continue
|
||||
# Validate each proposed interface transaction against the original
|
||||
# ring before committing any of them. One bad connector must not throw
|
||||
# away the other independently valid interfaces of a long sidewalk.
|
||||
# Nanometre-scale noding precision is a numerical identity tolerance,
|
||||
# separate from evidence/displacement gates; avoids rotation-dependent
|
||||
# microscopic faces at coincident endpoints in GEOS.
|
||||
trial = LineString(np.vstack([points[:a+1],np.asarray(shared.coords),points[b:]]))
|
||||
faces = list(polygonize(shapely.union_all([trial],grid_size=1e-8)))
|
||||
if len(faces) != 1 or faces[0].interiors or shared.difference(faces[0].boundary.buffer(1e-7)).length > 1e-6 or (valid_ring is not None and not valid_ring(faces[0].exterior)):
|
||||
if audit is not None:audit.append(dict(event='rejected-interface-topology',road_index=i,station_interval_m=[lo,hi]))
|
||||
out.extend(original[1:]);continue
|
||||
out.extend(np.asarray(shared.coords));out.append(original[-1])
|
||||
bindings.append(dict(road_index=i, station_interval_m=[lo,hi], length_m=shared.length))
|
||||
out = np.asarray(out)
|
||||
# Remove exact repeats only; retain original corners and exact road vertices.
|
||||
out = out[np.r_[True, np.any(np.diff(out,axis=0) != 0,axis=1)]]
|
||||
if not np.array_equal(out[0],out[-1]):out=np.vstack([out,out[0]])
|
||||
# Node transition connectors with retained coverage edges. At an existing
|
||||
# corner a connector can retrace the adjacent edge; it is a dangling line,
|
||||
# not an extra surface. Accept only one unambiguous bounded ring. Never
|
||||
# choose between competing faces or fill a hole to repair a bad proposal.
|
||||
path = LineString(out)
|
||||
if not path.is_simple:
|
||||
faces = list(polygonize(shapely.union_all([path],grid_size=1e-8)))
|
||||
if len(faces) != 1 or len(faces[0].interiors):
|
||||
if audit is not None:audit.append(dict(event='ambiguous-faces',count=len(faces),areas=[f.area for f in faces],proposed_m=sum(b['length_m'] for b in bindings)))
|
||||
return xy, []
|
||||
out = np.asarray(faces[0].exterior.coords)
|
||||
final = LineString(out)
|
||||
for link in bindings:
|
||||
interval = substring(roads[link['road_index']], *link['station_interval_m'])
|
||||
if interval.difference(final.buffer(1e-7)).length > 1e-6:
|
||||
if audit is not None:audit.append(dict(event='interval-trimmed',lost_m=interval.difference(final.buffer(1e-7)).length,proposed_m=sum(b['length_m'] for b in bindings)))
|
||||
return xy, []
|
||||
return out, bindings
|
||||
|
||||
|
||||
def reconcile(polygons, roads, classify, inferred=None, policy=EdgePolicy()):
|
||||
"""Return reconciled polygons and explicit shared-boundary bindings.
|
||||
|
||||
``classify(xy)`` samples original semantic labels (0 unknown, 1 road,
|
||||
2 sidewalk), not this function's output.
|
||||
Unchanged physical chains are authoritative only for already-admitted spans.
|
||||
A failed topology transaction leaves that polygon exactly as received.
|
||||
"""
|
||||
roads = [shapely.force_2d(g) for g in roads]
|
||||
polygons = [shapely.force_2d(p) for p in polygons]
|
||||
inferred = inferred if inferred is not None else [[] for _ in roads]
|
||||
result=[];records=[]
|
||||
for source in polygons:
|
||||
rings=[];bindings=[];audit=[]
|
||||
original_rings=[source.exterior,*source.interiors]
|
||||
for index, ring in enumerate(original_rings):
|
||||
def valid_ring(replacement):
|
||||
trial=list(original_rings);trial[index]=replacement
|
||||
return Polygon(trial[0],trial[1:]).is_valid
|
||||
p, links = _ring(ring.coords, roads, classify, inferred, policy, audit, valid_ring)
|
||||
rings.append(p);bindings.extend(links)
|
||||
candidate=Polygon(rings[0],rings[1:]);reason=None
|
||||
if not bindings:reason='no-unambiguous-observed-interface'
|
||||
elif not candidate.is_valid or candidate.is_empty:reason='invalid-topology';audit.append(dict(event='invalid-polygon',detail=shapely.is_valid_reason(candidate)))
|
||||
elif len(candidate.interiors)!=len(source.interiors):reason='hole-topology-changed'
|
||||
elif source.boundary.hausdorff_distance(candidate.boundary)>policy.max_displacement+1e-7:reason='displacement-limit'
|
||||
# Preserve the entire interior away from the association corridor.
|
||||
elif not source.buffer(-policy.max_displacement).difference(candidate).is_empty:reason='interior-loss'
|
||||
elif not candidate.difference(source.buffer(policy.max_displacement)).is_empty:reason='unsupported-expansion'
|
||||
result.append(source if reason else candidate)
|
||||
records.append(dict(accepted=reason is None,reason=reason,bindings=[] if reason else bindings,audit=audit))
|
||||
# Two independently plausible transactions must not overlap each other or
|
||||
# an untouched neighbour. Roll back participants; do not silently repair.
|
||||
conflicts=set()
|
||||
for i, a in enumerate(result):
|
||||
for j in range(i):
|
||||
if a.intersection(result[j]).area > polygons[i].intersection(polygons[j]).area+1e-7:
|
||||
conflicts.update([i,j])
|
||||
for i in conflicts:
|
||||
result[i]=polygons[i];records[i]=dict(accepted=False,reason='surface-overlap',bindings=[])
|
||||
# Rollback may reveal another overlap with the restored old boundary.
|
||||
while True:
|
||||
conflicts=set()
|
||||
for i,a in enumerate(result):
|
||||
for j in range(i):
|
||||
if a.intersection(result[j]).area > polygons[i].intersection(polygons[j]).area+1e-7:
|
||||
conflicts.update(k for k in [i,j] if records[k]['accepted'])
|
||||
if not conflicts:break
|
||||
for i in conflicts:
|
||||
result[i]=polygons[i];records[i]=dict(accepted=False,reason='surface-overlap',bindings=[])
|
||||
return result,records
|
||||
|
||||
|
||||
def reconcile_features(areas, boundaries, classify, policy=EdgePolicy()):
|
||||
"""Application adapter: XYZ from source edges; explicit shared intervals.
|
||||
|
||||
Raster labels remain immutable observations. The accepted plan geometry is
|
||||
a separate product and must not be fed back as evidence to paint checks.
|
||||
"""
|
||||
source_polygons=[shapely.geometry.shape(f['geometry']) for f in areas]
|
||||
source_roads=[shapely.geometry.shape(f['geometry']) for f in boundaries]
|
||||
inferred=[[span['station_interval_m'] for span in f['properties'].get('inferred_spans',[])] for f in boundaries]
|
||||
polygons,records=reconcile(source_polygons,source_roads,classify,inferred,policy)
|
||||
features=[];edges=[]
|
||||
for item,original,polygon,record in zip(areas,source_polygons,polygons,records):
|
||||
links=[]
|
||||
for link in record['bindings']:
|
||||
road=boundaries[link['road_index']]
|
||||
lo,hi=link['station_interval_m']
|
||||
edge=substring(source_roads[link['road_index']],lo,hi)
|
||||
ident='shared-'+hashlib.sha256(json.dumps([road['id'],lo,hi]).encode()).hexdigest()[:20]
|
||||
links.append(dict(edge_id=ident,boundary_id=road['id'],station_interval_m=[lo,hi]))
|
||||
edges.append(dict(id=ident,boundary_id=road['id'],station_interval_m=[lo,hi],
|
||||
geometry=shapely.geometry.mapping(edge),surface_classes=['carriageway','pedestrian_area'],
|
||||
status='source-derived-interface',route_permission='unassigned',review_status='unreviewed'))
|
||||
if record['accepted']:
|
||||
source_rings=[LineString(r.coords) for r in [original.exterior,*original.interiors]]
|
||||
shared=[substring(source_roads[b['road_index']],*b['station_interval_m']) for b in record['bindings']]
|
||||
source_array=np.asarray(source_rings,dtype=object)
|
||||
source_tree=shapely.STRtree(source_array)
|
||||
shared_array=np.asarray(shared,dtype=object)
|
||||
shared_tree=shapely.STRtree(shared_array)
|
||||
def xyz(ring):
|
||||
points=shapely.points(np.asarray(ring.coords)[:,:2])
|
||||
nearest=source_array[source_tree.nearest(points)]
|
||||
physical=shared_array[shared_tree.nearest(points)]
|
||||
use_physical=shapely.distance(physical,points)<1e-7
|
||||
nearest[use_physical]=physical[use_physical]
|
||||
projected=shapely.line_interpolate_point(nearest,shapely.line_locate_point(nearest,points))
|
||||
return shapely.get_coordinates(projected,include_z=original.has_z)
|
||||
polygon=Polygon(xyz(polygon.exterior),[xyz(r) for r in polygon.interiors])
|
||||
ident='plan-'+hashlib.sha256(('pedestrian_area'+polygon.wkt).encode()).hexdigest()[:20]
|
||||
geometry=shapely.geometry.mapping(polygon)
|
||||
else:
|
||||
ident=item['id'];geometry=item['geometry']
|
||||
features.append({**item,'id':ident,'geometry':geometry,'properties':{
|
||||
**item['properties'],'source_coverage_id':item['id'],
|
||||
'method':'shared-observed-surface-edges' if record['accepted'] else item['properties'].get('method'),
|
||||
'boundary_role':'shared-physical-intervals-and-unmatched-coverage',
|
||||
'physical_boundary_ids':sorted({b['boundary_id'] for b in links}),
|
||||
'shared_boundary_segments':links,'area_m2':polygon.area}})
|
||||
return features,dict(schema='missioncore.shared-surface-edges/v1',edges=edges,
|
||||
records=records,policy=vars(policy),original_evidence_unchanged=True,
|
||||
inferred_road_intervals_not_promoted=True,unmatched_edges_role='coverage-only')
|
||||
@@ -0,0 +1,107 @@
|
||||
from pathlib import Path
|
||||
import os,json,time,hashlib,collections
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import shape,mapping,LineString
|
||||
from shapely.ops import transform
|
||||
from layer_common import O,S,sample,feature,parts
|
||||
from search_views import SearchViews
|
||||
from discovery_rules import unpack,uncovered,glyph_context
|
||||
from discovery_evidence import glyph_views
|
||||
from catalog_evidence import mosaic_views
|
||||
from line_reconstruction import rows
|
||||
from beta_profiles import describe,profiles,section_evidence
|
||||
from interval_profiles import rectangle
|
||||
from corridor_profiles import missing_sections
|
||||
from catalog_templates import fit_bicycle
|
||||
from catalog_zigzag import fit_zigzag
|
||||
from catalog_rules import VERSION,POLICY,accept_bicycle,accept_zigzag
|
||||
from catalog_context import bicycle_context
|
||||
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']}
|
||||
proposal_path=Path('/primary/search-proposals.json');proposals=json.loads(proposal_path.read_text())
|
||||
fresh_path=Path('/primary/catalog-proposals.json');fresh=json.loads(fresh_path.read_text());assert fresh['source_fields_sha256']==hashlib.sha256(Path('/evidence_plan/fields.npz').read_bytes()).hexdigest()
|
||||
proposals['glyphs']=fresh['glyphs']
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
|
||||
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
def poly(f):return shapely.force_2d(shape(f['geometry']))
|
||||
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
|
||||
existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'])
|
||||
protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
|
||||
views=SearchViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[]
|
||||
def admit(p,subtype,kind,evidence,names,**extra):
|
||||
global existing
|
||||
if not uncovered(p,existing):return False
|
||||
f=feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_tile=names[0],source_tiles=names,standard_compliance='not_assessed',**extra)
|
||||
if f['id']in current:return False
|
||||
current[f['id']]=f;existing=shapely.union_all([existing,p]);transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']],before=[],after=[f],bounds_xy=p.bounds,evidence=evidence,source_tiles=names,**extra));print('ADMIT',len(transactions),subtype,kind,flush=True);return True
|
||||
|
||||
for i,r in enumerate(proposals['glyphs']):
|
||||
p=shape(r['geometry']);fits=fit_bicycle(p,all_hypotheses=True)
|
||||
if not fits:continue
|
||||
for fit in fits:
|
||||
diag={k:v for k,v in fit.items()if k!='polygon'};diag.update(kind='bicycle',proposal=i);diagnostics.append(diag)
|
||||
if fit['score']<POLICY['bicycle_fit_score']or fit['support']<POLICY['bicycle_fit_support']or fit['recall']<POLICY['bicycle_fit_recall']:continue
|
||||
p=fit['polygon'];context=bicycle_context(p,fit['parameters'],[unpack(r)for r in proposals['lines']]);diag['lane_context']=context
|
||||
if not context['passed']:continue
|
||||
ev,names=mosaic_views(p,views);diag.update(evidence=ev,source_tiles=names)
|
||||
mode=accept_bicycle(ev,fit['score']);diag['passed']=bool(mode);diag['evidence_mode']=mode
|
||||
if mode and admit(p,'bicycle','preset-bicycle',ev,names,evidence_mode=mode,template_parameters=fit['parameters'],template_fit_score=fit['score'],lane_context=context,artwork='1.23.3 Russian road marking / Major Alexey / CC BY-SA 4.0'):break
|
||||
print('BICYCLES DONE',len(diagnostics),flush=True)
|
||||
|
||||
# Existing full-image proposals supply connected paint components. A small
|
||||
# closing joins overlapping proposals, not unknown road segments.
|
||||
records=[unpack(r)for r in proposals['lines']]
|
||||
components=[shape(r['geometry'])for r in proposals['glyphs']]
|
||||
components += [r['polygon']for r in records if .6<r['L']<5.5 and .045<r['W']<.30]
|
||||
groups=parts(shapely.union_all(components).buffer(.055,join_style=2).buffer(-.055,join_style=2))
|
||||
groups += [p for component in components for p in parts(component)]
|
||||
for i,p in enumerate(groups):
|
||||
fit=fit_zigzag(p)
|
||||
if fit is None:continue
|
||||
q=fit['polygon'];ev,names=mosaic_views(q,views);leg_ev=[]
|
||||
for a,b in zip(fit['vertices'],fit['vertices'][1:]):
|
||||
ee,nn=mosaic_views(LineString([a,b]).buffer(fit['width_m']/2,cap_style=2),views);leg_ev.append(ee)
|
||||
mode=accept_zigzag(ev,leg_ev,fit)
|
||||
diagnostics.append(dict(kind='zigzag',group=i,passed=bool(mode),evidence_mode=mode,evidence=ev,leg_evidence=leg_ev,**{k:v for k,v in fit.items()if k!='polygon'}))
|
||||
if mode:admit(q,'zigzag','regularized-zigzag',dict(whole=ev,legs=leg_ev),names,evidence_mode=mode,vertices=fit['vertices'],leg_count=fit['legs'],width_m=fit['width_m'],fit_residual_m=fit['fit_residual_m'],proposal_recall=fit['proposal_recall'])
|
||||
print('ZIGZAGS DONE',len(transactions),flush=True)
|
||||
|
||||
# Visible portions of a long stripe do not need a dark physical end inside the
|
||||
# same camera. They remain explicitly observation-window-bounded segments.
|
||||
# Every admitted portion is positively supported in BOTH Gaussian mosaics.
|
||||
views.protected=shapely.union_all([protected]+[poly(f).convex_hull for f in current.values()if f['properties'].get('method')==VERSION])
|
||||
seeds=[]
|
||||
for r in records:
|
||||
if r['L']>=3 and r['W']<=POLICY['max_line_width_m']:
|
||||
s=describe(r['polygon'])
|
||||
if s is not None:seeds.append(s)
|
||||
for rr in rows(records):
|
||||
if len(rr['records'])<2:continue
|
||||
u=rr['axis'];o=rr['origin'];ranges=sorted([[(r['center']-o)@u-r['L']/2,(r['center']-o)@u+r['L']/2]for r in rr['records']]);chunks=[]
|
||||
for a,b in ranges:
|
||||
if chunks and a-chunks[-1][1]<=.30:chunks[-1][1]=max(chunks[-1][1],b)
|
||||
else:chunks.append([a,b])
|
||||
for a,b in chunks:
|
||||
if 3<b-a<55:seeds.append(dict(origin=o+(a+b)/2*u,axis=u,length=b-a,width=.12))
|
||||
seen=[];stats=collections.Counter()
|
||||
for i,seed in enumerate(sorted(seeds,key=lambda s:-s['length'])):
|
||||
domain=rectangle(seed['origin'],seed['axis'],-seed['length']/2,seed['length']/2,.14)
|
||||
if domain.intersection(existing.buffer(.10)).area/domain.area>.97:continue
|
||||
if any(domain.intersection(q).area/domain.area>.85 for q in seen):continue
|
||||
seen.append(domain);readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers,extension=.5)
|
||||
if pv is None:stats['no_profile']+=1;continue
|
||||
width=float(np.clip(np.median([v['width']for v in pv]),.075,.27));offset=float(np.mean([v['offset']for v in pv]))
|
||||
for a,b in pv[0]['intervals']:
|
||||
for c,d in pv[1]['intervals']:
|
||||
lo=max(a,c,-seed['length']/2);hi=min(b,d,seed['length']/2)
|
||||
if hi-lo<POLICY['min_line_length_m']:continue
|
||||
ev=[section_evidence(v,lo+.05,hi-.05)for v in pv]
|
||||
if not all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']and e['contrast']>=POLICY['min_line_contrast']for e in ev):stats['weak_paint']+=1;continue
|
||||
parent=rectangle(seed['origin'],seed['axis'],lo,hi,width,offset)
|
||||
for section in missing_sections(parent,existing):
|
||||
scores,names=glyph_views(section,views,None,None)
|
||||
if len(scores)!=2 or not all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']for e in scores):stats['section_views_rejected']+=1;continue
|
||||
admit(section,'linear_marking','observed-continuous-section',dict(profile=ev,section=scores,parent_geometry=mapping(parent)),names,line_kind='observed-continuous',endpoint_authority='observed_window_not_physical_end',width_m=width)
|
||||
if i%50==0:print('LINES',i,'/',len(seeds),'ADMITTED',len(transactions),flush=True)
|
||||
result={**old,'features':list(current.values()),'catalog_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'catalog-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'catalog-diagnostics.json').write_text(json.dumps(diagnostics,indent=2,allow_nan=False));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
|
||||
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),proposal_cache_sha256=hashlib.sha256(proposal_path.read_bytes()).hexdigest(),catalog_proposals_sha256=hashlib.sha256(fresh_path.read_bytes()).hexdigest(),proposal_source_fields_sha256=proposals['source_fields_sha256'],changed_segments=len(transactions),added_objects=len(transactions),added_subtypes=dict(collections.Counter(r['after'][0]['properties']['subtype']for r in transactions)),stages=dict(collections.Counter(r['kind']for r in transactions)),diagnostics=dict(stats),profiled_axes=len(seen),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
|
||||
(O/'catalog-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
|
||||
@@ -0,0 +1,54 @@
|
||||
from pathlib import Path
|
||||
import json,hashlib,time,os
|
||||
import cv2,numpy as np,shapely
|
||||
from PIL import Image
|
||||
from shapely.geometry import shape
|
||||
from shapely.ops import transform
|
||||
from layer_common import feature,sample
|
||||
from search_views import SearchViews
|
||||
from crossing_discovery import primitives,evidence,supported,periodic,sample_view,POLICY,VERSION
|
||||
from crossing_completion import observations,groups,model,recover
|
||||
O=Path('/out');raw=Path('/fullplan/full-map.json').read_bytes();base=json.loads(raw);start=time.monotonic();cv2.setNumThreads(2);cv2.setRNGSeed(2026)
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels,height,low,high=z['labels'],z['z'],z['bounds'][0],z['bounds'][1]
|
||||
tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None)
|
||||
seeds=[shape(f['geometry'])for f in json.loads(Path('/primary/crossing-seeds.json').read_text())]
|
||||
oldcross=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in base['features']if f['properties'].get('subtype')=='crosswalk'])
|
||||
(O/'crossing-seeds.json').write_text(json.dumps([feature(p,'road_marking',subtype='crosswalk')for p in seeds]))
|
||||
features=list(base['features']);rows=[];diagnostics=[]
|
||||
proposals=[(g,False)for g in groups(observations([feature(p,'road_marking',subtype='crosswalk')for p in seeds]))]
|
||||
proposals += [(g,True)for g in groups(observations(base['features']))if len(g)>=3]
|
||||
for group,anchored in proposals:
|
||||
# Two image primitives can propose a search axis; admission still requires
|
||||
# at least three separately observed, periodic bars in both original views.
|
||||
if len(group)<2:
|
||||
diagnostics.append(dict(seed_count=len(group),reason='insufficient-seeds',bounds_xy=list(shapely.union_all([r['p']for r in group]).bounds)))
|
||||
continue
|
||||
hull=shapely.union_all([r['p']for r in group]).convex_hull
|
||||
if not anchored and hull.distance(oldcross)<1.:continue
|
||||
m=model(group);center=m['origin'];tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center))['id']
|
||||
def sampler(xy):
|
||||
rgb,valid=sample_view(xy,tile,views);road=sample(labels,xy,low,high)==1
|
||||
return rgb,(~valid).astype(float),road.astype(float),np.ones(len(xy))
|
||||
fitted,rec=recover(m,sampler);candidates=[r for r in fitted if r['observed']];d=dict(seed_count=len(group),bounds_xy=list(hull.bounds),profile=rec,accepted=False,evidence=[]);diagnostics.append(d)
|
||||
if len(candidates)<3 or not periodic([r['center']for r in candidates]):d['reason']='family-period-or-count';continue
|
||||
out=[];out_evidence=[];anchors=[r['f']for r in group]if anchored else[]
|
||||
for r in candidates:
|
||||
if anchored and not r['new']:continue
|
||||
p=r['polygon'];ev=evidence(p,views);d['evidence'].append(ev)
|
||||
if anchored:
|
||||
from crossing_discovery import aligned_with_anchors
|
||||
if not aligned_with_anchors(p,anchors):continue
|
||||
if not supported(ev):continue
|
||||
if not all(POLICY['min_length_m']<=e['length_m']<=POLICY['max_length_m']and POLICY['min_width_m']<=e['width_m']<=POLICY['max_width_m']for e in ev):continue
|
||||
if any(p.intersection(shapely.force_2d(shape(f['geometry']))).area>.02 for f in features if f['properties']['class']=='road_marking'):continue
|
||||
lifted=transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
|
||||
out.append(feature(lifted,'road_marking',subtype='crosswalk',method=VERSION,family_size=len(candidates),source_tiles=[e['tile']for e in ev],observed=True))
|
||||
out_evidence.append(ev)
|
||||
if len(out)<(1 if anchored else 3):d['reason']='two-view-original-paint';continue
|
||||
# Do not publish a sparse subset of a family: every proposed observed bar must pass.
|
||||
if not anchored and len(out)!=len(candidates):d['reason']='incomplete-family-evidence';continue
|
||||
features.extend(out);d['accepted']=True
|
||||
display=shapely.union_all([hull]+[shapely.force_2d(shape(f['geometry']))for f in out])
|
||||
rows.append(dict(kind='anchored-crossing-completion'if anchored else'whole-crossing',context_ids=[f['id']for f in anchors],before=[],after=out,source_ids=[],output_ids=[f['id']for f in out],bounds_xy=list(display.buffer(1).bounds),evidence=out_evidence))
|
||||
result={**base,'features':features,'crossing_discovery':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'arrow-rows.json').write_text(json.dumps(rows,indent=2));(O/'crossing-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crossing-report.json').write_text(json.dumps(dict(scene=os.environ['SCENE'],policy=POLICY,seeds=len(seeds),families=len(rows),added_stripes=sum(len(r['after'])for r in rows),seconds=time.monotonic()-start,source_sha256=hashlib.sha256(raw).hexdigest()),indent=2))
|
||||
print('RESULT',len(seeds),len(rows),sum(len(r['after'])for r in rows),flush=True)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Measure a stroke axis from its connected image ridge, before profile fitting.
|
||||
|
||||
This generates a proposal only. Every output still needs the unchanged two-view
|
||||
body, flank, endpoint and ownership checks. No angle grid or reference map.
|
||||
"""
|
||||
import numpy as np
|
||||
import cv2
|
||||
from interval_profiles import strip
|
||||
|
||||
|
||||
def measure(seed,readers):
|
||||
if len(readers)!=2 or not .3<=seed['length']<=10.5:return seed,dict(reason='outside-local-stroke-scope')
|
||||
origin,axis=seed['origin'],seed['axis'];normal=np.array([-axis[1],axis[0]])
|
||||
step=.025
|
||||
ts=np.arange(-seed['length']/2-.25,seed['length']/2+.251,step)
|
||||
ns=np.arange(-.7,.701,step)
|
||||
center=(abs(ts[:,None])<=seed['length']/2)&(abs(ns[None,:])<=.13)
|
||||
fits=[]
|
||||
for read in readers:
|
||||
contrast,valid=strip(origin,axis,ts,ns,read)
|
||||
values=contrast[center&valid]
|
||||
if len(values)<5:return seed,dict(reason='unobserved-center')
|
||||
level=float(np.quantile(values,.8))
|
||||
if level<22:return seed,dict(reason='weak-center')
|
||||
mask=(contrast>max(15.,.35*level))&valid
|
||||
count,components,stats,_=cv2.connectedComponentsWithStats(mask.astype('uint8'),8)
|
||||
touched=np.bincount(components[center&mask],minlength=count);touched[0]=0
|
||||
index=int(touched.argmax())
|
||||
if touched[index]<5:return seed,dict(reason='no-connected-ridge')
|
||||
ii,jj=np.nonzero(components==index)
|
||||
# A component cut by the measurement window has no measured extent.
|
||||
if ii.min()==0 or ii.max()==len(ts)-1 or jj.min()==0 or jj.max()==len(ns)-1:return seed,dict(reason='component-clipped')
|
||||
points=np.column_stack([ts[ii],ns[jj]])
|
||||
weights=contrast[ii,jj].astype(float)
|
||||
center_uv=np.average(points,axis=0,weights=weights)
|
||||
covariance=(points-center_uv).T@((points-center_uv)*weights[:,None])/weights.sum()
|
||||
vals,vecs=np.linalg.eigh(covariance);direction=vecs[:,-1]
|
||||
if direction[0]<0:direction=-direction
|
||||
if vals[-1]<4*max(vals[0],1e-9):return seed,dict(reason='non-elongated-ridge')
|
||||
fits.append(dict(origin=origin+center_uv[0]*axis+center_uv[1]*normal,
|
||||
axis=direction[0]*axis+direction[1]*normal,length=float(np.ptp((points-center_uv)@direction))+step))
|
||||
angle=float(np.rad2deg(np.arccos(np.clip(abs(fits[0]['axis']@fits[1]['axis']),0,1))))
|
||||
if angle>3 or np.linalg.norm(fits[0]['origin']-fits[1]['origin'])>.05:return seed,dict(reason='view-disagreement',angle_degrees=angle)
|
||||
direction=fits[0]['axis']+fits[1]['axis'];direction/=np.linalg.norm(direction)
|
||||
result={**seed,'origin':np.mean([r['origin']for r in fits],axis=0),'axis':direction,'length':float(np.mean([r['length']for r in fits]))}
|
||||
return result,dict(reason='measured',angle_change_degrees=float(np.rad2deg(np.arccos(np.clip(abs(direction@axis),0,1)))),view_angle_degrees=angle)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Remove equivalent observations, never a distinct stroke hidden by a long one."""
|
||||
import shapely
|
||||
|
||||
|
||||
def deduplicate(records):
|
||||
ordered=sorted(records,key=lambda r:-(r['L']*r['W']))
|
||||
if not ordered:return []
|
||||
geometries=[r['polygon']for r in ordered];tree=shapely.STRtree(geometries)
|
||||
kept=set();result=[]
|
||||
for i,(record,p)in enumerate(zip(ordered,geometries)):
|
||||
duplicate=False
|
||||
for j in tree.query(p,predicate='intersects'):
|
||||
if j not in kept:continue
|
||||
q=geometries[j]
|
||||
if p.intersection(q).area/max(p.union(q).area,1e-9)>.85 and p.hausdorff_distance(q)<=.04:
|
||||
duplicate=True;break
|
||||
if duplicate:continue
|
||||
kept.add(i);result.append(record)
|
||||
return result
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Independent per-axis measurement, consumed once in original proposal order."""
|
||||
from pathlib import Path
|
||||
from collections import Counter,deque
|
||||
import json
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import shape
|
||||
from beta_profiles import profiles,section_evidence,corridor_dark,supported
|
||||
from beta_profiles import POLICY as PROFILE_POLICY
|
||||
from marking_profiles import diagnose_profiles
|
||||
from interval_profiles import rectangle
|
||||
from paired_markings import proposal as paired_proposal
|
||||
from search_views import SearchViews
|
||||
from marking_rules import POLICY as ADMISSION_POLICY
|
||||
from row_discovery import discover
|
||||
|
||||
|
||||
def initialize():
|
||||
global views,protected
|
||||
cv2.setNumThreads(3)
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
|
||||
tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
old=json.loads(Path('/fullplan/full-map.json').read_text())
|
||||
protected=shapely.union_all([shapely.force_2d(shape(f['geometry'])).convex_hull for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
|
||||
views=SearchViews(tiles,labels,low,high,protected)
|
||||
# Four processes share a 16 GiB container. Bound decoded observations per
|
||||
# process; long strips can touch more than the legacy twelve cached tiles.
|
||||
from observation_cache import ObservationCache
|
||||
views.inputs=ObservationCache(views.inputs,1536*1024**2)
|
||||
|
||||
|
||||
def observe(seed):
|
||||
stats=Counter();paired=[];candidates=[];pair_usage=[{},{}]
|
||||
readers,used=views.readers(seed['origin'],seed['axis'])
|
||||
domain=rectangle(seed['origin'],seed['axis'],-seed['length']/2,seed['length']/2,.14)
|
||||
if domain.intersection(protected).area>.005:return dict(stats=stats,domain=None)
|
||||
readers,used=views.readers(seed['origin'],seed['axis']);debug={}
|
||||
from measurement_reads import MeasurementRead
|
||||
readers=[MeasurementRead(reader) for reader in readers]
|
||||
if 3<=seed['length']<=65:
|
||||
pair=paired_proposal(domain,readers)
|
||||
if pair is not None:
|
||||
pair.update(original_bank=seed.get('original_seed',True),kind='observed-pair',profile_mode='two-view-transverse-pair',source_views=used,source_tiles=sorted(set(used[0])|set(used[1])))
|
||||
paired.append(pair)
|
||||
pair_usage=[dict(v)for v in used]
|
||||
pv=profiles(seed,readers)
|
||||
mode='original-window'
|
||||
if pv is None:pv=diagnose_profiles(seed,readers,debug=debug,adaptive=True);mode='stroke-sized-window'
|
||||
stats[mode+('-passed'if pv is not None else '-failed')]+=1
|
||||
if pv is None:
|
||||
stats['identical-measurements-reused']+=sum(reader.hits for reader in readers)
|
||||
stats['raw-measurement-queries']+=sum(reader.misses for reader in readers)
|
||||
return dict(stats=stats,domain=domain,paired=paired,candidates=candidates,pair_usage=pair_usage,source_views=used)
|
||||
found=discover(seed,pv,retain_alternatives=True)
|
||||
for r in found:
|
||||
r.update(original_bank=seed.get('original_seed',True) and r.get('original_bank',True),source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),profile_mode=mode)
|
||||
candidates.append(r)
|
||||
# Finite strokes use the same measured edges as periodic families, but
|
||||
# do not require unrelated neighbors to exist. Both views must establish
|
||||
# both endpoints; the complete strip and dark flanks are checked at commit.
|
||||
for a,b in pv[0]['intervals']:
|
||||
if b < -seed['length']/2 or a > seed['length']/2:continue
|
||||
for c,d in pv[1]['intervals']:
|
||||
if max(abs(a-c),abs(b-d))>PROFILE_POLICY['max_edge_disagreement_m']:continue
|
||||
lo,hi=(a+c)/2,(b+d)/2
|
||||
if not PROFILE_POLICY['min_dash_length_m']<=hi-lo<=PROFILE_POLICY['max_seed_length_m']:continue
|
||||
edge=[]
|
||||
for v in pv:
|
||||
edge.extend([corridor_dark(v,lo-.35,lo-.08),corridor_dark(v,hi+.08,hi+.35)])
|
||||
if not all(supported(e,False)for e in edge):continue
|
||||
ev=[section_evidence(v,lo+.04,hi-.04)for v in pv]
|
||||
if not all(e['valid']>=.98 and e['support']>=.93 and e['contrast']>=22 for e in ev):continue
|
||||
width=float(np.clip(np.median([v['width']for v in pv]),.075,.27));offset=float(np.mean([v['offset']for v in pv]))
|
||||
p=rectangle(seed['origin'],seed['axis'],lo,hi,width,offset)
|
||||
candidates.append(dict(original_bank=seed.get('original_seed',True),kind='observed-finite',polygons=[p],origin=seed['origin'],axis=seed['axis'],width=width,offset=offset,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),profile_mode=mode,paint_evidence=ev,edge_evidence=edge))
|
||||
# A long measured run remains a run, not a manufactured continuous road line.
|
||||
if seed['length']>=ADMISSION_POLICY['min_continuous_section_m']:
|
||||
for a,b in pv[0]['intervals']:
|
||||
for c,d in pv[1]['intervals']:
|
||||
lo=max(a,c);hi=min(b,d)
|
||||
if hi < -seed['length']/2 or lo > seed['length']/2:continue
|
||||
if hi-lo<ADMISSION_POLICY['min_continuous_section_m']:continue
|
||||
ev=[section_evidence(v,lo+.05,hi-.05)for v in pv]
|
||||
if not all(e['valid']>=.98 and e['support']>=.93 and e['contrast']>=22 for e in ev):continue
|
||||
width=float(np.clip(np.median([v['width']for v in pv]),.075,.27));offset=float(np.mean([v['offset']for v in pv]));p=rectangle(seed['origin'],seed['axis'],lo,hi,width,offset)
|
||||
candidates.append(dict(original_bank=seed.get('original_seed',True),kind='observed-continuous',polygons=[p],origin=seed['origin'],axis=seed['axis'],width=width,offset=offset,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),profile_mode=mode,paint_evidence=ev))
|
||||
stats['identical-measurements-reused']+=sum(reader.hits for reader in readers)
|
||||
stats['raw-measurement-queries']+=sum(reader.misses for reader in readers)
|
||||
return dict(stats=stats,domain=domain,paired=paired,candidates=candidates,pair_usage=pair_usage,source_views=used)
|
||||
|
||||
|
||||
def ordered(seeds,workers=4):
|
||||
if type(workers)is not int or not 1<=workers<=4:raise ValueError('Invalid stroke workers')
|
||||
if workers==1:
|
||||
initialize()
|
||||
for seed in seeds:yield observe(seed)
|
||||
return
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from multiprocessing import get_context
|
||||
source=iter(seeds);pending=deque()
|
||||
with ProcessPoolExecutor(max_workers=workers,mp_context=get_context('spawn'),initializer=initialize)as pool:
|
||||
for _ in range(2*workers):
|
||||
seed=next(source,None)
|
||||
if seed is None:break
|
||||
pending.append(pool.submit(observe,seed))
|
||||
while pending:
|
||||
result=pending.popleft().result()
|
||||
seed=next(source,None)
|
||||
if seed is not None:pending.append(pool.submit(observe,seed))
|
||||
yield result
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Proposal geometry may be blurred; only measured paint defines final width."""
|
||||
import numpy as np
|
||||
from beta_profiles import describe,POLICY
|
||||
from line_reconstruction import observation
|
||||
|
||||
|
||||
def from_component(polygon):
|
||||
ordinary=describe(polygon)
|
||||
if ordinary is not None:return ordinary
|
||||
if polygon.geom_type!='Polygon' or polygon.is_empty:return None
|
||||
observed=observation(np.asarray(polygon.exterior.coords),'primary-appearance')
|
||||
# The existing transverse measurement spans +/-0.7 m. A broad component
|
||||
# can supply an axis inside that domain without being admitted as a line.
|
||||
# Its width is retained as proposal metadata, never clamped into an output.
|
||||
if not POLICY['min_seed_length_m']<=observed['L']<=POLICY['max_seed_length_m']:return None
|
||||
if not POLICY['max_seed_width_m']<observed['W']<=2*POLICY['normal_half_width_m']:return None
|
||||
if observed['L']<2*observed['W']:return None
|
||||
axis=observed['axis'].astype(float);axis/=np.linalg.norm(axis)
|
||||
return dict(origin=observed['center'].astype(float),axis=axis,length=float(observed['L']),width=float(observed['W']),
|
||||
proposal_contract='connected-appearance-axis; final-width-unmeasured')
|
||||
@@ -0,0 +1,93 @@
|
||||
import numpy as np
|
||||
from conditional_replacements import plan
|
||||
from joint_assembly import select
|
||||
from shapely.geometry import box, mapping
|
||||
|
||||
|
||||
def feature(name, p, subtype="linear_marking"):
|
||||
return dict(
|
||||
id=name,
|
||||
geometry=mapping(p),
|
||||
properties=dict(class_="unused", **{"class": "road_marking"}, subtype=subtype),
|
||||
)
|
||||
|
||||
|
||||
def transaction(name, source, p):
|
||||
return dict(kind="verified", source_ids=[source], after=[feature(name, p)], atomic_family=False)
|
||||
|
||||
|
||||
def test_joint_neighbor_replacements_are_conditional():
|
||||
a = box(0, 0, 2, 0.12)
|
||||
# Old B overlaps new A. Its independently admitted replacement does not.
|
||||
b = box(1.4, 0.06, 4, 0.18)
|
||||
new_a = box(0, 0, 2, 0.12)
|
||||
new_b = box(2.4, 0.06, 4.4, 0.18)
|
||||
old = dict(features=[feature("a", a), feature("b", b)])
|
||||
options = [transaction("new-a", "a", new_a), transaction("new-b", "b", new_b)]
|
||||
evidence = [dict(geometry=mapping(new_b), properties=dict(source_tile="observed"))]
|
||||
chosen, _, _ = select(old, options, evidence)
|
||||
assert "new-b" in chosen
|
||||
# Force a simultaneous pair with crossing old neighbors and independent reward.
|
||||
from joint_choice import choose
|
||||
|
||||
nodes = [
|
||||
dict(id=k, sources=[s], incumbent=keep, cost=0.0)
|
||||
for k, s, keep in [
|
||||
("keep-a", "a", True),
|
||||
("keep-b", "b", True),
|
||||
("new-a", "a", False),
|
||||
("new-b", "b", False),
|
||||
]
|
||||
]
|
||||
conflicts = [("new-a", "keep-b"), ("new-b", "keep-a")]
|
||||
chosen, _ = choose(nodes, conflicts, [(["new-a"], 1.0), (["new-b"], 1.0)])
|
||||
assert set(chosen) == {"new-a", "new-b"}
|
||||
chosen, _ = choose(nodes[:-1], conflicts[:1], [(["new-a"], 100.0)])
|
||||
assert set(chosen) == {"keep-a", "keep-b"}
|
||||
|
||||
|
||||
def test_partial_neighbor_is_never_transferred_or_deleted():
|
||||
p = box(0, 0, 2, 0.12)
|
||||
old = {f["id"]: f for f in [feature("own", p), feature("neighbor", box(1.7, 0.08, 4, 0.2))]}
|
||||
r = dict(polygons=[p], axis=np.array([1.0, 0.0]), origin=np.array([1.0, 0.06]))
|
||||
ids, proof = plan(r, old, [])
|
||||
assert ids == ["own"] and proof["conditional_neighbors"] == ["neighbor"]
|
||||
assert set(old) == {"own", "neighbor"}
|
||||
protected = dict(old)
|
||||
protected["symbol"] = feature("symbol", box(1.8, 0, 2, 0.1), "right_arrow")
|
||||
assert plan(r, protected, [])[0] is None
|
||||
|
||||
|
||||
def test_unobserved_removed_paint_remains_rejected():
|
||||
p = box(0, 0, 2, 0.12)
|
||||
old = {"old": feature("old", box(0, -0.16, 2, 0.12))}
|
||||
r = dict(polygons=[p], axis=np.array([1.0, 0.0]), origin=np.array([1.0, 0.06]))
|
||||
|
||||
def unknown(points):
|
||||
return np.zeros((len(points), 3), "uint8"), np.zeros(len(points), bool)
|
||||
|
||||
ids, proof = plan(r, old, [unknown, unknown])
|
||||
assert ids is None and proof["reason"] == "positive-or-unobserved-removed-paint"
|
||||
|
||||
|
||||
def test_deferred_seam_is_still_a_hard_final_conflict():
|
||||
old = dict(features=[feature("old", box(0, 0, 2, 0.12))])
|
||||
p = box(2.1, 0, 4.1, 0.12)
|
||||
option = dict(
|
||||
kind="verified", source_ids=[], after=[feature("addition", p)], atomic_family=False
|
||||
)
|
||||
evidence = [dict(geometry=mapping(p), properties=dict(source_tile="observed"))]
|
||||
chosen, _, report = select(old, [option], evidence)
|
||||
assert set(chosen) == {"old"}
|
||||
assert report["conflicts"].get("unresolved-line-seam") == 1
|
||||
|
||||
|
||||
def qualify():
|
||||
for name, f in list(globals().items()):
|
||||
if name.startswith("test_"):
|
||||
f()
|
||||
print("PASS", name, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
qualify()
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Topology and conservation regressions, independent of any street fixture."""
|
||||
import numpy as np,shapely
|
||||
from shapely.geometry import box,mapping
|
||||
from connected_configurations import compose,junction,geometry
|
||||
from joint_assembly import select
|
||||
from layer_common import feature
|
||||
|
||||
def transaction(name,p,sources=()):
|
||||
f=feature(p,'road_marking',subtype='linear_marking',observed_paint=True)
|
||||
return dict(kind='observed-continuous-addition',source_ids=list(sources),before=[],after=[f],
|
||||
source_tiles=['camera-a','camera-b'],source_views=[{},{}],atomic_family=False,
|
||||
evidence=dict(strip=[dict(valid=1.,support=1.,contrast=60.,dark_flank=1.,flank_valid=1.)]*2))
|
||||
|
||||
def qualify():
|
||||
a,b=box(0,-.06,2.06,.06),box(1.94,0,2.06,2)
|
||||
original=[transaction('a',a),transaction('b',b)]
|
||||
new,proof=compose(original,lambda p:p)
|
||||
assert len(new)==1 and proof['additional_image_reads']==0
|
||||
p=geometry(new[0]['after'][0]);assert p.symmetric_difference(a.union(b)).area<1e-12
|
||||
assert new[0]['evidence']['added_area_m2']==0
|
||||
appearance=[dict(geometry=mapping(p),properties=dict(source_tile='camera-a'))]
|
||||
old,_,_=select(dict(features=[]),original,appearance)
|
||||
selected,_,_=select(dict(features=[]),original+new,appearance)
|
||||
assert len(old)==1 and len(selected)==1
|
||||
assert shapely.union_all([geometry(f)for f in selected.values()]).symmetric_difference(p).area<1e-12
|
||||
# A compound corner retains every member's end-to-end seam gate.
|
||||
neighbor=transaction('neighbor',box(-2.12,-.06,-.12,.06))
|
||||
evidence=appearance+[dict(geometry=neighbor['after'][0]['geometry'],properties=dict(source_tile='camera-a'))]
|
||||
guarded,_,_=select(dict(features=[]),new+[neighbor],evidence)
|
||||
assert len(guarded)==1,'Compound junction bypassed a member seam conflict'
|
||||
# Choosing a connected object must not spend its overlap twice.
|
||||
assert p.area<a.area+b.area
|
||||
assert compose(original[::-1],lambda p:p)[0]==new
|
||||
# Parallel alternative explanations, an internal crossing and a physical
|
||||
# gap cannot become a terminal connection.
|
||||
assert junction(a,box(0,-.05,2.06,.07))is None
|
||||
assert junction(a,box(.94,-1,1.06,1))is None
|
||||
assert junction(a,box(2.08,0,2.20,2))is None
|
||||
# Nearly square patches have overlapping terminal zones; different
|
||||
# fitted angles cannot turn two alternative patches into a line joint.
|
||||
from shapely.affinity import rotate
|
||||
short=box(-.15,-.135,.15,.135)
|
||||
assert junction(short,rotate(short,17,origin=(0,0)))is None
|
||||
duplicate_source=[transaction('a',a,['old']),transaction('b',b,['old'])]
|
||||
assert compose(duplicate_source,lambda p:p)[0]==[]
|
||||
guarded=[{**original[0],'atomic_family':True},original[1]]
|
||||
assert compose(guarded,lambda p:p)[0]==[]
|
||||
# Whole protected symbols are never eligible, even with a line-like outline.
|
||||
protected={**original[1],'after':[{**original[1]['after'][0],'properties':{'subtype':'right_arrow'}}]}
|
||||
assert compose([original[0],protected],lambda p:p)[0]==[]
|
||||
print('CONNECTED_CONFIGURATION_CONTRACT_OK',flush=True)
|
||||
|
||||
if __name__=='__main__':qualify()
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Synthetic connected-paint and negative controls; no historical map seeds."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
from connected_ridges import branches
|
||||
|
||||
def qualify():
|
||||
from shapely.geometry import Polygon,box
|
||||
def proposals(binary,mpp=.02):
|
||||
cs,_=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
|
||||
return [Polygon(p*mpp)for c in cs for p in branches(c,binary,mpp)]
|
||||
# Connected U-shaped parking paint has three bodies. Its whole envelope
|
||||
# is too wide to be a line; all three thin branches still get proposals.
|
||||
binary=np.zeros((190,190),np.uint8)
|
||||
binary[20:160,20:27]=1;binary[20:160,150:157]=1;binary[153:160,20:157]=1
|
||||
result=proposals(binary);assert result
|
||||
for target in [box(.4,.6,.52,2.9),box(3.,.6,3.12,2.9),box(.7,3.06,2.8,3.18)]:
|
||||
assert max(target.intersection(p.buffer(.025)).area/target.area for p in result)>.95
|
||||
# A wide solid pad or a single rectangle must not produce branch guesses.
|
||||
assert proposals(np.ones((80,100),np.uint8))==[]
|
||||
rect=np.zeros((120,120),np.uint8);rect[15:105,45:52]=1;assert proposals(rect)==[]
|
||||
# A filled diagonal wedge has no opposing parallel strip edges.
|
||||
wedge=np.zeros((160,160),np.uint8);cv2.fillPoly(wedge,[np.array([[10,10],[145,15],[90,140],[65,135]],np.int32)],1)
|
||||
assert proposals(wedge)==[]
|
||||
assert len(result)<=sum(len(cv2.approxPolyDP(c,1.25,True))for c in cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0])
|
||||
print('CONNECTED_RIDGE_CONTRACT_OK',flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':qualify()
|
||||
@@ -0,0 +1,69 @@
|
||||
import numpy as np
|
||||
from initial_views import choose,greedy,counts_at,POLICY,minimum_cover
|
||||
from observation_coverage import complete_coverage
|
||||
|
||||
def run():
|
||||
# The packed implementation must reproduce the original completion exactly.
|
||||
rng=np.random.default_rng(18)
|
||||
for points,original in [(np.c_[np.arange(-75,80,5),np.zeros(31)],np.array([[-40.,0.],[0.,0.],[40.,0.]])),(rng.uniform(-100,100,(800,2)),rng.uniform(-100,100,(20,2)))]:
|
||||
points=np.unique(points,axis=0);grid=np.unique(np.round(points/10)*10,axis=0)
|
||||
old,_=complete_coverage(points,original)
|
||||
selected,_=greedy(points,original,grid,len(original)+80)
|
||||
np.testing.assert_array_equal(selected,np.r_[original,np.asarray([r['center']for r in old]).reshape(-1,2)])
|
||||
fresh,report=choose(points,original,optimize=False)
|
||||
assert (counts_at(points,fresh)>=2).all() and len(fresh)<=len(selected)
|
||||
assert all(np.any(np.max(abs(fresh-c),axis=1)<1e-6)for c in original)
|
||||
np.testing.assert_array_equal(choose(points[::-1],original[::-1],optimize=False)[0],fresh)
|
||||
points=np.array([[-27.,0.],[27.,0.],[27.0000001,0.]])
|
||||
np.testing.assert_array_equal(counts_at(points,[[0.,0.]]),[1,1,0])
|
||||
for bad in [[],[[float('nan'),0.]]]:
|
||||
try:choose(bad,[[0.,0.]])
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('Invalid targets accepted')
|
||||
line=np.c_[np.arange(-40,41,20),np.zeros(5)]
|
||||
chosen,proof=minimum_cover(line,line,line,seconds=2.)
|
||||
assert len(chosen)==4 and proof['status']=='optimal'
|
||||
assert (counts_at(line,chosen)>=2).all()
|
||||
# A timeout can have no finite dual bound. Preserve the already complete
|
||||
# plan and publish valid JSON, rather than failing after safe fallback.
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
points=np.array([[0.,0.]]);pool=np.array([[0.,0.],[1.,0.]])
|
||||
for bound in [None,float('-inf'),float('nan')]:
|
||||
with patch('scipy.optimize.milp',return_value=SimpleNamespace(x=None,status=1,mip_dual_bound=bound)):
|
||||
chosen,proof=minimum_cover(points,pool,pool)
|
||||
np.testing.assert_array_equal(chosen,pool)
|
||||
assert proof['status']=='feasible-greedy-fallback' and proof['lower_bound']is None
|
||||
assert (counts_at(points,chosen)>=POLICY['required_views']).all()
|
||||
json.dumps(proof,allow_nan=False)
|
||||
# Coverage-only optimization may remove a useful structural view. Fixed
|
||||
# observers must survive even when they are redundant for ground coverage.
|
||||
points=np.array([[0.,0.]])
|
||||
pool=np.array([[-1.,0.],[0.,0.],[1.,0.]])
|
||||
chosen,proof=minimum_cover(points,pool,pool,seconds=2.,fixed=pool)
|
||||
np.testing.assert_array_equal(chosen,pool)
|
||||
assert proof['status']=='optimal'
|
||||
with patch('scipy.optimize.milp',return_value=SimpleNamespace(x=np.array([0.,1.,1.]),status=0,mip_dual_bound=2.)):
|
||||
chosen,proof=minimum_cover(points,pool,pool,fixed=pool)
|
||||
np.testing.assert_array_equal(chosen,pool)
|
||||
assert proof['status']=='feasible-greedy-fallback'
|
||||
# The planner returns only supplements; source jobs/index remain untouched.
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from initial_views import plan
|
||||
import copy
|
||||
with TemporaryDirectory()as tmp:
|
||||
root=Path(tmp);index={'tiles':[{'id':'struct-a','bounds_xy':[[-30.,-30.],[30.,30.]],'status':'surveyed'}]}
|
||||
job={'bounds_xy':[[-30.,-30.],[30.,30.]],'views':[{'id':'top','eye':[0.,0.,10.],'target':[0.,0.,0.]}]}
|
||||
(root/'struct-a').mkdir();(root/'struct-a/job.json').write_text(json.dumps(job));frozen=copy.deepcopy(index)
|
||||
with patch('initial_views.targets',return_value=np.array([[0.,0.]])):
|
||||
tiles,jobs,report=plan(root,index,selection=(np.array([[0.,0.],[10.,0.]]),{}))
|
||||
assert index==frozen and json.loads((root/'struct-a/job.json').read_text())==job
|
||||
assert len(tiles)==1 and report['structural_ids']==['struct-a']
|
||||
assert tiles[0]['id']=='primary-support-000' and tiles[0]['role']=='initial-two-view-support'
|
||||
print('INITIAL_VIEW_CONTRACT_OK',flush=True)
|
||||
|
||||
def test_initial_view_contract():run()
|
||||
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,86 @@
|
||||
from joint_choice import choose
|
||||
|
||||
def node(name,sources=(),incumbent=False,cost=0.):
|
||||
return dict(id=name,sources=list(sources),incumbent=incumbent,cost=cost)
|
||||
|
||||
def test_joint_beats_largest_first():
|
||||
nodes=[node('big'),node('left'),node('right')]
|
||||
chosen,r=choose(nodes,[('big','left'),('big','right')],[(['big'],5),(['left'],3),(['right'],3)])
|
||||
assert set(chosen)=={'left','right'} and r['optimal']
|
||||
|
||||
def test_shared_evidence_paid_once():
|
||||
chosen,r=choose([node('a',cost=.1),node('b',cost=.2)],[],[(['a','b'],10)])
|
||||
assert chosen==['a'] and r['components'][0]['objective']==9.9
|
||||
|
||||
def test_whole_family_not_split():
|
||||
nodes=[node('keep-a',['a'],True),node('keep-b',['b'],True),node('family',['a','b']),node('partial',['a'])]
|
||||
chosen,_=choose(nodes,[],[(['family'],10),(['partial'],7)])
|
||||
assert chosen==['family']
|
||||
|
||||
def test_unsupported_candidate_not_selected():
|
||||
chosen,_=choose([node('noise',cost=.1)],[],[])
|
||||
assert chosen==[]
|
||||
|
||||
def test_timeout_preserves_fresh_incumbent():
|
||||
nodes=[node('keep',['a'],True),node('replacement',['a'])]
|
||||
chosen,r=choose(nodes,[],[(['replacement'],20)],seconds=0.)
|
||||
assert chosen==['keep'] and not r['optimal']
|
||||
|
||||
def test_permutation_invariant():
|
||||
nodes=[node('a',cost=.1),node('b',cost=.2),node('c',cost=.1)]
|
||||
conflicts=[('a','b')];samples=[(['a','b'],3),(['c'],2)]
|
||||
assert choose(nodes,conflicts,samples)[0]==choose(nodes[::-1],conflicts[::-1],samples[::-1])[0]
|
||||
|
||||
def test_replacement_cannot_erase_another_source():
|
||||
nodes=[node('keep-a',['a'],True),node('keep-b',['b'],True),node('replacement',['a'])]
|
||||
chosen,_=choose(nodes,[('replacement','keep-b')],[(['replacement'],100)])
|
||||
assert set(chosen)=={'keep-a','keep-b'}
|
||||
|
||||
def test_conflict_cliques_exact_edge_cover():
|
||||
from joint_choice import conflict_cliques
|
||||
import itertools,random
|
||||
random.seed(18)
|
||||
for n,density in [(20,1.),(30,.7),(30,.1)]:
|
||||
edges={pair for pair in itertools.combinations(range(n),2) if random.random()<density}
|
||||
cliques=conflict_cliques(n,sorted(edges))
|
||||
recovered={tuple(sorted(pair)) for clique in cliques for pair in itertools.combinations(clique,2)}
|
||||
assert recovered==edges
|
||||
if density==1.:assert len(cliques)==1
|
||||
|
||||
|
||||
def test_independent_primary_channels_do_not_veto_each_other():
|
||||
from primary_evidence import collect
|
||||
from joint_assembly import select
|
||||
from shapely.geometry import box,mapping
|
||||
a,b=mapping(box(0,0,1,.1)),mapping(box(3,0,4,.1))
|
||||
appearance=[dict(geometry=a,properties=dict(source_tile='image-a'))]
|
||||
lines=[dict(polygon=b,source_tile='image-b')]
|
||||
configurations=[dict(kind='verified',source_ids=[],after=[dict(id=name,geometry=polygon,properties=dict(subtype='linear_marking'))],atomic_family=False) for name,polygon in [('a',a),('b',b)]]
|
||||
chosen,_,report=select(dict(features=[]),configurations,collect(appearance,lines))
|
||||
assert set(chosen)=={'a','b'} and report['optimal']
|
||||
empty,_,_=select(dict(features=[]),configurations,collect([],[]))
|
||||
assert not empty,'Unsupported configurations acquired invented evidence'
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
from qualify_row_graph_contract import run as graph
|
||||
from qualify_component_axis_contract import run as axis
|
||||
graph();axis()
|
||||
from test_connected_configurations import qualify as junctions
|
||||
junctions()
|
||||
from test_observed_geometry import qualify as observed_geometry
|
||||
observed_geometry()
|
||||
from test_object_evidence import qualify as object_evidence
|
||||
object_evidence()
|
||||
from measurement_reads import qualify
|
||||
qualify()
|
||||
from refine_markings import measured_width
|
||||
from interval_profiles import rectangle
|
||||
import numpy as np
|
||||
for length in [.27,.49,3.,70.]:
|
||||
for angle in [0.,.3,1.2]:
|
||||
polygon=rectangle(np.array([300.,-20.]),np.array([np.cos(angle),np.sin(angle)]),0.,length,.18)
|
||||
assert abs(measured_width(polygon)-.18)<1e-8
|
||||
print('PASS measured body width',flush=True)
|
||||
for name,fn in list(globals().items()):
|
||||
if name.startswith('test_'):fn();print('PASS',name,flush=True)
|
||||
@@ -0,0 +1,81 @@
|
||||
import numpy as np
|
||||
import shapely
|
||||
from marking_rules import check_strip
|
||||
from object_context import check, connection_supported, measure, relation
|
||||
from shapely.geometry import box
|
||||
|
||||
|
||||
def reader(paint, unknown=None):
|
||||
def read(xy):
|
||||
white = shapely.intersects_xy(paint, xy[:, 0], xy[:, 1])
|
||||
rgb = np.repeat(np.where(white, 230, 25).astype("uint8")[:, None], 3, axis=1)
|
||||
valid = np.ones(len(xy), bool)
|
||||
if unknown is not None:
|
||||
valid &= ~shapely.intersects_xy(unknown, xy[:, 0], xy[:, 1])
|
||||
return rgb, valid
|
||||
|
||||
return read
|
||||
|
||||
|
||||
def test_body_cannot_be_replaced_by_a_bright_axis():
|
||||
p = box(0, -0.15, 2, 0.15)
|
||||
read = reader(box(0, -0.03, 2, 0.03))
|
||||
m = measure(p, [read, read])
|
||||
assert not m["body_ok"]
|
||||
|
||||
|
||||
def test_metrics_agree_with_unchanged_strip_check():
|
||||
a = box(0, -0.1, 0.8, 0.1)
|
||||
b = box(0.6, -0.1, 0.8, 2)
|
||||
read = reader(a.union(b))
|
||||
for p in [a, b]:
|
||||
m = measure(p, [read, read])
|
||||
passed, ev = check_strip(p, [read, read])
|
||||
assert m["legacy"] == passed and m["legacy_evidence"] == ev
|
||||
|
||||
|
||||
def test_supported_neighbor_explains_only_its_own_body():
|
||||
a = box(0, -0.06, 0.7, 0.06)
|
||||
b = box(0.48, -0.35, 0.68, 0.35)
|
||||
read = reader(a.union(b))
|
||||
mm = [measure(p, [read, read]) for p in [a, b]]
|
||||
assert all(m["body_ok"] for m in mm), [(m["legacy_evidence"], m["body_evidence"]) for m in mm]
|
||||
assert not all(m["legacy"] for m in mm)
|
||||
assert relation(a, b) is not None and connection_supported(mm, a.intersection(b))[0]
|
||||
assert check(mm)[0]
|
||||
noise = box(0, -0.30, 0.45, -0.13)
|
||||
noisy = reader(a.union(b).union(noise))
|
||||
assert not check([measure(p, [noisy, noisy]) for p in [a, b]])[0]
|
||||
unknown = reader(a.union(b), box(0, -0.3, 0.6, -0.15))
|
||||
assert not check([measure(p, [unknown, unknown]) for p in [a, b]])[0]
|
||||
|
||||
|
||||
def test_context_cannot_override_failure_of_the_body_measurement():
|
||||
# A long bright arm can enter the transverse background estimate. This
|
||||
# experiment must report that body failure, never exempt it as context.
|
||||
a = box(0, -0.1, 0.8, 0.1)
|
||||
b = box(0.6, -0.1, 0.8, 2)
|
||||
read = reader(a.union(b))
|
||||
mm = [measure(p, [read, read]) for p in [a, b]]
|
||||
assert not all(m["body_ok"] for m in mm)
|
||||
assert not check(mm)[0]
|
||||
|
||||
|
||||
def test_graph_never_bridges_gaps_or_nearly_square_alternatives():
|
||||
assert relation(box(0, -0.06, 2, 0.06), box(2.1, 0, 2.22, 2)) is None
|
||||
from shapely.affinity import rotate
|
||||
|
||||
p = box(-0.15, -0.135, 0.15, 0.135)
|
||||
assert relation(p, rotate(p, 30)) is None
|
||||
assert relation(box(0, 0, 3, 0.1), box(0, 0.01, 3, 0.11)) is None
|
||||
|
||||
|
||||
def qualify():
|
||||
for name, f in list(globals().items()):
|
||||
if name.startswith("test_"):
|
||||
f()
|
||||
print("PASS", name, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
qualify()
|
||||
@@ -0,0 +1,86 @@
|
||||
import numpy as np
|
||||
from object_evidence import grid, inspect
|
||||
from shapely.geometry import Polygon, box
|
||||
|
||||
|
||||
def sampled(key):
|
||||
_, xy = grid(key)
|
||||
n = len(xy)
|
||||
paint = (xy[:, 0] > 0.2) & (xy[:, 0] < 5.8) & (abs(xy[:, 1]) < 0.1)
|
||||
physical = np.ones((2, n), bool)
|
||||
physical[1, xy[:, 0] > 5] = False
|
||||
road = np.ones((2, n), bool)
|
||||
road[:, xy[:, 0] < 0] = False
|
||||
return dict(physical=physical, road=road, paint=np.array([paint, paint]))
|
||||
|
||||
|
||||
def test_partition_and_duplicate_invariance():
|
||||
p = box(-0.3, -0.1, 6.3, 0.1)
|
||||
parts = [p.intersection(box(-1, -1, 2.13, 1)), p.intersection(box(2.13, -1, 7, 1))]
|
||||
one = inspect([p], sampled)
|
||||
for packed in [parts, parts[::-1], parts + [parts[0]], [parts[0].union(parts[1])]]:
|
||||
actual = inspect(packed, sampled)
|
||||
for k in ["body", "context", "evidence_signature", "tiles"]:
|
||||
assert actual[k] == one[k], k
|
||||
|
||||
|
||||
def test_holes_gaps_and_unknown_stay_distinct():
|
||||
p = box(-0.3, -0.1, 6.3, 0.1)
|
||||
hole = box(1, -0.06, 2, 0.06)
|
||||
full = inspect([p], sampled)
|
||||
cut = inspect([p.difference(hole)], sampled)
|
||||
assert cut["body"]["samples"] < full["body"]["samples"]
|
||||
assert full["body"]["unknown_physical"] > 0
|
||||
assert full["body"]["outside_road_observed"] > 0
|
||||
body = full["body"]
|
||||
assert (
|
||||
sum(
|
||||
body[k]
|
||||
for k in [
|
||||
"paint_supported",
|
||||
"observed_nonpaint",
|
||||
"view_disagreement",
|
||||
"outside_road_observed",
|
||||
"unknown_physical",
|
||||
]
|
||||
)
|
||||
== body["samples"]
|
||||
)
|
||||
|
||||
|
||||
def test_one_positive_view_cannot_confirm_paint():
|
||||
def sample(key):
|
||||
r = sampled(key)
|
||||
r["physical"][:] = True
|
||||
r["road"][:] = True
|
||||
r["paint"][0] = True
|
||||
r["paint"][1] = False
|
||||
return r
|
||||
|
||||
r = inspect([box(0, 0, 1, 1)], sample)["body"]
|
||||
assert r["paint_supported"] == 0 and r["view_disagreement"] == r["samples"]
|
||||
|
||||
|
||||
def test_area_and_evidence_are_invariant_to_ring_start_and_orientation():
|
||||
points = [
|
||||
(472.5013416099539, -59.336487630905765),
|
||||
(472.5883190697177, -59.462233676135256),
|
||||
(474.5004894447336, -58.1396018466333),
|
||||
(474.4135119849698, -58.01385580140381),
|
||||
]
|
||||
expected = inspect([Polygon(points)], sampled)
|
||||
for shift in range(len(points)):
|
||||
shifted = points[shift:] + points[:shift]
|
||||
for ring in [shifted, shifted[::-1]]:
|
||||
assert inspect([Polygon(ring)], sampled) == expected
|
||||
|
||||
|
||||
def qualify():
|
||||
for name, f in list(globals().items()):
|
||||
if name.startswith("test_"):
|
||||
f()
|
||||
print("PASS", name, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
qualify()
|
||||
@@ -0,0 +1,34 @@
|
||||
import shapely
|
||||
from marking_rules import missing_parts as fragmented_parts
|
||||
from observed_geometry import missing_parts
|
||||
from shapely.affinity import rotate, translate
|
||||
from shapely.geometry import box
|
||||
|
||||
|
||||
def test_unoccupied_measurement_is_an_exact_identity():
|
||||
for angle in [0.0, 17.0, 43.0, 81.0, 137.0]:
|
||||
p = translate(rotate(box(0, -0.075, 2.3, 0.075), angle, origin=(0, 0)), 474.0, -59.0)
|
||||
pieces = missing_parts(p, shapely.GeometryCollection())
|
||||
assert len(pieces) == 1 and pieces[0] is p and pieces[0].wkb == p.wkb
|
||||
distant = box(1000, 1000, 1001, 1001)
|
||||
assert missing_parts(p, distant)[0].wkb == p.wkb
|
||||
|
||||
|
||||
def test_actual_fragmentation_keeps_the_original_exclusion_and_section_rules():
|
||||
p = box(0, -0.075, 8, 0.075)
|
||||
for occupied in [box(2, -1, 3, 1), box(-1, -1, 9, 1), box(2, 0.12, 3, 0.2)]:
|
||||
actual = missing_parts(p, occupied)
|
||||
expected = fragmented_parts(p, occupied)
|
||||
assert [q.wkb for q in actual] == [q.wkb for q in expected]
|
||||
assert missing_parts(box(0, 0, 0.5, 0.1), shapely.GeometryCollection()) == []
|
||||
|
||||
|
||||
def qualify():
|
||||
for name, f in list(globals().items()):
|
||||
if name.startswith("test_"):
|
||||
f()
|
||||
print("PASS", name, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
qualify()
|
||||
@@ -0,0 +1,130 @@
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import LineString, Polygon, box
|
||||
from shared_surface_edges import reconcile
|
||||
|
||||
|
||||
def evidence(xy):
|
||||
return np.where(np.asarray(xy)[:,1] >= 0, 2, 1)
|
||||
|
||||
|
||||
def test_straight_shared_edge():
|
||||
source=box(0,0,10,4);road=LineString([(0,.2),(10,.2)])
|
||||
out,records=reconcile([source],[road],evidence)
|
||||
assert records[0]['accepted']
|
||||
assert out[0].boundary.intersection(road).length>8
|
||||
assert out[0].is_valid and source.buffer(-.6).difference(out[0]).is_empty
|
||||
|
||||
|
||||
def test_reversed_road_same_geometry():
|
||||
source=box(0,0,10,4);road=LineString([(0,.2),(10,.2)])
|
||||
a,_=reconcile([source],[road],evidence)
|
||||
b,_=reconcile([source],[LineString(list(road.coords)[::-1])],evidence)
|
||||
assert a[0].symmetric_difference(b[0]).area < 1e-7
|
||||
|
||||
|
||||
def test_unknown_strip_prevents_association():
|
||||
source=box(0,0,10,4);road=LineString([(0,.5),(10,.5)])
|
||||
def scan(xy):
|
||||
xy=np.asarray(xy);return np.where((xy[:,1]>.32)&(xy[:,1]<.42),0,evidence(xy))
|
||||
out,rec=reconcile([source],[road],scan)
|
||||
assert out[0].equals(source) and not rec[0]['accepted']
|
||||
|
||||
|
||||
def test_coverage_cap_not_physical_curb():
|
||||
source=box(0,0,10,4);road=LineString([(0,.2),(10,.2)])
|
||||
out,rec=reconcile([source],[road],lambda xy:np.where(np.asarray(xy)[:,1]>=0,2,0))
|
||||
assert out[0].equals(source) and not rec[0]['accepted']
|
||||
|
||||
|
||||
def test_ambiguous_parallel_boundaries_not_selected():
|
||||
source=box(0,0,10,4)
|
||||
out,rec=reconcile([source],[LineString([(0,.2),(10,.2)]),LineString([(0,.25),(10,.25)])],evidence)
|
||||
assert out[0].equals(source) and not rec[0]['accepted']
|
||||
|
||||
|
||||
def test_inferred_gap_stays_unshared():
|
||||
source=box(0,0,10,4);road=LineString([(0,.2),(10,.2)])
|
||||
out,rec=reconcile([source],[road],evidence,inferred=[[(3.,7.)]])
|
||||
assert rec[0]['accepted']
|
||||
for link in rec[0]['bindings']:
|
||||
a,b=link['station_interval_m'];assert max(a,3)>=min(b,7)
|
||||
assert out[0].boundary.intersection(LineString([(3,.2),(7,.2)])).length<1e-6
|
||||
|
||||
|
||||
def test_hole_preserved_without_moving_to_road():
|
||||
source=Polygon([(0,0),(10,0),(10,4),(0,4)],holes=[[(2,.4),(3,.4),(3,1),(2,1)]])
|
||||
road=LineString([(0,.15),(10,.15)])
|
||||
out,_=reconcile([source],[road],evidence)
|
||||
assert len(out[0].interiors)==1
|
||||
assert Polygon(out[0].interiors[0]).equals(Polygon(source.interiors[0]))
|
||||
|
||||
|
||||
def test_curve_uses_road_vertices_without_chord_shortcut():
|
||||
source=box(0,0,10,4);road=LineString([(0,.2),(3,.15),(5,.4),(7,.15),(10,.2)])
|
||||
out,rec=reconcile([source],[road],evidence)
|
||||
assert rec[0]['accepted']
|
||||
assert shapely.Point(5,.4).distance(out[0].boundary)<1e-8
|
||||
|
||||
|
||||
def test_no_road_extension():
|
||||
source=box(0,0,10,4);road=LineString([(2,.2),(8,.2)])
|
||||
out,rec=reconcile([source],[road],evidence)
|
||||
assert rec[0]['accepted']
|
||||
assert out[0].boundary.intersection(LineString([(0,0),(1,0)])).length>.99
|
||||
assert out[0].boundary.intersection(LineString([(9,0),(10,0)])).length>.99
|
||||
|
||||
|
||||
def test_input_order_does_not_choose_ambiguous_boundary():
|
||||
source=box(0,0,10,4);roads=[LineString([(0,.2),(10,.2)]),LineString([(0,.25),(10,.25)])]
|
||||
a,_=reconcile([source],roads,evidence);b,_=reconcile([source],roads[::-1],evidence)
|
||||
assert a[0].equals(b[0])
|
||||
|
||||
|
||||
def test_rigid_transform_preserves_policy():
|
||||
from shapely import affinity
|
||||
angle=.73;matrix=np.array([[np.cos(angle),-np.sin(angle)],[np.sin(angle),np.cos(angle)]]);offset=np.array([350.,-480.])
|
||||
source=box(0,0,10,4);road=LineString([(0,.2),(10,.2)])
|
||||
def move(g):return affinity.translate(affinity.rotate(g,np.degrees(angle),origin=(0,0)),*offset)
|
||||
a,_=reconcile([source],[road],evidence)
|
||||
b,rec=reconcile([move(source)],[move(road)],lambda xy:evidence((np.asarray(xy)-offset)@matrix))
|
||||
assert move(a[0]).symmetric_difference(b[0]).area<1e-6, (move(a[0]).symmetric_difference(b[0]).area,rec)
|
||||
|
||||
|
||||
def test_shared_xyz_comes_from_road_and_other_heights_are_preserved():
|
||||
from shared_surface_edges import reconcile_features
|
||||
def feature(g,kind):return dict(id=kind,geometry=shapely.geometry.mapping(g),properties={'class':kind,'method':'synthetic'})
|
||||
source=Polygon([(0,0,3),(10,0,3),(10,4,3),(0,4,3)])
|
||||
road=LineString([(0,.2,5),(10,.2,7)])
|
||||
out,topology=reconcile_features([feature(source,'pedestrian_area')],[feature(road,'road_boundary')],evidence)
|
||||
p=shapely.geometry.shape(out[0]['geometry']);a=np.array(p.exterior.coords)
|
||||
assert np.all(np.isfinite(a)) and a.shape[1]==3
|
||||
shared=a[abs(a[:,1]-.2)<1e-8];assert len(shared)>0
|
||||
assert np.allclose(shared[:,2],5+shared[:,0]*.2)
|
||||
assert np.allclose(a[a[:,1]>3,2],3)
|
||||
assert topology['edges'] and out[0]['properties']['physical_boundary_ids']==['road_boundary']
|
||||
|
||||
|
||||
def test_facade_corner_obeys_bridge_validator():
|
||||
from frontage_chains import join_planes
|
||||
a=LineString([(0,0),(5,0)]);b=LineString([(5.3,.3),(5.3,5)])
|
||||
accepted=join_planes([a,b],bridge_validator=lambda *_:True)
|
||||
rejected=join_planes([a,b],bridge_validator=lambda *_:False)
|
||||
assert not LineString(accepted[0][0]).equals(a)
|
||||
assert LineString(rejected[0][0]).equals(a) and LineString(rejected[1][0]).equals(b)
|
||||
|
||||
|
||||
def test_facade_corner_must_not_cross_third_front():
|
||||
from frontage_chains import join_planes
|
||||
a=LineString([(0,0),(5,0)]);b=LineString([(5.5,.3),(5.5,5)])
|
||||
c=LineString([(5.2,-.1),(5.3,.1)])
|
||||
out=join_planes([a,b,c],bridge_validator=lambda *_:True)
|
||||
assert LineString(out[0][0]).equals(a) and LineString(out[1][0]).equals(b)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
checks=sorted((name,fn) for name,fn in list(globals().items()) if name.startswith('test_') and callable(fn))
|
||||
for name,fn in checks:
|
||||
fn()
|
||||
print('PASS',name,flush=True)
|
||||
print('Shared surface contracts:',len(checks),'passed',flush=True)
|
||||
Reference in New Issue
Block a user