拓冰建站拓冰建站
首页 / 资讯中心 / 正文

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 stackconda 推荐 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示例中还会用到rtree、rasterstats、geopy、scipy、sklearn、pykrige、skgstat、esda、libpysal、richdem、mercantile、Pillow等可按需pip install。所有与面积、距离、缓冲区相关的运算都必须先转到投影坐标系如 UTM这是示例反复强调的核心约束。一、Python 核心操作矢量数据GeoPandas 是矢量数据的主力接口底层封装 FionaI/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, layerlayer_name)读取后第一件事是检查gdf.crs。如为None需用gdf.set_crs(EPSG:4326)手动指定多数据源叠加前务必保证 CRS 一致coordinate-systems.md 给出了ensure_same_crs辅助函数作为规范写法。4-5. 重投影与缓冲区# 4. ReprojectEPSG: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 joinhow 决定保留哪些记录predicate 决定空间关系 joined gpd.sjoin(points, polygons, howinner, predicatewithin)predicate可选intersects、within、contains、touches、crosses、overlaps等howinner只保留空间上匹配到的记录howleft保留左侧全部。GeoPandas 会自动使用空间索引加速匹配SKILL.md 性能提示称可带来 10-100 倍查询加速。7-8. 融合与裁剪# 7. Dissolve按属性字段聚合几何 dissolved gdf.dissolve(bycategory) # 8. Clip用 mask 多边形裁剪矢量 clipped gpd.clip(gdf, mask)dissolve支持aggfunc参数对属性做聚合统计如aggfuncsumgpd.clip是 0.7 版本提供的顶层便捷函数等价于逐要素相交后合并。9-10. 面积与长度计算# 9. Calculate area投影坐标系下单位为平方米 gdf[area_km2] gdf.geometry.area / 1e6 # 10. Calculate length米 → 千米 gdf[length_km] gdf.geometry.length / 1000geometry.area/geometry.length返回的结果单位取决于当前 CRS。在 EPSG:4326 下会得到平方度/度因此这两行代码同样必须在投影后执行。完整的正确写法见 coordinate-systems.md 的面积单位陷阱一节。二、栅格数据处理RasterioRasterio 提供对 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, windowwindow)窗口读取是处理超大影像的核心手段。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 NDVISentinel-2band4Red, band8NIR red src.read(4) nir src.read(8) ndvi (nir - red) / (nir red 1e-8) # 1e-8 防止除零NDVI 公式即归一化植被指数1e-8 的 epsilon 用于避免分母为零。更完整的写法可参考 SKILL.md 的 Quick Startsrc.read(4).astype(float)并配合profile.update(count1, dtyperasterio.float32)后写出同时处理 NaN。索引族NDVI/EVI/SAVI/NDWI/NBR/NDBI的批量计算实现见 remote-sensing.md。16-17. 多边形掩膜与栅格重投影# 16. Mask raster with polygoncropTrue 裁剪到要素范围 from rasterio.mask import mask masked, transform mask(src, [polygon.geometry], cropTrue) # 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 GeoPandascolumn 指定着色字段 gdf.plot(columnvalue, cmapYlOrRd, legendTrue, figsize(12, 8)) # 19. Interactive map with Folium import folium m folium.Map(location[37.7, -122.4], zoom_start12) folium.GeoJson(gdf).add_to(m) # 20. Choropleth分级设色图stats 为属性 DataFrame folium.Choropleth(gdf, datastats, columns[id, value], key_onfeature.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(alpha0.5) ctx.add_basemap(ax, crsgdf.crs) # 23. Multi-layer map多层叠加到同一坐标轴 import matplotlib.pyplot as plt fig, ax plt.subplots() gdf1.plot(axax, colorblue) gdf2.plot(axax, colorred) # 24. 3D plot with PyDeck import pydeck as pdk pdk.Deck(layers[pdk.Layer(ScatterplotLayer, datadf)], map_stylemapbox://styles/mapbox/dark-v9) # 25. Time series map with hvplot支持 OSM 瓦片底图 import hvplot.geopandas gdf.hvplot(cvalue, geoTrue, tilesOSM, frame_width600)示例 22 中crsgdf.crs必须与底图坐标系一致通常为 EPSG:3857add_basemap会自动处理重投影。示例 25 的hvplot可直接对带时间维的 GeoDataFrame 生成滑动条动画地图。四、R 语言示例sf 包R 侧的地理空间生态以sfSimple Features为核心。programming-languages.md 还展示了terra栅格包、ggplot2绘图与完整的 R 土地覆盖分类工作流randomForestcaret。以下 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. Reproject32610 UTM Zone 10N米制 roads_utm - st_transform(roads, 32610) # 31. Bufferdist 单位为 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 / GeoInterfaceJulia 侧通过ArchGDAL直接绑定 GDALGeoInterface提供跨库统一的几何抽象programming-languages.md 中还包含GeoStats.jl的地统计插值、克里金与模拟示例。# 36. Load ArchGDAL using ArchGDAL # 37. Read shapefiledo-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.jsTurf.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 seriesSR 地表反射率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 collectionLC08 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 maskingQA60 第 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 Drivescale10m task ee.batch.Export.image.toDrive(image, description, scale10)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_estimators100, max_depth20) 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_weightbalanced与分类报告评估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_typedrive) # 62. 最短路径weight 可选 length/travel_time route ox.shortest_path(G, orig_node, dest_node, weightlength) # 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 中的网络分析示例即以weighttravel_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_shapeimage.shape[1:]) pixels image[:, mask 0].T X.extend(pixels) y.extend([row[class]] * len(pixels)) # Train rf RandomForestClassifier(n_estimators100) 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(dtyperasterio.uint8, count1) with rasterio.open(output_path, w, **profile) as dst: dst.write(prediction.astype(rasterio.uint8), 1)这是遥感分类的标准范式训练样本栅格化 → 按掩膜提取像素特征 → 随机森林拟合 → 全图预测 → 写回 GeoTIFF。machine-learning.md 对该工作流的完善版本额外传入了transform参数以保证栅格化坐标正确out_shapetransformfill0并加入验证集评估与特征重要性输出。洪水制图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, aspectSKILL.md 的地形分析章节在坡度/坡向基础上补充了山体阴影hillshade计算代码几乎逐行对应示例 97 的公式可作为本示例的直接延伸。九、扩展示例69-100空间统计、插值与水文分析几何与空间关系69-71# 69. Point in polygon test point.within(polygon) # 70. Nearest neighborBallTree 加速最近邻查询 from sklearn.neighbors import BallTree tree BallTree(coords) distances, indices tree.query(point) # 71. Spatial indexR-tree 批量插入几何 from rtree import index idx index.Index() for i, geom in enumerate(geometries): idx.insert(i, geom.bounds)示例 70-71 是空间加速的两类典型BallTree用于点的近邻检索R-treertree库用于几何包围盒bounds的快速相交预筛选后者正是 GeoPandassindex的底层机制。栅格进阶72-77# 72. Clip rastercropTrue 裁剪到多边形范围 from rasterio.mask import mask clipped, transform mask(src, [polygon], cropTrue) # 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_transformtransform, src_crscrs) # 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), resamplingResampling.bilinear)zonal_stats是区域统计的标准工具返回每个分区内的均值、总和、计数等配合sample_gen可在点位置直接采样栅格值二者是矢量 × 栅格联动的高频操作。网格与地理编码78-83# 78. Create regular grid规则格网生成 from shapely.geometry import box grid [box(xmin, ymin, xmindx, ymindy) 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_agentgeo_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. Morans I全局空间自相关 from esda.moran import Moran moran Moran(values, weights) # 89. Gearys C另一全局自相关指标 from esda.geary import Geary geary Geary(values, weights) # 90. Semi-variogram半变异函数拟合 from skgstat import Variogram vario Variogram(coords, values)示例 87-89 使用esdaPySAL 家族做探索性空间数据分析Morans I 衡量全局聚集程度Getis-Ord G* 定位局部热点weights为空间权重矩阵可由libpysal.weights构建。Variogram则为后续克里金插值提供经验变异函数。空间插值91-94# 91. Kriging普通克里金球状变异函数模型 from pykrige.ok import OrdinaryKriging OK OrdinaryKriging(X, Y, Z, variogram_modelspherical) # 92. IDW interpolation反距离加权method 可选 linear/cubic/nearest from scipy.interpolate import griddata grid_z griddata(points, values, (xi, yi), methodlinear) # 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, functionmultiquadric)四种插值各有适用场景克里金带误差估计且需变异函数模型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_placeTrue) # 填洼 flow rd.FlowAccumulation(dem, methodD8) # 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, dtypebool) 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(azdeg315, altdeg45) shaded ls.hillshade(elevation, vert_exaggeration1) # 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 例清单的设计遵循清晰的分层逻辑可按需取用按语言选择Python 覆盖最全约 80 例适合作为主力Rsf、JuliaArchGDAL、JavaScriptTurf.js适合团队既有技术栈或 Web 端轻量分析。C、Java、Go、Rust 的对应实现见 programming-languages.md。按任务组装典型的地表覆盖制图任务 示例 11读栅格 示例 1读矢量样本 示例 66分类工作流 示例 19可视化洪水风险分析 示例 67淹没模拟 示例 96河网提取 示例 75分区统计。始终遵守两条铁律面积/距离/缓冲区运算前先投影示例 4-5、9-10多数据源操作前校验 CRS 一致。完整 CRS 理论、UTM 分区与变换 API 见 coordinate-systems.md。若示例运行报错troubleshooting.md 提供了常见问题定位想要更大规模数据与云原生流程STAC COG Planetary ComputerSKILL.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),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门