# moonbit-cog

`moonbit-cog` 是一个使用 MoonBit 编写的地理空间处理引擎，面向 Cloud-Optimized GeoTIFF（COG）、栅格代数、多光谱指数、地形分析和云端字节范围规划。项目以原生执行为参考路径，也按 MoonBit 的跨平台组织方式支持 WebAssembly 相关目标，并且不依赖外部 C/C++ 运行时。

[![CI](https://github.com/Mostan-303/moonbit-cog/actions/workflows/test.yml/badge.svg)](https://github.com/Mostan-303/moonbit-cog/actions/workflows/test.yml)
[![许可证](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE)

## 应用场景

- 解析 TIFF 6.0、BigTIFF、GeoKeys、瓦片、条带和金字塔概览元数据。
- 处理 Sentinel-2、Landsat 等多光谱场景，计算植被、水体、火烧、土壤和水分指数。
- 执行栅格地图代数、窗口统计、空间滤波、重采样、分类、DEM 地形和水文分析。
- 在远程读取前，为 COG 窗口生成确定性的 HTTP Byte-Range 请求计划。
- 将独立 MoonBit 包复用于原生命令行、数据处理工具和 WebAssembly 应用。

## 核心能力

项目包含 TIFF/BigTIFF 解码与编码、LZW/Deflate/PackBits 解压、仿射地理参考、栅格统计、多光谱算子、空间索引、STAC 目录结构、地形与水文分析以及质量验证工具。`RasterWindow` API 会安全裁剪窗口请求，保留仿射变换的比例、倾斜和偏移，并在统计时忽略 NoData 与非有限值。

```moonbit
let request = @raster.RasterWindow::new(128, 64, 512, 512)
match @raster.analyze_window(grid, request) {
  Some(analysis) => println(analysis.statistics.mean.to_string())
  None => println("窗口与栅格没有交集")
}
```

## 包结构

| 领域 | 包 |
| --- | --- |
| 文件格式 | `tiff`、`encoder`、`compression`、`geokeys`、`crs`、`geotiff_exif` |
| 栅格与指数 | `raster`、`indices`、`spectral`、`pipeline`、`stats`、`analysis` |
| 空间处理 | `spatial_ops`、`spatial_statistics`、`indexing`、`tiling`、`morphology` |
| 地形与质量 | `dem`、`hydrology`、`quality_control`、`validation_suite` |
| 云端与目录 | `cloud_optim`、`cog_validator`、`stac`、`stac_catalog` |
| 工具与输出 | `cli`、`main`、`reports`、`visualization`、`benchmark` |

## 快速开始

安装当前 MoonBit stable 工具链后，在仓库根目录执行：

```bash
moon update
moon fmt --check
moon check --deny-warn
moon test --deny-warn
moon build --target native src/main
moon run --target native src/main -- help
```

运行实测 NDVI 基准：

```bash
moon run --target native src/main -- bench 512 512
```

输出包含尺寸、迭代次数、算法实测耗时、每秒百万像素吞吐量和确定性校验和。可复现的本地数据记录在 [BENCHMARKS.md](BENCHMARKS.md)。

## 验证与目标平台

CI 会检查格式、包元数据、所有目标的编译以及在禁止警告模式下的所有目标测试。本地等价命令如下：

```bash
moon version --all
moon update
moon fmt --check
moon check --target all --deny-warn
moon test --target all --deny-warn
moon fmt && git diff --exit-code
moon info && git diff --exit-code
```

代码按 `native`、`wasm`、`wasm-gc` 和 `js` 目标组织，具体可用性取决于所选包及运行时。命令行基准以 native 目标为参考。

## 源码统计方法

源码规模以 `src/` 下的非测试 `.mbt` 文件为对象，排除空行和整行注释；生成的接口文件与构建产物不计入源码。可在仓库根目录运行下面的 PowerShell 命令获得可审计统计：

```powershell
$files = Get-ChildItem src -Recurse -Filter *.mbt | Where-Object { $_.Name -notmatch '_test\.mbt$' }
$lines = $files | Get-Content | Where-Object {
  $t = $_.Trim()
  $t.Length -gt 0 -and $t -notmatch '^//' -and $t -notmatch '^///\|'
}
($lines | Measure-Object).Count
```

## 基准方法

每次基准运行执行三轮合成 Sentinel-2 NDVI 流程。`elapsed_ms` 使用 `moonbitlang/core/env.now` 包围三轮流程进行测量；吞吐量按总处理像素数除以实测秒数计算；校验和是三轮 NDVI 均值之和。机器相关的进程耗时和完整命令输出记录在 [BENCHMARKS.md](BENCHMARKS.md)。

## 许可证

本项目采用 [Apache-2.0 License](LICENSE)。

英文文档见 [README.md](README.md)。
