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:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
@@ -0,0 +1,71 @@
Full-image Gaussian paint discovery
==================================
Offline continuation of corridor-pass-20261012. All computation and image
processing run on Worker006. No point clouds, colliders, manual processing
regions, address-specific settings, live deployment or rover commands.
Method
------
1. Read every surveyed ground-render tile and the previously qualified extra
Gaussian tiles. Use native RGB resolution up to 4096 pixels for proposals,
instead of first reducing every image to 2048 pixels.
2. Reuse OpenCV top-hat paint extraction, components, Hough ridges and robust
row fitting. Proposals come from images; an existing vector is not required
to provide their axis. Existing non-linear markings are protected, and
already covered paint is excluded from final additions.
3. Keep the accepted road/alpha/vehicle gates. For extra tiles, reproject the
marking-proposal semantic field from the nearest original camera chosen
by geometry. This field nominates symbols, never proves their geometry.
4. Reuse periodic-row validation and attributed symbol presets. At every
station, select two covering Gaussian views by geometry before inspecting
paint. Require measured paint, gaps and agreement; symbols additionally
require shape parts, unpainted negative space, ends and lane context.
5. A measured solid strip may partly overlap an existing line. Subtract entire
occupied longitudinal intervals and validate each remaining section in two
full-object views. Do not emit thin parallel residual slivers. Minimum new
section length is 2.7 m. Fully present markings are not duplicated.
6. Addition-only transaction replay, all inherited controlled checks, full
three-scene regression and visual inspection of every admitted transaction.
Execution
---------
The qualification replay ZIP contains the operator runner, scene registry and
verification helpers. It requires the existing canonical checkout and accepted
Worker caches, the pinned image and the official recorded-job queue. It is not
a self-contained export of private scans. Source bundle mappings reuse identical
canonical components. The review-only font remains in the qualification cache.
Each stage uses a network-disabled, read-only-root container, 4 CPUs and 20 GiB
RAM, a bounded timeout and an official reservation. No new renders or new GPU
model are needed in this pass. Receipts pin all source files, baseline maps,
container image, UTC and monotonic execution times and resource release.
Limits
------
The extra tiles were planned from periodic marking families in the prior pass;
they do not guarantee two-view coverage of every scene point. Semantic road and
vehicle masks can still reject real paint. Two renders of one reconstruction
share its errors. Higher raster resolution is not higher physical scan accuracy.
Known-scene regression is not proof of generalization to an unseen map.
No full recall, absolute metric accuracy or GOST compliance has been measured.
All previous objects remain unchanged; this pass cannot repair their geometry.
Reuse and attribution
---------------------
OpenCV, SciPy, Shapely and existing calibrated Gaussian RGB/evidence fields.
Arrow artwork by MajorAlexey, adapted to normalized polygon presets under
CC BY-SA 4.0:
https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg
https://creativecommons.org/licenses/by-sa/4.0/
Qualified result
----------------
Frozen source 0295e2cbfe5964dae45d. All 248 controlled checks passed.
Maroseyka: two new straight-arrow preset instances and one measured long stroke.
Pokrovka: seven new periodic strokes in two transactions, including a six-stroke
row absent from the previous vector map in that region. Smolensk: no additions.
Five transactions, ten added objects, zero modifications of previous features.
All five transactions were visually reviewed. A measured long stroke is not
automatically classified as a solid divider. Missing glyphs, strokes and divider
continuations remain visible; this pass does not claim complete infrastructure.
@@ -0,0 +1,36 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
from search_rules import POLICY,VERSION,uncovered,glyph_pass
from beta_profiles import supported
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/search-rows.json').read_text());current={f['id']:f for f in old['features']}
def poly(f):return shapely.force_2d(shape(f['geometry']))
existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'])
checks=dict(transaction_replay=True,only_paint_added=True,no_new_neighbor_overlap=True,evidence_passes=True,independent_image_proposals=True)
for r in rows:
checks['transaction_replay']&=not r['before']and not r['source_ids']and r['output_ids']==[f['id']for f in r['after']]and all(f['id']not in current for f in r['after'])
checks['independent_image_proposals']&=r['discovery_without_vector_seed']
checks['only_paint_added']&=all(f['properties']['class']=='road_marking'and f['properties']['method']==VERSION for f in r['after'])
okay=len(set(r['source_tiles']))>=2;ev=r['evidence']
if r['kind']=='glyph':okay&=len(ev)==2 and all(glyph_pass(e)and len(e.get('parts',[]))>=2 and len(e.get('ends',[]))==2 for e in ev)and r['template_fit_score']>=POLICY['symbol_proposal_score'] and r['fit_recall']>=POLICY['symbol_proposal_recall']and r['lane_context']['passed']and r['lane_context']['supporting_strips']>=2
elif r['kind']=='observed-strip':
okay&=len(ev['paint'])==2 and len(ev['ends'])==4 and all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']and e['contrast']>=22 for e in ev['paint'])and all(e.get('full_corridor')and supported(e,False)for e in ev['ends'])
okay&=len(ev['section_views'])==2 and all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']for e in ev['section_views'])
parent=shape(ev['parent_geometry'])
okay&=all(poly(f).difference(parent.buffer(.001)).area<.001 for f in r['after'])
elif r['kind']=='periodic-row':
okay&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint'])and len(ev['gaps'])==2*(len(ev['observations'])-1)
okay&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps'])
okay&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=.20 for e in ev['observations'])
else:okay=False
checks['evidence_passes']&=okay
for f in r['after']:
checks['no_new_neighbor_overlap']&=uncovered(poly(f),existing);existing=shapely.union_all([existing,poly(f)]);current[f['id']]=f
features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features'])
checks['all_baseline_objects_unchanged']=all(features.get(f['id'])==f for f in old['features'])
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
report=json.loads(Path('/out/search-report.json').read_text());checks['same_policy']=new['search_refinement']==VERSION and report['policy']==POLICY
checks['every_operation_counted']=report['changed_segments']==len(rows)and report['added_objects']==sum(len(r['after'])for r in rows)
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/search-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,168 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_beta.py": "beta_pass/audit_beta.py",
"audit_completion.py": "completion_pass/audit_completion.py",
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_corridor.py": "corridor_pass/audit_corridor.py",
"audit_discovery.py": "discovery_pass/audit_discovery.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_rows.py": "rows_pass/audit_rows.py",
"audit_search.py": "search_pass/audit_search.py",
"audit_sections.py": "sections_pass/audit_sections.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"beta_profiles.py": "beta_pass/beta_profiles.py",
"completion_profiles.py": "completion_pass/completion_profiles.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"coordinate_cache.py": "orthophoto/coordinate_cache.py",
"corridor_profiles.py": "search_pass/corridor_profiles.py",
"coverage_evidence.py": "corridor_pass/coverage_evidence.py",
"coverage_plan.py": "corridor_pass/coverage_plan.py",
"diagnose_corridor.py": "corridor_pass/diagnose_corridor.py",
"diagnose_coverage.py": "corridor_pass/diagnose_coverage.py",
"discovery_evidence.py": "discovery_pass/discovery_evidence.py",
"discovery_rules.py": "discovery_pass/discovery_rules.py",
"extract_discovery.py": "discovery_pass/extract_discovery.py",
"extract_search.py": "search_pass/extract_search.py",
"fit_scene.py": "full_plan/fit_scene.py",
"fragment_templates.py": "discovery_pass/fragment_templates.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"mapping.py": "corridor_pass/mapping.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"ortho_terrain.py": "orthophoto/ortho_terrain.py",
"paint_templates.py": "continuation_pass/paint_templates.py",
"refine_beta.py": "beta_pass/refine_beta.py",
"refine_completion.py": "completion_pass/refine_completion.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_corridor.py": "corridor_pass/refine_corridor.py",
"refine_discovery.py": "discovery_pass/refine_discovery.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_rows.py": "rows_pass/refine_rows.py",
"refine_search.py": "search_pass/refine_search.py",
"refine_sections.py": "sections_pass/refine_sections.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_beta.py": "beta_pass/render_beta.py",
"render_completion.py": "completion_pass/render_completion.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_corridor.py": "corridor_pass/render_corridor.py",
"render_coverage.py": "corridor_pass/render_coverage.py",
"render_discovery.py": "discovery_pass/render_discovery.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "search_pass/render_plan.py",
"render_rows.py": "rows_pass/render_rows.py",
"render_search.py": "search_pass/render_search.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"road_glyph_presets.py": "continuation_pass/road_glyph_presets.py",
"row_evidence.py": "corridor_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.py",
"search_rules.py": "search_pass/search_rules.py",
"search_views.py": "search_pass/search_views.py",
"section_profiles.py": "sections_pass/section_profiles.py",
"test_beta.py": "beta_pass/test_beta.py",
"test_completion.py": "completion_pass/test_completion.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_corridor.py": "corridor_pass/test_corridor.py",
"test_discovery.py": "discovery_pass/test_discovery.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_rows.py": "rows_pass/test_rows.py",
"test_search.py": "search_pass/test_search.py",
"test_sections.py": "sections_pass/test_sections.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py",
"validation.py": "corridor_pass/validation.py"
},
"reference_qualification": "search-pass-20261013",
"source_snapshot": "0295e2cbfe5964dae45d",
"source_sha256": {
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe",
"audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4",
"corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672",
"coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497",
"coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda",
"diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6",
"diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7",
"discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb",
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
"extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681",
"extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f",
"refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f",
"render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c",
"render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "98e2f7ab10755855ade7dacc462707c10c838906d75e90bfbbf1c551b24f6af8",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41",
"search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703",
"test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e",
"validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,82 @@
"""Metric corridor calibration from measured paint, shared by all locations.
OpenCV transverse background, SciPy peaks and robust polynomial least squares.
The old vectors nominate a corridor, never dictate its paint length or offset.
"""
import numpy as np
from scipy.signal import find_peaks,peak_widths
from scipy.ndimage import gaussian_filter1d
from scipy.optimize import least_squares
from interval_profiles import strip,runs,rectangle
from completion_profiles import POLICY as BASE,slot
VERSION='paint-corridor-calibration-v1'
POLICY={**BASE,'max_measured_offset_m':.35,'min_calibration_anchors':3,'max_curve_angle_deg':8.,'max_curve_second_derivative':.02,'max_curve_residual_m':.06,'max_measured_phase_m':.35,'max_length_recalibration_ratio':.5,'max_curve_extrapolation_m':8.,'min_pair_support':.85}
def measure(seed,index,readers,debug=None):
if len(readers)!=2:return None
o,u=seed['origin'],seed['axis'];P,L=seed['period'],seed['length'];c=index*P;step=.025;ext=min(P/2,L/2+max(.5,.3*L));ts=np.arange(c-ext,c+ext+step/2,step);ns=np.arange(-.7,.701,step);records=[]
for vi,read in enumerate(readers):
con,allowed=strip(o,u,ts,ns,read);core=abs(ts-c)<min(.3*L,.3*P);tr=np.median(np.where(allowed[core],con[core],0),axis=0);pk,_=find_peaks(tr,height=22,prominence=10,distance=4);pk=[k for k in pk if abs(ns[k])<=POLICY['max_measured_offset_m']]
if not pk:
if debug is not None:debug.update(reason='no-measured-ridge',view=vi)
return None
k=min(pk,key=lambda k:abs(ns[k]));W=float(peak_widths(tr,[k],rel_height=.5)[0][0]*step)
if not .045<=W<=.35:
if debug is not None:debug.update(reason='ridge-width',width=W,view=vi)
return None
band=abs(ns-ns[k])<=.04;sig=gaussian_filter1d(np.median(con[:,band],axis=1),1);valid=allowed[:,band].all(1);cut=max(15.,.35*float(np.median(sig[core])));on=(sig>cut)&valid
for a,b in runs(~on):
if a>0 and b<len(ts)and(b-a)*step<=.125 and valid[a:b].all():on[a:b]=True
opts=[(ts[a]-step/2,ts[b-1]+step/2)for a,b in runs(on)if a>0 and b<len(ts)]
if L<1.45:
pk2,_=find_peaks(np.where(valid,sig,0),prominence=22,distance=max(1,int(.45/step)));ws=peak_widths(np.where(valid,sig,0),pk2,rel_height=.5)
opts += [(ts[0]+a*step,ts[0]+b*step)for a,b in zip(ws[2],ws[3])if a>0 and b<len(ts)-1]
opts=[ab for ab in opts if .26<=ab[1]-ab[0]<=min(10.5,P-.15)and abs((ab[0]+ab[1])/2-c)<=POLICY['max_measured_phase_m']and abs(ab[1]-ab[0]-L)<=max(.20,L*POLICY['max_length_recalibration_ratio'])]
if not opts:
if debug is not None:debug.update(reason='no-measured-stroke',view=vi)
return None
lo,hi=min(opts,key=lambda ab:abs((ab[0]+ab[1])/2-c)+.1*abs(ab[1]-ab[0]-L));center=(lo+hi)/2;length=hi-lo
sel=abs(ts-center)<.35*length;bright=dict(valid=float(valid[sel].mean()),support=float((sig[sel]>cut).mean()),contrast=float(np.median(sig[sel])))
if bright['valid']<.95 or bright['support']<.82 or bright['contrast']<22:return None
records.append(dict(center=center,offset=float(ns[k]),length=length,width=W,paint=bright,edges=[lo,hi]))
if abs(records[0]['offset']-records[1]['offset'])>.05 or max(abs(records[0]['edges'][j]-records[1]['edges'][j])for j in [0,1])>.20:return None
return dict(index=index,center=float(np.mean([r['center']for r in records])),offset=float(np.mean([r['offset']for r in records])),length=float(np.median([r['length']for r in records])),width=float(np.median([r['width']for r in records])),views=records)
def calibrate(seed,observations):
anchors=[r for r in observations if r['index']in seed['indices']]
if len(anchors)<POLICY['min_calibration_anchors']:return None
indices=np.array([r['index']for r in anchors]);ts=np.array([r['center']for r in anchors]);ys=np.array([r['offset']for r in anchors]);lengths=np.array([r['length']for r in anchors]);L=float(np.median(lengths));P,phase=np.polyfit(indices,ts,1)
if abs(P-seed['period'])>.10*seed['period']or max(abs(ts-(phase+indices*P)))>.20 or max(abs(lengths-L))>max(.20,.25*L):return None
mid=float(np.mean(ts));scale=max(1.,float(np.ptp(ts)));x=(ts-mid)/scale;degree=2 if len(anchors)>=5 and np.ptp(ts)>=4 else 1
A=np.stack([x**i for i in range(degree+1)],1);coef=least_squares(lambda c:A@c-ys,np.linalg.lstsq(A,ys,rcond=None)[0],loss='soft_l1',f_scale=.025).x
res=np.abs(A@coef-ys)
if max(res)>POLICY['max_curve_residual_m']:return None
probe=np.linspace(ts.min()-8,ts.max()+8,100);xx=(probe-mid)/scale;dy=np.polynomial.polynomial.polyval(xx,np.arange(1,len(coef))*coef[1:])/scale
second=2*coef[2]/scale**2 if degree==2 else 0.
if max(abs(dy))>np.tan(np.deg2rad(POLICY['max_curve_angle_deg']))or abs(second)>POLICY['max_curve_second_derivative']:return None
return dict(origin=seed['origin'],axis=seed['axis'],period=float(P),phase=float(phase),length=L,width=float(np.clip(np.median([r['width']for r in anchors]),.075,.27)),mid=mid,scale=scale,coef=coef,anchor_range=[float(ts.min()),float(ts.max())],anchors=anchors,max_residual=float(max(res)))
def local_seed(model,index):
t=model['phase']+index*model['period'];x=(t-model['mid'])/model['scale'];coef=model['coef'];d=float(np.polynomial.polynomial.polyval(x,coef));slope=float(np.polynomial.polynomial.polyval(x,np.arange(1,len(coef))*coef[1:])/model['scale']);u=model['axis'];n=np.array([-u[1],u[0]]);axis=u+slope*n;axis/=np.linalg.norm(axis)
if abs(d)>POLICY['max_measured_offset_m']or t<model['anchor_range'][0]-POLICY['max_curve_extrapolation_m']or t>model['anchor_range'][1]+POLICY['max_curve_extrapolation_m']:return None
return dict(origin=model['origin']+t*u+d*n,axis=axis,period=model['period'],length=model['length'],width=model['width'])
def validated_slot(model,index,readers,debug=None):
local=local_seed(model,index)
if local is None:return None
return slot(local,0,readers,debug)
def missing_sections(candidate,existing):
"""Subtract occupied longitudinal intervals, never create parallel side slivers."""
import shapely
from layer_common import parts
from beta_profiles import describe
d=describe(candidate)
if d is None:return []
o,u=d['origin'],d['axis'];output=candidate
nearby=existing.intersection(candidate.buffer(.10,join_style=2))
for part in parts(nearby):
if part.is_empty:continue
tt=(shapely.get_coordinates(part)-o)@u
output=output.difference(rectangle(o,u,float(tt.min())-.12,float(tt.max())+.12,2.))
return [p for p in parts(output)if (z:=describe(p))is not None and z['length']>=2.7 and p.area>.15]
@@ -0,0 +1,66 @@
from pathlib import Path
import json,time,hashlib
import numpy as np,cv2,shapely
from PIL import Image
from shapely.geometry import Polygon,shape,mapping
from scipy.ndimage import distance_transform_edt
from layer_common import O,S,sample,parts
from fit_scene import world,project
from line_reconstruction import extract,dedup
from search_rules import POLICY,eligible_symbol,pack
from search_views import SearchViews
cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-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('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
views=SearchViews(tiles,labels,low,high,None);tiles=views.tiles
inside=distance_transform_edt(labels==1)*.1
protected=[shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']
protected_union=shapely.union_all(protected);symbols=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')not in ['linear_marking','crosswalk']])
lines=[];glyphs=[];reports=[]
for tile in tiles:
name=tile['id'];g=views.geometry(name);native_rgb,raw_vehicle=views.inputs(name);size=min(native_rgb.shape[0],POLICY['proposal_image_size']);mpp=60/size
rgb=native_rgb if native_rgb.shape[0]==size else cv2.resize(native_rgb,(size,size),interpolation=cv2.INTER_AREA)
vehicle=cv2.resize(raw_vehicle,(size,size))
semantic=views.semantics(name,size)
def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g)
yy,xx=np.mgrid[:size,:size];points=xy(np.c_[xx.ravel(),yy.ravel()]);allowed=(sample(inside,points,low,high)>.25).reshape(size,size)&(vehicle<.2)&(cv2.resize(g['alpha'].astype('float32'),(size,size))>.65)
mask=np.zeros((size,size),np.uint8);domain=shapely.box(*tile['bounds_xy'][0],*tile['bounds_xy'][1])
for p in protected:
if p.intersects(domain):
for q in parts(p.buffer(.10)):cv2.fillPoly(mask,[np.rint((project(q.exterior.coords,g)+.5)*size/1200-.5).astype('int32')],1)
observations,rec=extract(rgb,allowed&(mask==0),xy,name,mpp);lines.extend(observations)
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<.018:continue
holes=[];j=hier[0,i,2]
while j>=0:
if cv2.contourArea(cc[j])*mpp*mpp>.018:holes.append(xy(cc[j][:,0]))
j=hier[0,j,0]
p=shapely.make_valid(Polygon(xy(c[:,0]),holes));components.extend(parts(p))
union=shapely.union_all(components);proposals=list(components)
for radius in POLICY['fragment_join_radii_m']:
for region in parts(union.buffer(radius).buffer(-radius)):
if not eligible_symbol(region):continue
p=union.intersection(region.buffer(.02))
if not p.is_empty:proposals.append(p)
count=0
for p in proposals:
if not eligible_symbol(p)or p.intersection(symbols).area/p.area>.35:continue
coords=project(np.asarray(p.convex_hull.exterior.coords),g);uv=np.rint((coords+.5)*size/1200-.5).astype('int32');x,y,w,h=cv2.boundingRect(uv)
if x<0 or y<0 or x+w>size or y+h>size:continue
sel=np.zeros((h,w),np.uint8);cv2.fillPoly(sel,[uv-[x,y]],1);vals=semantic[y:y+h,x:x+w][sel>0]
mean=float(vals.mean());peak=float(np.quantile(vals,.9))
if mean<POLICY['min_semantic_mean']or peak<POLICY['min_semantic_peak']:continue
glyphs.append(dict(geometry=mapping(p),source_tile=name,semantic_mean=mean,semantic_peak=peak));count+=1
reports.append(dict(tile=name,**rec,glyph_proposals=count,proposal_pixels=size,additional_frame=name in views.additional));print('TILE',name,'LINES',len(observations),'GLYPHS',count,flush=True)
records=dedup(lines);candidates=[]
for r in sorted(glyphs,key=lambda r:-shape(r['geometry']).area):
p=shape(r['geometry'])
if any(p.intersection(shape(q['geometry'])).area/min(p.area,shape(q['geometry']).area)>.75 for q in candidates):continue
candidates.append(r)
(O/'search-proposals.json').write_text(json.dumps(dict(lines=[pack(r)for r in records],glyphs=candidates,tile_reports=reports,seconds=time.monotonic()-start,policy=POLICY,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest()),allow_nan=False))
print('PROPOSALS',len(records),len(candidates),flush=True)
@@ -0,0 +1,106 @@
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 line_reconstruction import rows
from beta_profiles import describe,profiles,discover,section_evidence,supported
from interval_profiles import rectangle
from row_evidence import GaussianViews
from search_rules import VERSION,POLICY,unpack,uncovered,glyph_pass,glyph_context
from discovery_evidence import glyph_views
from search_views import SearchViews
from fragment_templates import fit_symbol
from gost_catalog import assess_dash
from corridor_profiles import missing_sections
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']}
proposals=json.loads((O/'search-proposals.json').read_text());assert proposals['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest()
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)
paint=[poly(f)for f in old['features']if f['properties']['class']=='road_marking'];existing=shapely.union_all(paint)
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(polys,subtype,kind,evidence,source_tiles,**extra):
global existing
kept=[p for p in polys if uncovered(p,existing)]
if not kept:return False
new=[feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_ids=[],source_tile=source_tiles[0],source_tiles=source_tiles,line_kind='dashed'if kind=='periodic-row'else'unclassified-strip'if kind=='observed-strip'else None,standard_compliance='not_assessed',**extra)for p in kept]
if len(set(f['id']for f in new))!=len(new)or any(f['id']in current for f in new):return False
for f in new:current[f['id']]=f
existing=shapely.union_all([existing]+kept)
transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']for f in new],before=[],after=new,bounds_xy=shapely.union_all(polys).bounds,evidence=evidence,source_tiles=source_tiles,discovery_without_vector_seed=True,**extra))
print('ADMIT',len(transactions),kind,subtype,len(new),flush=True);return True
# Fragment sets and complete components share the same attributed presets.
# The two full-object render footprints are selected by geometry only.
records=[unpack(r)for r in proposals['lines']]
for gi,r in enumerate(proposals['glyphs']):
p=shape(r['geometry']);diag=[];f=fit_symbol(p,diagnostics=diag)
if f is None:diagnostics.append(dict(kind='glyph',reason='template-rejected',proposal=gi,best_score=max((q['score']for q in diag),default=0),model_trials=diag));continue
polygon,score,kind,recall,params=f
if not uncovered(polygon,existing):continue
context=glyph_context(polygon,params,records)
if not context['passed']:diagnostics.append(dict(kind='glyph',proposal=gi,reason='no-compatible-lane-context',context=context,geometry=mapping(polygon)));continue
ev,names=glyph_views(polygon,views,kind,params);okay=len(ev)==2 and len(set(names))==2 and all(glyph_pass(e)for e in ev)
diagnostics.append(dict(kind='glyph',proposal=gi,subtype=kind,score=score,evidence=ev,passed=okay,geometry=mapping(polygon)))
if okay:admit([polygon],kind,'glyph',ev,names,template_fit_score=score,fit_recall=recall,template_parameters=params,fragment_count=len(getattr(p,'geoms',[p])),lane_context=context)
if gi%10==0:print('GLYPH',gi+1,'/',len(proposals['glyphs']),flush=True)
views.protected=shapely.union_all([protected]+[poly(f).convex_hull for f in current.values()if f['properties'].get('method')==VERSION and f['properties'].get('subtype')!='linear_marking'])
# Use both individual image strips and robust component-center row hypotheses.
# No old vector supplies a proposal axis or selects a processing neighborhood.
records=[unpack(r)for r in proposals['lines']];seeds=[]
for r in records:
if r['W']<=.35 and r['L']>=.3 and r['polygon'].intersection(existing.buffer(.1)).area/r['polygon'].area<.99:
seed=describe(r['polygon'])
if seed is not None:seeds.append(seed)
for row in rows(records):
if len(row['records'])<3:continue
o,u=row['origin'].astype(float),row['axis'].astype(float);u/=np.linalg.norm(u);ts=(row['points']-o)@u;L=float(ts.max()-ts.min())
if 1<L<70:
p=rectangle(o,u,float(ts.min()),float(ts.max()),.12)
if p.intersection(existing.buffer(.1)).area/p.area<.99:seeds.append(dict(origin=o+(ts.max()+ts.min())/2*u,axis=u,length=L,width=.12))
seen=[];periodic=[];solids=[];profiled=0;profile_stats=collections.Counter()
for si,seed in enumerate(sorted(seeds,key=lambda r:(int(np.argmin(np.linalg.norm(views.centers-r['origin'],axis=1))),-r['length']))):
domain=rectangle(seed['origin'],seed['axis'],-seed['length']/2,seed['length']/2,.14)
if any(domain.intersection(p).area/domain.area>.8 for p in seen):continue
seen.append(domain);profiled+=1;readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers)
profile_stats['two_view_profile'if pv is not None else 'no_two_view_profile']+=1
found=discover(seed,pv)
for r in found:r['source_tiles']=sorted(set(used[0])|set(used[1]));periodic.append(r)
if pv is not None and seed['length']>=POLICY['min_solid_length_m']:
# Keep measured uninterrupted intervals only. Endpoints of new solids
# come from agreeing paint runs, never a semantic/visibility mask edge.
for a,b in pv[0]['intervals']:
if b-a<3 or b<-seed['length']/2 or a>seed['length']/2:continue
matches=[(c,d)for c,d in pv[1]['intervals']if max(abs(a-c),abs(b-d))<=.2]
if not matches:continue
c,d=min(matches,key=lambda z:abs(z[0]-a)+abs(z[1]-b));lo0,hi0=(a+c)/2,(b+d)/2
ev=[section_evidence(v,lo0+.1,hi0-.1)for v in pv]
if not all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']and e['contrast']>=22 for e in ev):continue
from beta_profiles import corridor_dark
ends=[corridor_dark(v,*span)for v in pv for span in [(lo0-.3,lo0-.07),(hi0+.07,hi0+.3)]]
if not all(supported(e,False)for e in ends):continue
p=rectangle(seed['origin'],seed['axis'],lo0,hi0,float(np.clip(np.median([v['width']for v in pv]),.075,.27)),float(np.mean([v['offset']for v in pv])))
solids.append(dict(polygon=p,evidence=dict(paint=ev,ends=ends),source_tiles=sorted(set(used[0])|set(used[1]))))
if profiled%25==0:print('PROFILE',profiled,'/',len(seeds),'ROWS',len(periodic),'SOLIDS',len(solids),flush=True)
for r in sorted(periodic,key=lambda r:-len(r['polygons'])):
ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode'])
admit(r['polygons'],'linear_marking','periodic-row',ev,r['source_tiles'],period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width']))
for r in sorted(solids,key=lambda r:-r['polygon'].area):
# Existing parts of a measured stripe must not discard its absent sections.
# Subtract full longitudinal occupancy, avoiding parallel side slivers.
for section in missing_sections(r['polygon'],existing):
scores,names=glyph_views(section,views,None,None)
if len(scores)!=2 or not all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']for e in scores):continue
ev={**r['evidence'],'section_views':scores,'parent_geometry':mapping(r['polygon'])}
admit([section],'linear_marking','observed-strip',ev,sorted(set(r['source_tiles']+names)))
result={**old,'features':list(current.values()),'search_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
(O/'search-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'search-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()-start,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(collections.Counter(r['kind']for r in transactions)),profiled_axes=profiled,profile_stats=dict(profile_stats),raw_line_proposals=len(records),raw_glyph_proposals=len(proposals['glyphs']),added_objects=sum(len(r['after'])for r in transactions),added_subtypes=dict(collections.Counter(f['properties']['subtype']for r in transactions for f in r['after'])),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'search-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,107 @@
"""Evidence images from metric vectors, not AI-generated imagery."""
from pathlib import Path
import json,os,shapely
from datetime import datetime,timezone
import shutil
import numpy as np
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape,box
from fit_scene import project
from search_views import SearchViews
from layer_common import B,O,S
D=json.loads((O/'full-map.json').read_text());v=json.loads((B/'viewer-data.json').read_text());low,high=np.asarray(v['bounds_xy']);res=v['resolution_m'];fontpath='/candidate/review-font.ttf'
prior=set(O.glob('bridge-*.jpg'))|{O/'glyph-proof.jpg'}
for p in prior:
if p.exists():
history=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));history.mkdir(parents=True,exist_ok=True);shutil.move(p,history/p.name)
try:font=ImageFont.truetype(fontpath,20)
except OSError:font=ImageFont.load_default()
colors={'road_boundary':(236,124,25),'pedestrian_boundary':(18,165,92),'building_facade':(0,151,224),'road_marking':(241,195,0)}
def draw_plan(im,projector,features,width=3):
rgba=im.convert('RGBA');fill=Image.new('RGBA',im.size);df=ImageDraw.Draw(fill)
for f in features:
if f['properties']['class']!='pedestrian_area':continue
rings=f['geometry']['coordinates']
df.polygon([tuple(q)for q in projector(rings[0])],fill=(25,193,120,58))
for ring in rings[1:]:df.polygon([tuple(q)for q in projector(ring)],fill=(0,0,0,0))
rgba=Image.alpha_composite(rgba,fill);draw=ImageDraw.Draw(rgba)
for cls in ['pedestrian_boundary','building_facade','road_marking','road_boundary']:
for f in features:
if f['properties']['class']!=cls:continue
rings=f['geometry']['coordinates']if f['geometry']['type']=='Polygon'else[f['geometry']['coordinates']]
for ring in rings:
pts=[tuple(q)for q in projector(ring)];draw.line(pts,fill=colors[cls],width=width,joint='curve')
return rgba.convert('RGB')
def title(im,name):
result=Image.new('RGB',(im.width,im.height+68),'white');result.paste(im,(0,68));d=ImageDraw.Draw(result);d.text((15,7),name,font=font,fill='#263640')
x=15
for text,clr in [('Дороги',(236,124,25)),('Пешеходные зоны',(18,165,92)),('Фасады',(0,151,224)),('Разметка',(200,155,0))]:
d.rectangle((x,42,x+20,57),fill=clr);d.text((x+29,37),text,font=font,fill='#263640');x+=int(d.textlength(text,font=font))+64
return result
world=lambda p:np.c_[(np.asarray(p)[:,0]-low[0])/res,(high[1]-np.asarray(p)[:,1])/res]
if (B/'whole-gaussians.jpg').exists():base=Image.open(B/'whole-gaussians.jpg').convert('RGB')
else:
width,height=v['size'];mosaic=np.full((height,width,3),255,np.uint8);weights=np.zeros((height,width),np.float32)
for tile in json.loads((S/'tile-index.json').read_text())['tiles']:
if tile['status']!='surveyed':continue
lo,hi=np.asarray(tile['bounds_xy']);tw,th=np.rint((hi-lo)/res).astype(int);x,y=np.rint([(lo[0]-low[0])/res,(high[1]-hi[1])/res]).astype(int)
im=np.asarray(Image.open(S/tile['id']/'top.png').convert('RGB').resize((tw,th),Image.Resampling.LANCZOS));g=np.load(S/tile['id']/'top.geometry.npz');alpha=np.asarray(Image.fromarray(g['alpha'].astype('float32')).resize((tw,th),Image.Resampling.BILINEAR));g.close()
yy,xx=np.mgrid[:th,:tw];score=(.01+np.minimum.reduce([xx+1,yy+1,tw-xx,th-yy])/max(tw,th))*np.clip(alpha,0,1);sl=np.s_[y:y+th,x:x+tw];take=score>weights[sl];mosaic[sl][take]=im[take];weights[sl][take]=score[take]
base=Image.fromarray(mosaic)
whole=draw_plan(base,world,D['features']);whole.save(O/'whole-overlay.jpg',quality=96)
plan=draw_plan(Image.new('RGB',base.size,'#f5f5f2'),world,D['features']);title(plan,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · инженерные слои').save(O/'whole-plan.jpg',quality=96)
preview=whole.copy();preview.thumbnail((2300,1500));title(preview,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · четыре слоя поверх гауссов').save(O/'overview.jpg',quality=96)
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];scores=[];records=[]
for tile in tiles:
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));domain=box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]);features=[f for f in D['features']if shape(f['geometry']).intersects(domain)];counts={c:sum(f['properties']['class']==c for f in features)for c in ['building_facade','road_marking','pedestrian_area','road_boundary']}
image=Image.open(S/name/'top.png').convert('RGB');overlay=draw_plan(image,lambda p:project(p,g),features)
overlay.save(O/(name+'.overlay.jpg'),quality=95);image.save(O/(name+'.source.jpg'),quality=95)
score=sum(v>0 for v in counts.values())*100+min(counts['building_facade'],10)*3+min(counts['road_marking'],20)
scores.append((score,name));records.append(dict(tile=name,counts=counts))
chosen=[]
for score,name in sorted(scores,reverse=True):
if any(abs(int(name.split('-')[1])-int(n.split('-')[1]))<2 for n in chosen):continue
chosen.append(name)
if len(chosen)==3:break
sheet=Image.new('RGB',(1800,950*len(chosen)),'white');draw=ImageDraw.Draw(sheet)
for row,name in enumerate(chosen):
for col,suffix in enumerate(['source','overlay']):
im=Image.open(O/(name+'.'+suffix+'.jpg')).resize((900,900),Image.Resampling.LANCZOS);sheet.paste(im,(900*col,950*row+50));draw.text((900*col+12,950*row+12),name+' · '+('Гауссы'if col==0 else'Все слои'),font=font,fill='#263640')
sheet.save(O/'details.jpg',quality=96)
(O/'visual-manifest.json').write_text(json.dumps(dict(review_only_selection='automatic class diversity with spatial separation',selected=chosen,all_tiles=records,manual_processing_rois=[]),indent=2));print('PICTURES',chosen,flush=True)
# Whole-scene before/after comparison and an exhaustive glyph evidence sheet.
old=json.loads(Path('/fullplan/full-map.json').read_text())
before=draw_plan(base,world,old['features']);before.thumbnail((2300,1500))
after=whole.copy();after.thumbnail((2300,1500))
rows=[title(before,os.environ['SCENE']+' · предыдущая сборка'),title(after,os.environ['SCENE']+' · уточнение')]
comparison=Image.new('RGB',(max(x.width for x in rows),sum(x.height for x in rows)+12),'white');y=0
for row in rows:comparison.paste(row,(0,y));y+=row.height+12
comparison.save(O/'comparison-full.jpg',quality=95)
search_views=SearchViews(tiles,None,None,None,None)
glyphs=[f for f in D['features']if f['properties'].get('subtype')not in [None,'linear_marking','crosswalk']]
if glyphs:
sheet=Image.new('RGB',(1600,270*int(np.ceil(len(glyphs)/4))),'white');d=ImageDraw.Draw(sheet)
for k,item in enumerate(glyphs):
prop=item['properties'];name=prop.get('source_tile')
if not name:continue
g=search_views.geometry(name);raw=Image.fromarray(search_views.inputs(name)[0]);factor=raw.width/1200
xy=shapely.get_coordinates(shape(item['geometry']));uv=project(xy,g)*factor;lo=uv.min(0)-25;hi=uv.max(0)+25;center=(lo+hi)/2;extent=max(hi-lo);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int))
overlay=draw_plan(raw,lambda p:project(p,g)*factor,[item],width=3)
for j,im in enumerate([raw,overlay]):sheet.paste(im.crop(bbox).resize((195,195),Image.Resampling.LANCZOS),((k%4)*400+j*200,(k//4)*270+65))
d.text(((k%4)*400+5,(k//4)*270+8),str(k+1)+' '+prop['subtype'],font=font,fill='#263640');d.text(((k%4)*400+5,(k//4)*270+34),name,font=font,fill='#263640')
sheet.save(O/'glyph-proof.jpg',quality=96)
# Inspect every admitted road interpolation, not a hand-picked success crop.
spans=[(f,s)for f in D['features']if f['properties']['class']=='road_boundary'for s in f['properties'].get('inferred_spans',[])]
if spans:
sheet=Image.new('RGB',(1800,645*len(spans)),'white');d=ImageDraw.Draw(sheet)
for k,(owner,span)in enumerate(spans):
coords=np.array(span['coordinates']);center=coords[:,:2].mean(0)
tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'))
raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
uv=project(coords,g)*factor;middle=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*8/60;extent=max(extent,raw.width*18/60)
bbox=tuple(np.r_[middle-extent/2,middle+extent/2].astype(int))
for col,(fs,label)in enumerate([(None,'Гауссы'),(old['features'],'До'),(D['features'],'После')]):
im=raw if fs is None else draw_plan(raw,lambda p:project(p,g)*factor,fs,width=max(2,int(factor*2)))
patch=im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS);sheet.paste(patch,(col*600,k*645+45));d.text((col*600+10,k*645+10),str(k+1)+' · '+label,font=font,fill='#263640')
sheet.save(O/'bridge-proof.jpg',quality=95)
for k in range(len(spans)):sheet.crop((0,k*645,1800,(k+1)*645)).save(O/('bridge-%02d.jpg'%(k+1)),quality=96)
@@ -0,0 +1,33 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from search_views import SearchViews
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'search-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('search-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('class')!='road_marking':continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
views=SearchViews(tiles,None,None,None,None);tiles=views.tiles
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='search-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('search-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'search-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
@@ -0,0 +1,7 @@
"""Full-image discovery; accepted paint thresholds are inherited unchanged."""
from discovery_rules import eligible_symbol,pack,unpack,uncovered,glyph_pass,glyph_context
from discovery_rules import POLICY as BASE_POLICY
VERSION='native-image-search-v1'
POLICY={**BASE_POLICY,'proposal_image_size':4096,'additional_gaussian_frames':True,
'proposal_semantics':'nearest-original-camera-by-geometry',
'min_uncovered_solid_section_m':2.7}
@@ -0,0 +1,42 @@
"""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']
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,28 @@
import runpy,json,numpy as np,cv2,shapely
from shapely.geometry import box
from search_views import warp_semantic
from search_rules import POLICY
from discovery_rules import POLICY as ORIGINAL
from line_reconstruction import extract
from corridor_profiles import missing_sections
prior=runpy.run_path('/candidate/test_corridor.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
checks['acceptance_thresholds_unchanged']=all(POLICY[k]==v for k,v in ORIGINAL.items()if k!='proposal_image_size')
field=np.zeros((64,64),np.float32);field[10:22,30:45]=1
corners=np.array([[0,0],[63,0],[63,63],[0,63]],float)
checks['semantic_identity_preserves_pixels']=np.array_equal(warp_semantic(field,corners,corners,64),field)
shifted=warp_semantic(field,corners,corners+[5,-3],64)
checks['semantic_camera_translation_correct']=np.all(shifted[7:19,35:50]==1)and shifted.sum()==field.sum()
for size in [512,1024]:
mpp=12/size;yy,xx=np.mgrid[:size,:size];on=(xx*mpp>2)&(xx*mpp<10)&(abs(yy*mpp-6)<.075)
rgb=np.repeat(np.where(on,220,65)[:,:,None],3,axis=2).astype('uint8')
records,_=extract(rgb,np.ones((size,size),bool),lambda p:np.asarray(p)*mpp,'synthetic',mpp)
checks['image_only_proposal_at_'+str(size)]=any(7.7<r['L']<8.2 and .08<r['W']<.2 for r in records)
empty,_=extract(rgb,np.zeros((size,size),bool),lambda p:np.asarray(p)*mpp,'synthetic',mpp)
checks['invalid_coverage_never_proposes_at_'+str(size)]=not empty
solid=box(0,-.06,20,.06);existing=box(0,-.08,8,.08)
sections=missing_sections(solid,existing)
checks['partially_present_solid_keeps_new_interval']=len(sections)==1 and sections[0].bounds[0]>8 and sections[0].bounds[2]==20
checks['present_paint_not_duplicated']=not missing_sections(solid,solid)
checks['empty_polygon_intersection_retains_new_solid']=len(missing_sections(solid,box(50,50,55,55)))==1
checks['empty_map_retains_new_solid']=len(missing_sections(solid,shapely.GeometryCollection()))==1
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/search-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed']