property-research/properties/willington-ct-049-002-00/evidence/zoning/th-22-4/build-harvest-trails.py
acamilo 7d814c3413 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.
2026-10-08 17:09:17 -04:00

87 lines
6.3 KiB
Python

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')