signature: crate de mesure de signatures de relief (cadrage 20), CLI signer, 13 tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
a25690363d
révision
6f2445c8a9
12 fichiers modifiés
+1786
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,112 @@
|
||||
//! Grille d'altitudes (f32, mètres) et utilitaires de rééchantillonnage.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Raster {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
/// Taille d'une cellule en mètres.
|
||||
pub pas_m: f32,
|
||||
/// Ligne par ligne, nord en premier. Les valeurs non finies sont traitées comme « sans donnée ».
|
||||
pub z: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Raster {
|
||||
pub fn new(w: usize, h: usize, pas_m: f32, z: Vec<f32>) -> Raster {
|
||||
assert_eq!(w * h, z.len(), "taille de grille incohérente");
|
||||
Raster { w, h, pas_m, z }
|
||||
}
|
||||
pub fn from_fn(w: usize, h: usize, pas_m: f32, f: impl Fn(f32, f32) -> f32) -> Raster {
|
||||
let mut z = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
z.push(f(x as f32 * pas_m, y as f32 * pas_m));
|
||||
}
|
||||
}
|
||||
Raster { w, h, pas_m, z }
|
||||
}
|
||||
#[inline]
|
||||
pub fn at(&self, x: usize, y: usize) -> f32 {
|
||||
self.z[y * self.w + x]
|
||||
}
|
||||
/// Moyenne par blocs de `k`×`k` (réduction de résolution). Ignore les valeurs non finies.
|
||||
pub fn coarsen(&self, k: usize) -> Raster {
|
||||
if k <= 1 {
|
||||
return self.clone();
|
||||
}
|
||||
let (nw, nh) = (self.w / k, self.h / k);
|
||||
let mut z = Vec::with_capacity(nw * nh);
|
||||
for by in 0..nh {
|
||||
for bx in 0..nw {
|
||||
let (mut s, mut n) = (0.0f64, 0u32);
|
||||
for dy in 0..k {
|
||||
for dx in 0..k {
|
||||
let v = self.at(bx * k + dx, by * k + dy);
|
||||
if v.is_finite() {
|
||||
s += v as f64;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
z.push(if n > 0 { (s / n as f64) as f32 } else { f32::NAN });
|
||||
}
|
||||
}
|
||||
Raster { w: nw, h: nh, pas_m: self.pas_m * k as f32, z }
|
||||
}
|
||||
pub fn crop(&self, x0: usize, y0: usize, w: usize, h: usize) -> Raster {
|
||||
let mut z = Vec::with_capacity(w * h);
|
||||
for y in y0..y0 + h {
|
||||
z.extend_from_slice(&self.z[y * self.w + x0..y * self.w + x0 + w]);
|
||||
}
|
||||
Raster { w, h, pas_m: self.pas_m, z }
|
||||
}
|
||||
/// Remplace les trous par la moyenne globale (simple, suffisant pour des tuiles quasi complètes).
|
||||
pub fn filled(&self) -> Raster {
|
||||
let (s, n) = self.z.iter().filter(|v| v.is_finite()).fold((0.0f64, 0usize), |a, v| (a.0 + *v as f64, a.1 + 1));
|
||||
let m = if n > 0 { (s / n as f64) as f32 } else { 0.0 };
|
||||
Raster { z: self.z.iter().map(|v| if v.is_finite() { *v } else { m }).collect(), ..self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Lecture d'un .npy float32 2D (C-order, little-endian), version 1.0/2.0.
|
||||
#[allow(clippy::chunks_exact_with_constant_chunk_size)]
|
||||
pub fn read_npy_f32(bytes: &[u8]) -> Result<(usize, usize, Vec<f32>), String> {
|
||||
if bytes.len() < 10 || &bytes[..6] != b"\x93NUMPY" {
|
||||
return Err("pas un fichier .npy".into());
|
||||
}
|
||||
let (hlen, off) = if bytes[6] == 1 { (u16::from_le_bytes([bytes[8], bytes[9]]) as usize, 10) } else { (u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize, 12) };
|
||||
let hdr = std::str::from_utf8(&bytes[off..off + hlen]).map_err(|e| e.to_string())?;
|
||||
if !hdr.contains("<f4") || hdr.contains("True") {
|
||||
return Err(format!("npy non supporté (attendu <f4, C-order): {hdr}"));
|
||||
}
|
||||
let sh = hdr.split("'shape': (").nth(1).ok_or("shape absente")?.split(')').next().unwrap();
|
||||
let d: Vec<usize> = sh.split(',').filter_map(|s| s.trim().parse().ok()).collect();
|
||||
if d.len() != 2 {
|
||||
return Err("grille 2D attendue".into());
|
||||
}
|
||||
let data = &bytes[off + hlen..];
|
||||
if data.len() < d[0] * d[1] * 4 {
|
||||
return Err("données tronquées".into());
|
||||
}
|
||||
let z = data.chunks_exact(4).take(d[0] * d[1]).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
|
||||
Ok((d[1], d[0], z))
|
||||
}
|
||||
|
||||
/// Lit un GeoTIFF mono-bande (f32/u8/u16/i16...) ; pas lu dans ModelPixelScale (tag 33550), 1 m sinon.
|
||||
/// Valeurs <= -9000 (nodata) -> NaN.
|
||||
pub fn lire_geotiff(path: &str) -> Result<Raster, String> {
|
||||
use tiff::decoder::{Decoder, DecodingResult};
|
||||
use tiff::tags::Tag;
|
||||
let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let mut d = Decoder::new(std::io::BufReader::new(f)).map_err(|e| e.to_string())?;
|
||||
let (w, h) = d.dimensions().map_err(|e| e.to_string())?;
|
||||
let pas = d.get_tag_f64_vec(Tag::Unknown(33550)).ok().and_then(|v| v.first().copied()).unwrap_or(1.0) as f32;
|
||||
let z: Vec<f32> = match d.read_image().map_err(|e| e.to_string())? {
|
||||
DecodingResult::F32(v) => v,
|
||||
DecodingResult::F64(v) => v.into_iter().map(|x| x as f32).collect(),
|
||||
DecodingResult::U8(v) => v.into_iter().map(|x| x as f32).collect(),
|
||||
DecodingResult::U16(v) => v.into_iter().map(|x| x as f32).collect(),
|
||||
DecodingResult::I16(v) => v.into_iter().map(|x| x as f32).collect(),
|
||||
_ => return Err("type de pixel non supporté".into()),
|
||||
};
|
||||
let z = z.into_iter().map(|v| if v <= -9000.0 { f32::NAN } else { v }).collect();
|
||||
Ok(Raster::new(w as usize, h as usize, pas, z))
|
||||
}
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur