news 2026/9/10 17:18:00

GeoMaster 地理空间技能代码示例全解析:100 个 Python / R / Julia / JavaScript 实战模板速查

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
GeoMaster 地理空间技能代码示例全解析:100 个 Python / R / Julia / JavaScript 实战模板速查

GeoMaster 地理空间技能代码示例全解析:100 个 Python / R / Julia / JavaScript 实战模板速查

【免费下载链接】scientific-agent-skillsTurn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 190,000+ scientists worldwide. 165 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.项目地址: https://gitcode.com/GitHub_Trending/cl/scientific-agent-skills

本指南以 scientific-agent-skills 仓库中 code-examples.md 为主体,完整收录并详解 GeoMaster 地理空间技能沉淀的 100 个代码示例,覆盖矢量/栅格核心操作、多语言(Python、R、Julia、JavaScript)实现、遥感(Sentinel-2、Landsat、SAR)、空间机器学习、网络分析、地形水文分析与完整端到端工作流。读者阅读后可直接按分类复制运行,快速搭建从数据读取、处理、分析到可视化与机器学习分类的完整地理空间处理管线,并理解每个 API 背后的坐标系统与性能最佳实践。

背景:GeoMaster 与示例库的定位

GeoMaster 是一个面向 GIS、遥感、空间分析与地学机器学习的综合技能(Skill),主文档 SKILL.md 声明其覆盖 70+ 主题,并提供 8 种编程语言(Python、R、Julia、JavaScript、C++、Java、Go、Rust)的 500+ 代码示例。README.md 进一步将其组织为 70+ 章节、300+ 地理空间库与工具,横跨遥感、GIS、空间统计与地球观测 ML/AI 四大领域。

本文解析的 code-examples.md 正是这套示例体系的核心清单:按"分类 × 语言"编排,从最基础的矢量/栅格读写到完整的土地覆盖分类、洪水制图、地形分析工作流,再到空间统计、插值、水文提取等高级主题。它同时与仓库内其他参考文档相互呼应:

  • 坐标系统理论见 coordinate-systems.md;
  • 底层库原理见 core-libraries.md;
  • 遥感处理专篇见 remote-sensing.md;
  • 空间机器学习见 machine-learning.md;
  • 多语言生态见 programming-languages.md。

运行环境准备

在运行下述示例前,先按 SKILL.md 的安装指引搭好环境。核心 Python 栈建议使用 conda-forge 安装(GDAL 等二进制依赖在 conda 下最稳妥):

# Core Python stack(conda 推荐) conda install -c conda-forge gdal rasterio fiona shapely pyproj geopandas # 遥感与 ML uv pip install rsgislib torchgeo earthengine-api uv pip install scikit-learn xgboost torch-geometric # 网络与可视化 uv pip install osmnx networkx folium keplergl uv pip install cartopy contextily mapclassify # 大数据与云原生 uv pip install xarray rioxarray dask-geopandas uv pip install pystac-client planetary-computer # 点云 uv pip install laspy pylas open3d pdal # 空间数据库 conda install -c conda-forge postgis spatialite

示例中还会用到rtreerasterstatsgeopyscipysklearnpykrigeskgstatesdalibpysalrichdemmercantilePillow等,可按需pip install所有与面积、距离、缓冲区相关的运算都必须先转到投影坐标系(如 UTM),这是示例反复强调的核心约束。


一、Python 核心操作:矢量数据

GeoPandas 是矢量数据的主力接口,底层封装 Fiona(I/O)与 Shapely(几何运算)。以下 10 个操作构成日常 GIS 处理的原子能力。

1-3. 读取三种主流矢量格式

import geopandas as gpd # 1. Read GeoJSON gdf = gpd.read_file('data.geojson') # 2. Read Shapefile(中文属性建议显式指定编码) gdf = gpd.read_file('data.shp') # 3. Read GeoPackage(可指定图层) gdf = gpd.read_file('data.gpkg', layer='layer_name')

读取后第一件事是检查gdf.crs。如为None,需用gdf.set_crs("EPSG:4326")手动指定;多数据源叠加前务必保证 CRS 一致,coordinate-systems.md 给出了ensure_same_crs辅助函数作为规范写法。

4-5. 重投影与缓冲区

# 4. Reproject(EPSG:32633 为 UTM Zone 33N,米制) gdf_utm = gdf.to_crs('EPSG:32633') # 5. Buffer(必须在投影坐标系下执行,单位是米) gdf['buffer_1km'] = gdf.geometry.buffer(1000)

关键约束:在 EPSG:4326(经纬度)下直接buffer(1000)表示 1000 度,结果完全错误。规范做法是先gdf.to_crs(gdf.estimate_utm_crs())再缓冲。estimate_utm_crs()会根据数据范围自动推断最合适的 UTM 分区(参见 coordinate-systems.md 的自动检测章节)。

6. 空间连接(Spatial Join)

# 6. Spatial join(how 决定保留哪些记录,predicate 决定空间关系) joined = gpd.sjoin(points, polygons, how='inner', predicate='within')

predicate可选'intersects''within''contains''touches''crosses''overlaps'等;how='inner'只保留空间上匹配到的记录,how='left'保留左侧全部。GeoPandas 会自动使用空间索引加速匹配(SKILL.md 性能提示称可带来 10-100 倍查询加速)。

7-8. 融合与裁剪

# 7. Dissolve(按属性字段聚合几何) dissolved = gdf.dissolve(by='category') # 8. Clip(用 mask 多边形裁剪矢量) clipped = gpd.clip(gdf, mask)

dissolve支持aggfunc参数对属性做聚合统计(如aggfunc='sum');gpd.clip是 0.7+ 版本提供的顶层便捷函数,等价于逐要素相交后合并。

9-10. 面积与长度计算

# 9. Calculate area(投影坐标系下单位为平方米) gdf['area_km2'] = gdf.geometry.area / 1e6 # 10. Calculate length(米 → 千米) gdf['length_km'] = gdf.geometry.length / 1000

geometry.area/geometry.length返回的结果单位取决于当前 CRS。在 EPSG:4326 下会得到"平方度/度",因此这两行代码同样必须在投影后执行。完整的正确写法见 coordinate-systems.md 的"面积单位陷阱"一节。


二、栅格数据处理(Rasterio)

Rasterio 提供对 GDAL 更友好的 Python 接口,负责 GeoTIFF 等栅格格式的读写。以下 7 个示例覆盖栅格全生命周期。

11-13. 读取栅格、单波段与窗口读取

import rasterio # 11. Read raster(返回所有波段、元数据与 CRS) with rasterio.open('raster.tif') as src: data = src.read() profile = src.profile crs = src.crs # 12. Read single band with rasterio.open('raster.tif') as src: band1 = src.read(1) # band 从 1 开始计数 # 13. Read with window(大文件按窗口局部读取,内存友好) with rasterio.open('large.tif') as src: window = ((0, 1000), (0, 1000)) # ((row_start, row_stop), (col_start, col_stop)) subset = src.read(1, window=window)

窗口读取是处理超大影像的核心手段。SKILL.md 性能章节还提供了基于src.block_windows(1)的分块遍历模式,配合gdal.SetCacheMax(2**30)可显著提升大栅格处理效率。

14-15. 写入栅格与 NDVI 计算

# 14. Write raster(复用源 profile 保证元数据一致) with rasterio.open('output.tif', 'w', **profile) as dst: dst.write(data) # 15. Calculate NDVI(Sentinel-2:band4=Red, band8=NIR) red = src.read(4) nir = src.read(8) ndvi = (nir - red) / (nir + red + 1e-8) # 1e-8 防止除零

NDVI 公式即归一化植被指数,1e-8 的 epsilon 用于避免分母为零。更完整的写法可参考 SKILL.md 的 Quick Start:src.read(4).astype(float)并配合profile.update(count=1, dtype=rasterio.float32)后写出,同时处理 NaN。索引族(NDVI/EVI/SAVI/NDWI/NBR/NDBI)的批量计算实现见 remote-sensing.md。

16-17. 多边形掩膜与栅格重投影

# 16. Mask raster with polygon(crop=True 裁剪到要素范围) from rasterio.mask import mask masked, transform = mask(src, [polygon.geometry], crop=True) # 17. Reproject raster(自动计算目标变换与尺寸) from rasterio.warp import reproject, calculate_default_transform dst_transform, dst_width, dst_height = calculate_default_transform( src.crs, 'EPSG:32633', src.width, src.height, *src.bounds)

掩膜常用于按研究区 AOI 裁剪影像;calculate_default_transform根据源 CRS、目标 CRS 与边界自动推导输出仿射变换和尺寸,是栅格重投影的标准第一步。


三、可视化:从静态到交互

18-20. GeoPandas 静态制图与 Folium 交互

# 18. Static plot with GeoPandas(column 指定着色字段) gdf.plot(column='value', cmap='YlOrRd', legend=True, figsize=(12, 8)) # 19. Interactive map with Folium import folium m = folium.Map(location=[37.7, -122.4], zoom_start=12) folium.GeoJson(gdf).add_to(m) # 20. Choropleth(分级设色图,stats 为属性 DataFrame) folium.Choropleth(gdf, data=stats, columns=['id', 'value'], key_on='feature.properties.id').add_to(m)

key_on用于将外部统计表stats的字段与 GeoJSON 要素的properties.id关联,是 Choropleth 正确配色的关键。

21-25. 标记、底图与多维可视化

# 21. Add markers(逐行添加点标记) for _, row in points.iterrows(): folium.Marker([row.lat, row.lon]).add_to(m) # 22. Map with Contextily(叠加在线底图,需传入 crs) import contextily as ctx ax = gdf.plot(alpha=0.5) ctx.add_basemap(ax, crs=gdf.crs) # 23. Multi-layer map(多层叠加到同一坐标轴) import matplotlib.pyplot as plt fig, ax = plt.subplots() gdf1.plot(ax=ax, color='blue') gdf2.plot(ax=ax, color='red') # 24. 3D plot with PyDeck import pydeck as pdk pdk.Deck(layers=[pdk.Layer('ScatterplotLayer', data=df)], map_style='mapbox://styles/mapbox/dark-v9') # 25. Time series map with hvplot(支持 OSM 瓦片底图) import hvplot.geopandas gdf.hvplot(c='value', geo=True, tiles='OSM', frame_width=600)

示例 22 中crs=gdf.crs必须与底图坐标系一致(通常为 EPSG:3857,add_basemap会自动处理重投影)。示例 25 的hvplot可直接对带时间维的 GeoDataFrame 生成滑动条动画地图。


四、R 语言示例(sf 包)

R 侧的地理空间生态以sf(Simple Features)为核心。programming-languages.md 还展示了terra栅格包、ggplot2绘图与完整的 R 土地覆盖分类工作流(randomForest+caret)。以下 10 个示例与 Python 侧一一对应。

# 26. Load sf package library(sf) # 27. Read shapefile roads <- st_read("roads.shp") # 28. Read GeoJSON zones <- st_read("zones.geojson") # 29. Check CRS st_crs(roads) # 30. Reproject(32610 = UTM Zone 10N,米制) roads_utm <- st_transform(roads, 32610) # 31. Buffer(dist 单位为 CRS 单位,投影后为米) roads_buffer <- st_buffer(roads, dist = 100) # 32. Spatial join(默认 st_intersects 谓词) joined <- st_join(roads, zones, join = st_intersects) # 33. Calculate area(返回单位对象,可 /1e6 转平方千米) zones$area <- st_area(zones) # 34. Dissolve(按几何合并) dissolved <- st_union(zones) # 35. Plot plot(zones$geometry)

st_area在 R 中返回带单位的units对象(自动感知 CRS 单位),这是与 GeoPandas 的区别之一;st_transform(roads, 32610)的第二个参数可传 EPSG 数字或完整 WKT/Proj4 字符串。


五、Julia 语言示例(ArchGDAL / GeoInterface)

Julia 侧通过ArchGDAL直接绑定 GDAL,GeoInterface提供跨库统一的几何抽象(programming-languages.md 中还包含GeoStats.jl的地统计插值、克里金与模拟示例)。

# 36. Load ArchGDAL using ArchGDAL # 37. Read shapefile(do-block 自动管理资源) data = ArchGDAL.read("countries.shp") do dataset layer = dataset[1] features = [] for feature in layer push!(features, ArchGDAL.getgeom(feature)) end features end # 38. Create point using GeoInterface point = GeoInterface.Point(-122.4, 37.7) # 39. Buffer buffered = GeoInterface.buffer(point, 1000) # 40. Intersection intersection = GeoInterface.intersection(poly1, poly2)

ArchGDAL.read(f) do dataset ... end是 Julia 的资源管理惯用法,确保数据集在使用后自动关闭。GeoInterface 让同一套几何操作代码在不同几何后端(ArchGDAL、GeoJSON.jl 等)间复用。


六、JavaScript 示例(Turf.js)

Turf.js 是浏览器与 Node.js 通用的空间分析库,适合 Web 端轻量分析。programming-languages.md 还补充了 Leaflet 的 Web 地图加载、GeoJSON 图层、弹窗与圆形标记示例。以下 10 个示例覆盖常见空间操作。

// 41. Turf.js point const pt1 = turf.point([-122.4, 37.7]); // 42. Distance(默认公里,可选 miles/kilometers/degrees) const distance = turf.distance(pt1, pt2, {units: 'kilometers'}); // 43. Buffer const buffered = turf.buffer(pt1, 5, {units: 'kilometers'}); // 44. Within(点落在多边形内的集合) const ptsWithin = turf.pointsWithinPolygon(points, polygon); // 45. Bounding box const bbox = turf.bbox(feature); // 46. Area(返回平方米) const area = turf.area(polygon); // square meters // 47. Along(沿线按距离取点) const along = turf.along(line, 2, {units: 'kilometers'}); // 48. Nearest point(最近点查询) const nearest = turf.nearestPoint(pt, points); // 49. Interpolate(沿线插值) const interpolated = turf.interpolate(line, 100); // 50. Center(要素集合的几何中心) const center = turf.center(features);

注意 Turf.js 默认假设平面坐标,distance/area在低纬度小范围内足够精确,跨大洲分析时建议先投影。安装方式为npm install @turf/turf


七、领域特定示例

遥感:Sentinel-2 NDVI 时间序列与云掩膜

以下 5 个示例基于 Google Earth Engine,展示云原生遥感处理的典型链式调用(remote-sensing.md 提供了更完整的波段指数函数族与 Landsat Collection 2 定标处理)。

import ee # 51. Sentinel-2 NDVI time series(SR = 地表反射率,HARMONIZED 为统一数据集) s2 = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED') def add_ndvi(img): return img.addBands(img.normalizedDifference(['B8', 'B4']).rename('NDVI')) s2_ndvi = s2.map(add_ndvi) # 52. Landsat collection(LC08 = Landsat 8, C02/T1_L2 = Collection 2 Level 2) landsat = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2') landsat = landsat.filter(ee.Filter.lt('CLOUD_COVER', 20)) # 53. Cloud masking(QA60 第 10/11 位为云标志) def mask_clouds(image): qa = image.select('QA60') mask = qa.bitwiseAnd(1 << 10).eq(0) return image.updateMask(mask) # 54. Composite(中值合成去除残余云噪声) median = s2.median() # 55. Export(导出到 Google Drive,scale=10m) task = ee.batch.Export.image.toDrive(image, 'description', scale=10)

normalizedDifference(['B8', 'B4'])即 NDVI 的 EE 内置实现;map()对集合内每景影像应用函数,是 EE 批量处理的函数式范式。完整的 EE 时间序列提取流程(reduceRegion+ 构建 pandas DataFrame)见 SKILL.md 的 Google Earth Engine 章节。

机器学习:从随机森林到 CNN

# 56-58. 随机森林训练、预测与特征重要性 from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(n_estimators=100, max_depth=20) rf.fit(X_train, y_train) prediction = rf.predict(X_test) importances = pd.DataFrame({'feature': features, 'importance': rf.feature_importances_}) # 59-60. CNN 模型定义与训练循环 import torch.nn as nn class CNN(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(4, 32, 3) # 输入 4 波段 self.conv2 = nn.Conv2d(32, 64, 3) self.fc = nn.Linear(64 * 28 * 28, 10) # 输出 10 类 for epoch in range(epochs): outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step()

machine-learning.md 对这块做了大幅深化:随机森林的完整版本含train_test_split、分层采样、class_weight='balanced'与分类报告评估;CNN 扩展为带BatchNorm2d与转置卷积解码器的 U-Net 语义分割结构;还给出图神经网络(PyTorch Geometric GCN)、Siamese 变化检测网络与 SHAP 空间可解释性实现,可直接作为进阶参考。

网络分析:OSMnx 路网

import osmnx as ox # 61. 按地名下载路网(network_type 可选 drive/walk/bike/all) G = ox.graph_from_place('City', network_type='drive') # 62. 最短路径(weight 可选 length/travel_time) route = ox.shortest_path(G, orig_node, dest_node, weight='length') # 63. 添加边属性(速度 → 通行时间) G = ox.add_edge_speeds(G) G = ox.add_edge_travel_times(G) # 64. 最近节点(坐标 → 路网节点) node = ox.distance.nearest_nodes(G, X, Y) # 65. 绘制路径 ox.plot_graph_route(G, route)

示例 63 中add_edge_speeds依据道路等级推断限速,add_edge_travel_times再由速度与长度计算通行时间,二者搭配即可将最短路径问题升级为最省时路径(SKILL.md 中的网络分析示例即以weight='travel_time'做路径规划)。


八、完整工作流

土地覆盖分类(栅格 + 矢量训练样本 + 随机森林)

# 66. Complete classification workflow def classify_imagery(image_path, training_gdf, output_path): from sklearn.ensemble import RandomForestClassifier import rasterio from rasterio.features import rasterize # Load imagery with rasterio.open(image_path) as src: image = src.read() profile = src.profile # Extract training data(用训练多边形栅格化提取样本像素) X, y = [], [] for _, row in training_gdf.iterrows(): mask = rasterize([(row.geometry, 1)], out_shape=image.shape[1:]) pixels = image[:, mask > 0].T X.extend(pixels) y.extend([row['class']] * len(pixels)) # Train rf = RandomForestClassifier(n_estimators=100) rf.fit(X, y) # Predict(整幅影像逐像素分类) image_flat = image.reshape(image.shape[0], -1).T prediction = rf.predict(image_flat) prediction = prediction.reshape(image.shape[1], image.shape[2]) # Save profile.update(dtype=rasterio.uint8, count=1) with rasterio.open(output_path, 'w', **profile) as dst: dst.write(prediction.astype(rasterio.uint8), 1)

这是遥感分类的标准范式:训练样本栅格化 → 按掩膜提取像素特征 → 随机森林拟合 → 全图预测 → 写回 GeoTIFF。machine-learning.md 对该工作流的完善版本额外传入了transform参数以保证栅格化坐标正确(out_shape+transform+fill=0),并加入验证集评估与特征重要性输出。

洪水制图(DEM 淹没分析)

# 67. Flood inundation from DEM def map_flood(dem_path, flood_level, output_path): import rasterio import numpy as np with rasterio.open(dem_path) as src: dem = src.read(1) profile = src.profile # Identify flooded cells(低于水位的像元即被淹没) flooded = dem < flood_level # Calculate depth(淹没深度 = 水位 - 地面高程) depth = np.where(flooded, flood_level - dem, 0) # Save with rasterio.open(output_path, 'w', **profile) as dst: dst.write(depth.astype(rasterio.float32), 1)

该示例演示了基于 DEM 的静态淹没模拟:flood_level为假定水位(单位与 DEM 高程一致),输出淹没范围与水深栅格。实际洪水研究中通常还需结合流向累积(见示例 96 的FlowAccumulation)做连通性约束。

地形分析(坡度与坡向)

# 68. Slope and aspect from DEM def terrain_analysis(dem_path): import numpy as np from scipy import ndimage with rasterio.open(dem_path) as src: dem = src.read(1) # Calculate gradients dy, dx = np.gradient(dem) # Slope in degrees(坡度角 = arctan(梯度模长)) slope = np.arctan(np.sqrt(dx**2 + dy**2)) * 180 / np.pi # Aspect(坡向,0°=北,顺时针) aspect = np.arctan2(-dy, dx) * 180 / np.pi aspect = (90 - aspect) % 360 return slope, aspect

SKILL.md 的地形分析章节在坡度/坡向基础上补充了山体阴影(hillshade)计算,代码几乎逐行对应示例 97 的公式,可作为本示例的直接延伸。


九、扩展示例(69-100):空间统计、插值与水文分析

几何与空间关系(69-71)

# 69. Point in polygon test point.within(polygon) # 70. Nearest neighbor(BallTree 加速最近邻查询) from sklearn.neighbors import BallTree tree = BallTree(coords) distances, indices = tree.query(point) # 71. Spatial index(R-tree 批量插入几何) from rtree import index idx = index.Index() for i, geom in enumerate(geometries): idx.insert(i, geom.bounds)

示例 70-71 是空间加速的两类典型:BallTree用于点的近邻检索,R-tree(rtree库)用于几何包围盒(bounds)的快速相交预筛选,后者正是 GeoPandassindex的底层机制。

栅格进阶(72-77)

# 72. Clip raster(crop=True 裁剪到多边形范围) from rasterio.mask import mask clipped, transform = mask(src, [polygon], crop=True) # 73. Merge rasters(多幅拼接,自动统一变换) from rasterio.merge import merge merged, transform = merge([src1, src2, src3]) # 74. Reproject image from rasterio.warp import reproject reproject(source, destination, src_transform=transform, src_crs=crs) # 75. Zonal statistics(按分区统计栅格:mean/sum 等) from rasterstats import zonal_stats stats = zonal_stats(zones, raster, stats=['mean', 'sum']) # 76. Extract values at points(栅格在指定坐标处采样) from rasterio.sample import sample_gen values = list(sample_gen(src, [(x, y), (x2, y2)])) # 77. Resample raster(双线性重采样放大 2 倍) import rasterio from rasterio.enums import Resampling resampled = dst.read(out_shape=(src.height * 2, src.width * 2), resampling=Resampling.bilinear)

zonal_stats是区域统计的标准工具(返回每个分区内的均值、总和、计数等),配合sample_gen可在点位置直接采样栅格值,二者是"矢量 × 栅格"联动的高频操作。

网格与地理编码(78-83)

# 78. Create regular grid(规则格网生成) from shapely.geometry import box grid = [box(xmin, ymin, xmin+dx, ymin+dy) for xmin in np.arange(minx, maxx, dx) for ymin in np.arange(miny, maxy, dy)] # 79. Geocoding with geopy(地址 → 坐标) from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="geo_app") location = geolocator.geocode("Golden Gate Bridge") # 80. Reverse geocoding(坐标 → 地址) location = geolocator.reverse("37.8, -122.4") # 81. Calculate bearing(两点初始方位角) from geopy import distance bearing = distance.geodesic(point1, point2).initial_bearing # 82. Great circle distance(大圆距离,单位 km) from geopy.distance import geodesic d = geodesic(point1, point2).km # 83. Create bounding box from shapely.geometry import box bbox = box(minx, miny, maxx, maxy)

注意Nominatim必须提供合法user_agent,且大量请求需遵守 OSM 使用政策(限速)。

空间分布与空间统计(84-90)

# 84. Convex hull(凸包) hull = points.geometry.unary_union.convex_hull # 85. Voronoi diagram(泰森多边形) from scipy.spatial import Voronoi vor = Voronoi(coords) # 86. Kernel density estimation(核密度估计) from scipy.stats import gaussian_kde kde = gaussian_kde(points) density = kde(np.mgrid[xmin:xmax:100j, ymin:ymax:100j]) # 87. Hotspot analysis(局部 Getis-Ord G* 热点分析) from esda.getisord import G_Local g_local = G_Local(values, weights) # 88. Moran's I(全局空间自相关) from esda.moran import Moran moran = Moran(values, weights) # 89. Geary's C(另一全局自相关指标) from esda.geary import Geary geary = Geary(values, weights) # 90. Semi-variogram(半变异函数拟合) from skgstat import Variogram vario = Variogram(coords, values)

示例 87-89 使用esda(PySAL 家族)做探索性空间数据分析:Moran's I 衡量全局聚集程度,Getis-Ord G* 定位局部热点,weights为空间权重矩阵(可由libpysal.weights构建)。Variogram则为后续克里金插值提供经验变异函数。

空间插值(91-94)

# 91. Kriging(普通克里金,球状变异函数模型) from pykrige.ok import OrdinaryKriging OK = OrdinaryKriging(X, Y, Z, variogram_model='spherical') # 92. IDW interpolation(反距离加权,method 可选 linear/cubic/nearest) from scipy.interpolate import griddata grid_z = griddata(points, values, (xi, yi), method='linear') # 93. Natural neighbor interpolation(自然邻域法) from scipy.interpolate import NearestNDInterpolator interp = NearestNDInterpolator(points, values) # 94. Spline interpolation(径向基函数样条) from scipy.interpolate import Rbf rbf = Rbf(x, y, z, function='multiquadric')

四种插值各有适用场景:克里金带误差估计且需变异函数模型;IDW 简单快速但对参数敏感;NearestNDInterpolator即自然邻域思想的离散近似;RBF 适合平滑连续场。Julia 侧的克里金与模拟实现见 programming-languages.md 的 GeoStats.jl 示例。

水文与地形渲染(95-100)

# 95. Watershed delineation(流域分割,标记 + 分水岭算法) from scipy.ndimage import label, watershed markers = label(local_minima) labels = watershed(elevation, markers) # 96. Stream extraction(流向累积提取河网) import richdem as rd rd.FillDepressions(dem, in_place=True) # 填洼 flow = rd.FlowAccumulation(dem, method='D8') # D8 流向累积 streams = flow > 1000 # 阈值提取河网 # 97. Hillshade(山体阴影公式,alt 为太阳高度角、az 为方位角) from scipy import ndimage hillshade = np.sin(alt) * np.sin(slope) + np.cos(alt) * np.cos(slope) * np.cos(az - aspect) # 98. Viewshed(通视分析骨架:从观测点逐角度发射视线) def viewshed(dem, observer): # Line of sight calculation visible = np.ones_like(dem, dtype=bool) for angle in np.linspace(0, 2*np.pi, 360): # Cast ray and check visibility pass return visible # 99. Shaded relief(基于 matplotlib LightSource 的立体渲染) from matplotlib.colors import LightSource ls = LightSource(azdeg=315, altdeg=45) shaded = ls.hillshade(elevation, vert_exaggeration=1) # 100. Export to web tiles(按 XYZ 瓦片切片导出) from mercantile import tiles from PIL import Image for tile in tiles(w, s, z): # Render tile pass

示例 96 是标准水文流程:填洼 → 流向累积 → 阈值提取;示例 97 与 SKILL.md 中的 hillshade 公式一致(太阳默认方位 315°、高度 45°),示例 99 则用LightSource一行实现同样效果并支持垂直夸张(vert_exaggeration)。示例 100 展示了将栅格切成 Web 墨卡托 XYZ 瓦片(Web Mercator,即 EPSG:3857)的导出思路。


十、示例库的使用策略与进阶路径

这份 100 例清单的设计遵循清晰的分层逻辑,可按需取用:

  1. 按语言选择:Python 覆盖最全(约 80 例),适合作为主力;R(sf)、Julia(ArchGDAL)、JavaScript(Turf.js)适合团队既有技术栈或 Web 端轻量分析。C++、Java、Go、Rust 的对应实现见 programming-languages.md。
  2. 按任务组装:典型的地表覆盖制图任务 = 示例 11(读栅格)+ 示例 1(读矢量样本)+ 示例 66(分类工作流)+ 示例 19(可视化);洪水风险分析 = 示例 67(淹没模拟)+ 示例 96(河网提取)+ 示例 75(分区统计)。
  3. 始终遵守两条铁律:面积/距离/缓冲区运算前先投影(示例 4-5、9-10);多数据源操作前校验 CRS 一致。完整 CRS 理论、UTM 分区与变换 API 见 coordinate-systems.md。

若示例运行报错,troubleshooting.md 提供了常见问题定位;想要更大规模数据与云原生流程(STAC + COG + Planetary Computer),SKILL.md 的现代云工作流章节给出了从 STAC 检索到 xarray 加载的完整链式代码。示例库的剩余部分(按语言与分类组织的 500+ 例)位于 code-examples.md 所在目录的其他参考文档中,可对照 README.md 的目录索引继续深入。

【免费下载链接】scientific-agent-skillsTurn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 190,000+ scientists worldwide. 165 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.项目地址: https://gitcode.com/GitHub_Trending/cl/scientific-agent-skills

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/10 17:16:33

MAX2769ETI+T,多星座GNSS单芯片射频接收机前端

MAX2769ETIT是ADI&#xff08;原Maxim&#xff09;基于SiGe BiCMOS工艺的完整低中频GNSS射频接收前端&#xff0c;支持GPS、GLONASS、Galileo卫星定位信号接收。单芯片集成双路LNA、混频器、镜像抑制滤波器、PGA、分数N PLL/VCO、有源天线检测与多位ADC&#xff0c;无需外置中频…

作者头像 李华
网站建设 2026/9/10 17:16:31

AD8232ACPZ-R7,单导联ECG超低功耗生物电位模拟前端

AD8232ACPZ-R7是ADI亚德诺单导联生物电专用模拟前端AFE芯片&#xff0c;专为ECG心电、肌电EMG等微弱生物电位信号采集设计。单芯片集成仪表放大器、双极点高通滤波、右腿驱动RLD电路、导联脱落检测、辅助运放&#xff0c;支持2.0V~3.5V单电源&#xff0c;典型增益100倍&#xf…

作者头像 李华
网站建设 2026/9/10 17:13:18

MATLAB均匀量化仿真:精准建模ADC量化误差与SNR验证

简介&#xff1a;本资源是一套面向信号处理初学者与通信工程学生的MATLAB均匀量化仿真实验材料&#xff0c;聚焦量化误差成因、建模与性能评估等核心问题。资源包含3个关键文件&#xff1a;1个MATLAB主脚本&#xff08;Untitled2.m&#xff09;实现正弦/语音信号的采样、8级均匀…

作者头像 李华
网站建设 2026/9/10 17:11:09

TVBoxOSC文档查看器:3步把电视盒子变成大屏文档阅读台

TVBoxOSC文档查看器&#xff1a;3步把电视盒子变成大屏文档阅读台 【免费下载链接】TVBoxOSC TVBoxOSC - 一个基于第三方项目的代码库&#xff0c;用于电视盒子的控制和管理。 项目地址: https://gitcode.com/GitHub_Trending/tv/TVBoxOSC TVBoxOSC是一个面向电视盒子的…

作者头像 李华
网站建设 2026/9/10 17:09:16

JAVA毕设选题推荐:基于 Web 的实验室耗材全生命周期管理平台的设计与实现 基于 Web 技术的实验室耗材管理系统【附源码、mysql、文档、调试+代码讲解+全bao等】

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华