willington 049-002-00: georeference the TH-22-4 harvest trails and crossings as splines with lidar z
Thin-plate-spline fit of the forester's 2022 map to the parcel, trails traced and checked against the 2023 0.25 ft ortho and 2 ft lidar; crossings snapped to DEM-derived channels. GeoJSON in WGS84 and EPSG:6433, overlay images, method notes, and a payload/push script for the viewer's plan layer.
This commit is contained in:
parent
f847511001
commit
7d814c3413
10 changed files with 4685 additions and 0 deletions
|
|
@ -59,3 +59,11 @@ Town may have permitted it and is asking the Town; our FOIA draft asks the same.
|
|||
`th-22-4/IW-22-12-permit-print.pdf` and `.txt`.
|
||||
- Still outstanding from the Town: anything on the 1980s pond, building/zoning history, and the Fenton Bluffs
|
||||
subdivision file (FOIA draft to mdamato@willingtonct.gov).
|
||||
|
||||
## Trails and crossings as map geometry (2026-10-08)
|
||||
|
||||
The forester's proposed trails, the two poled stream crossings and the landing are georeferenced in
|
||||
`th-22-4/harvest-trails.geojson` (WGS84 + z) and `th-22-4/harvest-trails-6433.geojson` (viewer CRS); method and
|
||||
caveats in `th-22-4/harvest-trails.md`. Only the east haul road to the Fenton Bluffs cul-de-sac is visible in the
|
||||
2023 ortho; the rest is the drawing as fitted (10-30 m). Draft Property Explorer layer `th-22-4-harvest-trails`
|
||||
(id 3) is created and empty, waiting for an item API; `tools/pe_push_trails.py` holds the payload builder.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,87 @@
|
|||
import json, numpy as np
|
||||
from scipy.interpolate import RBFInterpolator
|
||||
from scipy.ndimage import map_coordinates
|
||||
from pyproj import Transformer
|
||||
from PIL import Image, ImageDraw
|
||||
Image.MAX_IMAGE_PIXELS=None
|
||||
P='/home/alex/property-research/properties/willington-ct-049-002-00/'
|
||||
OUT=P+'evidence/zoning/th-22-4/'
|
||||
FT=0.3048006096012192
|
||||
src=open('fit.py').read()
|
||||
cp=eval(src.split('cp=')[1].split('\nsrc=')[0])
|
||||
trails=eval(src.split('trails=')[1].split('\npoints=')[0])
|
||||
S=np.array([c[0] for c in cp],float); D=np.array([c[1] for c in cp],float)
|
||||
tps=RBFInterpolator(S,D,kernel='thin_plate_spline',smoothing=5.0)
|
||||
A=np.c_[S,np.ones(len(S))]; coef=np.linalg.lstsq(A,D,rcond=None)[0]; aff_res=np.hypot(*((A@coef)-D).T)
|
||||
T=lambda pts: tps(np.array(pts,float))
|
||||
# DEM (2 ft, ft NAVD88) and flow accumulation
|
||||
dem=np.array(Image.open('dem/dem-2ft.tif'),dtype=np.float64); acc=np.load('dem/acc.npy')
|
||||
ox,oy,res=1140746.0,903046.0,2.0
|
||||
def px(x,y): return ((x/FT-ox)/res,(oy-y/FT)/res)
|
||||
def zof(x,y):
|
||||
c,r=px(x,y); return float(map_coordinates(dem,[[r],[c]],order=1)[0])*FT
|
||||
def snap_channel(x,y,rad=30,min_ha=5.0):
|
||||
# nearest DEM cell within rad metres whose upslope area is at least min_ha
|
||||
c,r=px(x,y); R=int(rad/(res*FT))
|
||||
r0,r1,c0,c1=int(r)-R,int(r)+R+1,int(c)-R,int(c)+R+1
|
||||
sub=acc[r0:r1,c0:c1]; ok=sub*(res*FT)**2/10000>=min_ha
|
||||
rr,cc=np.where(ok); dd=np.hypot(rr-(r-r0),cc-(c-c0)); i=dd.argmin()
|
||||
rr,cc=rr[i],cc[i]
|
||||
return ((c0+cc+0.5)*res+ox)*FT,(oy-(r0+rr+0.5)*res)*FT,int(sub[rr,cc])
|
||||
def catmull(pts,step=5.0):
|
||||
pts=np.array(pts,float)
|
||||
if len(pts)<3: return pts
|
||||
p=np.vstack([pts[0],pts,pts[-1]]); out=[]
|
||||
for i in range(1,len(p)-2):
|
||||
p0,p1,p2,p3=p[i-1],p[i],p[i+1],p[i+2]; n=max(2,int(np.hypot(*(p2-p1))/step))
|
||||
for t in np.linspace(0,1,n,endpoint=False):
|
||||
out.append(0.5*((2*p1)+(-p0+p2)*t+(2*p0-5*p1+4*p2-p3)*t*t+(-p0+3*p1-3*p2+p3)*t**3))
|
||||
out.append(p[-2]); return np.array(out)
|
||||
# --- geometry in EPSG:6433 ---
|
||||
sc1=snap_channel(348378,274758); sc2=snap_channel(348135,274392); landing=(348430.0,274748.0)
|
||||
Jd=T([trails['A-west-spine'][-1]])[0] # forester's junction (spine / east trail / centre trail)
|
||||
feat={}
|
||||
feat['A-west-spine']=(T(trails['A-west-spine']),'forester map (TPS fit); not visible in the 2023 ortho or lidar')
|
||||
feat['A-east-haul-road']=(np.array([tuple(Jd),(348215,274728),(348235,274757),(348300,274759),(348340,274760),(sc1[0],sc1[1]),(348400,274752),landing]),'forester map; from the junction it is routed onto the pale corridor visible in the 2023 spring ortho (348100-348330 E at about 274758 N); SC-1 snapped to the DEM channel')
|
||||
feat['corridor-west-stub']=(np.array([(348100,274752),(348150,274755),(348200,274758),(348235,274757)]),'pale corridor visible in the 2023 ortho west of the forester junction; not on the forester map; likely the real skid-road alignment or an older woods road')
|
||||
B=T(trails['B-centre'])
|
||||
feat['B-centre']=(np.vstack([[Jd],B[1:8],[(sc2[0],sc2[1])],B[10:]]),'forester map (TPS fit); SC-2 vertex snapped to the DEM channel below the pond outlet')
|
||||
feat['C-south']=(T(trails['C-south']),'forester map (TPS fit), not visible in 2023 ortho or lidar')
|
||||
pts={'SC-1':((sc1[0],sc1[1]),f'poled stream crossing; forester map, snapped to DEM channel (upslope {sc1[2]*(res*FT)**2/10000:.1f} ha)'),
|
||||
'SC-2':((sc2[0],sc2[1]),f'poled stream crossing; forester map, snapped to DEM channel (upslope {sc2[2]*(res*FT)**2/10000:.1f} ha)'),
|
||||
'Landing':(landing,'log landing at the Fenton Bluffs Drive cul-de-sac (forester map; cul-de-sac from ortho)')}
|
||||
to84=Transformer.from_crs('EPSG:6433','EPSG:4326',always_xy=True)
|
||||
def fc(wgs):
|
||||
F=[]
|
||||
for k,(xy,basis) in feat.items():
|
||||
sm=catmull(xy,5.0); coords=[]
|
||||
for x,y in sm:
|
||||
z=zof(x,y);
|
||||
if wgs: lon,lat=to84.transform(x,y); coords.append([round(lon,7),round(lat,7),round(z,2)])
|
||||
else: coords.append([round(x,2),round(y,2),round(z,2)])
|
||||
L=float(np.sum(np.hypot(*np.diff(sm,axis=0).T)))
|
||||
F.append({'type':'Feature','id':f'trail:{k}','geometry':{'type':'LineString','coordinates':coords},
|
||||
'properties':{'kind':'skid-trail','label':k,'source':'TH-22-4 forest map, John Clarke 9/2022 (Proposed Trail)','basis':basis,'length_m':round(L,1),'control_vertices':[[round(float(a),1),round(float(b),1)] for a,b in xy],'spline':'catmull-rom through control_vertices, 5 m samples, z = CT 2023 lidar DEM (2 ft) NAVD88 m'}})
|
||||
for k,(xy,basis) in pts.items():
|
||||
x,y=xy; z=zof(x,y)
|
||||
c=[round(v,7) for v in to84.transform(x,y)]+[round(z,2)] if wgs else [round(x,2),round(y,2),round(z,2)]
|
||||
F.append({'type':'Feature','id':f'point:{k}','geometry':{'type':'Point','coordinates':c},
|
||||
'properties':{'kind':'stream-crossing' if k.startswith('SC') else 'landing','label':k,'source':'TH-22-4 forest map, John Clarke 9/2022','basis':basis}})
|
||||
return {'type':'FeatureCollection','name':'TH-22-4 harvest trails and crossings','crs_note':'EPSG:4326 lon,lat,z(m NAVD88)' if wgs else 'EPSG:6433 NAD83(2011) CT state plane metres x,y,z(m NAVD88)',
|
||||
'georeference':{'method':'thin-plate spline from 17 drawn parcel corners to GIS parcel vertices (boundary.geojson)','affine_check_residual_m':{'mean':round(float(aff_res.mean()),1),'max':round(float(aff_res.max()),1)},'map_scale_m_per_px':round(float(np.hypot(coef[0,0],coef[1,0])),3),'control_points_px_to_6433':[[list(a),list(b)] for a,b in cp]},
|
||||
'features':F}
|
||||
json.dump(fc(True),open(OUT+'harvest-trails.geojson','w'),indent=1)
|
||||
json.dump(fc(False),open(OUT+'harvest-trails-6433.geojson','w'),indent=1)
|
||||
# summary
|
||||
for k,(xy,_) in feat.items():
|
||||
sm=catmull(xy); zs=[zof(x,y) for x,y in sm]; print(k,'len %.0f m'%np.sum(np.hypot(*np.diff(sm,axis=0).T)),'z %.0f-%.0f m'%(min(zs),max(zs)))
|
||||
for k,(xy,b) in pts.items(): print(k,[round(v,1) for v in xy],'z %.1f'%zof(*xy),b)
|
||||
# final overlay on the ortho overview (2 ft/px)
|
||||
im=Image.open('ov-plain.png').convert('RGB'); d=ImageDraw.Draw(im)
|
||||
oxo,oyo,ro=1140746,903046,2.0
|
||||
tp=lambda x,y: ((x/FT-oxo)/ro,(oyo-y/FT)/ro)
|
||||
a=np.array(im); H,W=a.shape[:2]; a[acc[:H,:W]>26909]=(0,255,255); im=Image.fromarray(a); d=ImageDraw.Draw(im)
|
||||
for k,(xy,_) in feat.items(): d.line([tp(x,y) for x,y in catmull(xy)],fill=(255,40,40),width=3)
|
||||
for k,(xy,_) in pts.items():
|
||||
cx,cy=tp(*xy); d.ellipse([cx-7,cy-7,cx+7,cy+7],outline=(0,255,0),width=3); d.text((cx+9,cy-7),k,fill=(0,255,0))
|
||||
im.save(OUT+'harvest-trails-overlay-2023-ortho.png'); print('written')
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 809 KiB |
|
|
@ -0,0 +1,56 @@
|
|||
import json, numpy as np
|
||||
from scipy.interpolate import RBFInterpolator
|
||||
from PIL import Image, ImageDraw
|
||||
P='/home/alex/property-research/properties/willington-ct-049-002-00/'
|
||||
FT=0.3048006096012192 # US survey foot
|
||||
# control points: forester map pixel (2200x1700 north-up) -> EPSG:6433 metres (GIS boundary vertex)
|
||||
cp=[((675,93),(347910.2,275144.1)),((890,113),(348028.5,275129.5)),((953,27),(348062.5,275195.8)),
|
||||
((899,177),(348035.4,275078.9)),((1067,193),(348130.5,275068.8)),((1117,220),(348161.5,275046.9)),
|
||||
((1100,400),(348148.3,274913.2)),((1500,437),(348374.1,274888.4)),((607,503),(347873.8,274832.1)),
|
||||
((803,557),(347985.1,274795.7)),((760,777),(347961.5,274636.1)),((340,1173),(347723.2,274330.7)),
|
||||
((1373,1360),(348304.7,274193.7)),((1410,987),(348334.8,274445.3)),((1473,987),(348358.2,274471.4)),
|
||||
((1557,847),(348418.0,274577.0)),((1640,625),(348490.4,274717.8))]
|
||||
src=np.array([c[0] for c in cp],float); dst=np.array([c[1] for c in cp],float)
|
||||
# affine for diagnostics
|
||||
A=np.c_[src,np.ones(len(src))]; coef,res,_,_=np.linalg.lstsq(A,dst,rcond=None)
|
||||
aff=A@coef; r=np.hypot(*(aff-dst).T); print('affine residual m: mean %.1f max %.1f'%(r.mean(),r.max()))
|
||||
print('scale m/px', np.hypot(coef[0,0],coef[1,0]), 'rot deg', np.degrees(np.arctan2(coef[1,0],coef[0,0])))
|
||||
tps=RBFInterpolator(src,dst,kernel='thin_plate_spline',smoothing=5.0)
|
||||
r2=np.hypot(*(tps(src)-dst).T); print('tps residual m: mean %.1f max %.1f'%(r2.mean(),r2.max()))
|
||||
trails={
|
||||
'A-west-spine':[(747,247),(767,280),(793,333),(813,373),(833,433),(847,480),(863,527),(873,567),(900,620),(940,667),(973,693),(1007,700),(1060,700),(1100,693),(1147,690),(1187,693)],
|
||||
'A-east-to-landing':[(1187,693),(1213,683),(1260,667),(1313,660),(1367,667),(1407,680),(1447,673),(1480,670),(1500,658),(1530,615),(1563,580)],
|
||||
'B-centre':[(1187,693),(1180,733),(1177,787),(1167,847),(1153,887),(1140,933),(1127,1000),(1120,1053),(1107,1095),(1095,1105),(1060,1150),(1040,1185)],
|
||||
'C-south':[(633,1120),(680,1130),(720,1143),(760,1150),(800,1153),(853,1157),(907,1157),(953,1167),(1007,1177),(1040,1185),(1067,1185),(1100,1200),(1153,1203),(1200,1213),(1253,1220),(1280,1227)],
|
||||
}
|
||||
points={'SC-1':(1500,658),'SC-2':(1095,1105),'Landing':(1563,580)}
|
||||
out={'trails':{k:tps(np.array(v,float)).round(1).tolist() for k,v in trails.items()},
|
||||
'points':{k:tps(np.array([v],float))[0].round(1).tolist() for k,v in points.items()}}
|
||||
json.dump(out,open('fit.json','w'),indent=1)
|
||||
# overlay on hillshade (EPSG:6434 ft, 2 ft/px, origin 1140656,903040)
|
||||
hs=Image.open(P+'terrain/hillshade-2023.jpg').convert('RGB')
|
||||
def px(x,y): return ((x/FT-1140656)/2.0, (903040-y/FT)/2.0)
|
||||
ring=json.load(open(P+'terrain/terrain-features.geojson'))
|
||||
from pyproj import Transformer
|
||||
tr=Transformer.from_crs('EPSG:4326','EPSG:6433',always_xy=True)
|
||||
b=json.load(open(P+'boundary.geojson'))['features'][0]['geometry']['coordinates'][0]
|
||||
bp=[px(*tr.transform(x,y)) for x,y in b]
|
||||
Z=2; big=hs.resize((hs.width*Z,hs.height*Z),Image.LANCZOS); d=ImageDraw.Draw(big)
|
||||
d.line([(x*Z,y*Z) for x,y in bp]+[(bp[0][0]*Z,bp[0][1]*Z)],fill=(255,255,0),width=2)
|
||||
for k,v in out['trails'].items():
|
||||
d.line([(px(x,y)[0]*Z,px(x,y)[1]*Z) for x,y in v],fill=(255,0,0),width=2)
|
||||
for k,(x,y) in out['points'].items():
|
||||
cx,cy=px(x,y); d.ellipse([cx*Z-6,cy*Z-6,cx*Z+6,cy*Z+6],outline=(0,255,0),width=2); d.text((cx*Z+8,cy*Z-6),k,fill=(0,255,0))
|
||||
# 100 m grid in 6433
|
||||
for gx in range(347700,348600,100):
|
||||
x0,_=px(gx,274000); d.line([(x0*Z,0),(x0*Z,big.height)],fill=(0,200,255),width=1); d.text((x0*Z+2,2),str(gx),fill=(0,200,255))
|
||||
for gy in range(274100,275300,100):
|
||||
_,y0=px(347000,gy); d.line([(0,y0*Z),(big.width,y0*Z)],fill=(0,200,255),width=1); d.text((2,y0*Z+2),str(gy),fill=(0,200,255))
|
||||
big.save('hs-overlay.png')
|
||||
# crops: parcel bbox in px
|
||||
xs=[p[0] for p in bp]; ys=[p[1] for p in bp]
|
||||
x0,x1,y0,y1=int(min(xs))-20,int(max(xs))+20,int(min(ys))-20,int(max(ys))+20
|
||||
print('parcel px box',x0,x1,y0,y1)
|
||||
cw=(x1-x0)//2; ch=(y1-y0)//2
|
||||
for name,(cx,cy) in {'nw':(x0,y0),'ne':(x0+cw,y0),'sw':(x0,y0+ch),'se':(x0+cw,y0+ch)}.items():
|
||||
big.crop((cx*Z,cy*Z,(cx+cw+40)*Z,(cy+ch+40)*Z)).save(f'hs-{name}.png')
|
||||
File diff suppressed because it is too large
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 517 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 925 KiB |
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,50 @@
|
|||
# TH-22-4 harvest trails and stream crossings as map geometry
|
||||
|
||||
Built 2026-10-08 from the forester's hand-drawn map (`forest-map-north-up.png`, John Clarke 9/2022, 1" = 375')
|
||||
so the proposed skid trails, the two poled stream crossings and the landing can be pushed into the Property
|
||||
Explorer viewer as draped lines and points once an item-writing interface exists (the MCP only creates empty
|
||||
layers today; an empty draft layer "TH-22-4 harvest trails" has been created to receive them).
|
||||
|
||||
Files
|
||||
- `harvest-trails.geojson` — WGS84 lon/lat with z (m NAVD88) on every vertex. Lines are Catmull-Rom splines
|
||||
through the digitised control vertices, sampled every 5 m; z is bilinear from the CT 2023 lidar DEM at 2 ft.
|
||||
- `harvest-trails-6433.geojson` — the same in EPSG:6433 (NAD83(2011) CT state plane, metres), the viewer's CRS.
|
||||
Each line feature keeps its `control_vertices` so the spline can be rebuilt or edited.
|
||||
- `harvest-trails-overlay-2023-ortho.jpg` — the result over the 2023 leaf-off ortho (2 ft/px) with the
|
||||
lidar-derived channels (cyan, upslope area over 1 ha) and the parcel.
|
||||
- `harvest-trails-corridor-2023-ortho-0.5ft.jpg` — the haul-road corridor at 6 in/px.
|
||||
- `dem-channels-2023-lidar.jpg` — the D8 flow-accumulation channels used to snap the crossings.
|
||||
- `fit-forest-map.py`, `build-harvest-trails.py` — the scripts (run from the scratchpad; they expect the CT ECO
|
||||
exports listed below next to them).
|
||||
|
||||
Method
|
||||
1. Georeference: 17 parcel corners read off the drawing (pixels of the 2200x1700 north-up scan) were matched to
|
||||
GIS parcel vertices (`boundary.geojson`). A plain affine fits with mean 8.4 m / max 32 m residual
|
||||
(scale 0.574 m/px, rotation 0.4 deg); the drawing is hand-sketched and locally compressed, so a thin-plate
|
||||
spline through the same points was used to warp the trails.
|
||||
2. Digitise: the "Proposed Trail" dashes were traced as four lines: `A-west-spine` (NW corner to the central
|
||||
junction), `A-east-haul-road` (junction to SC-1 and the landing), `B-centre` (junction south across SC-2 to
|
||||
the south trail) and `C-south` (east-west below the pond). Label leaders and stand-type lines were ignored.
|
||||
3. Check against imagery: CT ECO 2023 leaf-off ortho at 0.25 ft native (exported at 1 ft and 0.5 ft) and the
|
||||
2023 lidar hillshade. Only one feature is visible: a pale corridor running east along about 274758 N from
|
||||
348100 E to the brook at 348378 E, continuing to the Fenton Bluffs cul-de-sac. The forester's east trail
|
||||
was moved onto it; the part west of his junction is kept as a separate `corridor-west-stub`. No other
|
||||
trail is visible, so the spine, the centre trail and the south trail are the drawing as fitted
|
||||
(expect 10-30 m error). The flight date of the ortho relative to the Nov 2022-Feb 2023 cutting window is
|
||||
not known; the woods show no obvious fresh landings or slash, so it may predate the job.
|
||||
4. Stream crossings: the USGS NHD has neither brook. Channels were derived from the 2 ft DEM (pysheds D8).
|
||||
SC-1 was snapped to the eastern brook (20 ha upslope) where the corridor crosses it, at
|
||||
348378 E 274758 N, elevation 220 m; SC-2 to the pond-outlet brook (11 ha) at 348133 E 274390 N, 258 m.
|
||||
The landing is placed inside the parcel at the cul-de-sac, 348430 E 274748 N.
|
||||
|
||||
Lengths: spine 493 m, east haul road 287 m, corridor stub 135 m, centre 428 m, south 384 m
|
||||
(about 1.7 km of trail; the spine climbs from 249 to 284 m).
|
||||
|
||||
Inputs not kept in the repo (re-export from CT ECO ImageServer if needed)
|
||||
- Ortho_2023_CTspNAD83_2011 exportImage, bbox 1140746,899437,1143370,903046 (EPSG:6434 ft), 2624x3609 (1 ft)
|
||||
and two 5248x3610 halves (0.5 ft).
|
||||
- Statewide2023_CTspNAD83_2011 (DEM) exportImage, same bbox, 1312x1805 F32 tiff (2 ft).
|
||||
|
||||
Push format (pending the viewer's item API): one item per feature, geometry in EPSG:6433 metres,
|
||||
`kind` = skid-trail | stream-crossing | landing, `label`, `basis`, draped on the terrain (z is supplied but the
|
||||
viewer's own DEM should win). See `tools/pe_push_trails.py`.
|
||||
92
tools/pe_push_trails.py
Executable file
92
tools/pe_push_trails.py
Executable file
|
|
@ -0,0 +1,92 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Push a trails GeoJSON (EPSG:6433 metres, x y z) into a Property Explorer plan layer.
|
||||
|
||||
The viewer's MCP server has no item-writing tool yet (only layer_create / orchard_layout), so this script
|
||||
prepares the exact item payloads and sends them through whatever interface becomes available:
|
||||
|
||||
--dry-run print the items that would be sent (default when no transport is given)
|
||||
--mcp URL --tool T call MCP tool T on the streamable-HTTP endpoint (e.g. http://host:8080/mcp) once per item,
|
||||
with arguments {"property", "layer", "item"}; adjust map_item() if the tool's schema differs
|
||||
--http URL POST the whole item list as JSON to URL (a REST endpoint, if one appears)
|
||||
|
||||
Nothing here embeds credentials: pass a bearer token through the PE_TOKEN environment variable if required.
|
||||
|
||||
Example:
|
||||
tools/pe_push_trails.py properties/willington-ct-049-002-00/evidence/zoning/th-22-4/harvest-trails-6433.geojson \
|
||||
--property willington-ct-049-002-00 --layer th-22-4-harvest-trails --dry-run
|
||||
"""
|
||||
import argparse, json, os, sys, urllib.request
|
||||
|
||||
|
||||
def map_item(feature):
|
||||
"""GeoJSON feature -> plan-layer item. Keep geometry in EPSG:6433 metres; z is advisory (viewer drapes)."""
|
||||
p = feature["properties"]
|
||||
g = feature["geometry"]
|
||||
item = {
|
||||
"id": feature.get("id"),
|
||||
"kind": p.get("kind"), # skid-trail | stream-crossing | landing
|
||||
"label": p.get("label"),
|
||||
"geometry": {"type": g["type"], "coordinates": g["coordinates"], "crs": "EPSG:6433"},
|
||||
"drape": True,
|
||||
"style": {"skid-trail": {"stroke": "#d33", "width": 3, "dash": [8, 6]},
|
||||
"stream-crossing": {"marker": "circle", "fill": "#0c0"},
|
||||
"landing": {"marker": "square", "fill": "#fa0"}}.get(p.get("kind"), {}),
|
||||
"note": p.get("basis"),
|
||||
"source": p.get("source"),
|
||||
}
|
||||
if "control_vertices" in p:
|
||||
item["spline"] = {"type": "catmull-rom", "control_vertices": p["control_vertices"], "sample_m": 5}
|
||||
return item
|
||||
|
||||
|
||||
def mcp_call(url, tool, arguments, token=None):
|
||||
hdr = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
|
||||
if token:
|
||||
hdr["Authorization"] = f"Bearer {token}"
|
||||
init = {"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
||||
"params": {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "pe-push-trails", "version": "0"}}}
|
||||
req = urllib.request.Request(url, data=json.dumps(init).encode(), headers=hdr)
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
sid = r.headers.get("mcp-session-id")
|
||||
hdr2 = dict(hdr, **({"Mcp-Session-Id": sid} if sid else {}))
|
||||
call = {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": tool, "arguments": arguments}}
|
||||
req = urllib.request.Request(url, data=json.dumps(call).encode(), headers=hdr2)
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
return r.read().decode()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("geojson")
|
||||
ap.add_argument("--property", required=True)
|
||||
ap.add_argument("--layer", required=True, help="plan layer slug (create it first with layer_create)")
|
||||
ap.add_argument("--mcp", help="MCP streamable-HTTP endpoint")
|
||||
ap.add_argument("--tool", help="MCP tool name that adds one item to a layer")
|
||||
ap.add_argument("--http", help="REST endpoint that accepts {property, layer, items}")
|
||||
ap.add_argument("--dry-run", action="store_true")
|
||||
a = ap.parse_args()
|
||||
|
||||
fc = json.load(open(a.geojson))
|
||||
if "6433" not in fc.get("crs_note", "") and "6433" not in a.geojson:
|
||||
sys.exit("expected the EPSG:6433 file (harvest-trails-6433.geojson)")
|
||||
items = [map_item(f) for f in fc["features"]]
|
||||
token = os.environ.get("PE_TOKEN")
|
||||
|
||||
if a.dry_run or not (a.mcp or a.http):
|
||||
print(json.dumps({"property": a.property, "layer": a.layer, "items": items}, indent=1)[:4000])
|
||||
print(f"... {len(items)} items, {sum(len(i['geometry']['coordinates']) for i in items if i['geometry']['type']=='LineString')} line vertices")
|
||||
return
|
||||
if a.http:
|
||||
req = urllib.request.Request(a.http, data=json.dumps({"property": a.property, "layer": a.layer, "items": items}).encode(),
|
||||
headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {token}"} if token else {})})
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
print(r.status, r.read().decode()[:2000])
|
||||
return
|
||||
if not a.tool:
|
||||
sys.exit("--mcp needs --tool")
|
||||
for it in items:
|
||||
print(it["id"], mcp_call(a.mcp, a.tool, {"property": a.property, "layer": a.layer, "item": it}, token)[:300])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Add table
Reference in a new issue