1use crate::{Error, Result, WindField};
12use nalgebra::Vector3;
13
14const EARTH_RADIUS_M: f64 = 6_371_000.0;
16
17fn horizontal(speed_mps: f64, direction_from_deg: f64) -> Vector3<f64> {
20 let toward = (direction_from_deg + 180.0).to_radians();
21 Vector3::new(speed_mps * toward.cos(), 0.0, speed_mps * toward.sin())
22}
23
24#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct Monitor {
27 pub x_m: f64,
29 pub z_m: f64,
31 pub speed_mps: f64,
33 pub direction_from_deg: f64,
36}
37
38impl Monitor {
39 pub fn at(x_m: f64, z_m: f64, speed_mps: f64, direction_from_deg: f64) -> Self {
41 Self {
42 x_m,
43 z_m,
44 speed_mps,
45 direction_from_deg,
46 }
47 }
48
49 pub fn from_geo(
54 lat_deg: f64,
55 lon_deg: f64,
56 speed_mps: f64,
57 dir_compass_from_deg: f64,
58 ref_lat_deg: f64,
59 ref_lon_deg: f64,
60 north_azimuth_deg: f64,
61 ) -> Self {
62 let (x_m, z_m) = local_en_m(lat_deg, lon_deg, ref_lat_deg, ref_lon_deg);
63 Self {
64 x_m,
65 z_m,
66 speed_mps,
67 direction_from_deg: (dir_compass_from_deg - north_azimuth_deg).rem_euclid(360.0),
68 }
69 }
70}
71
72pub fn local_en_m(lat_deg: f64, lon_deg: f64, ref_lat_deg: f64, ref_lon_deg: f64) -> (f64, f64) {
76 let dlat = (lat_deg - ref_lat_deg).to_radians();
77 let dlon = (lon_deg - ref_lon_deg).to_radians();
78 let east = EARTH_RADIUS_M * dlon * ref_lat_deg.to_radians().cos();
79 let north = EARTH_RADIUS_M * dlat;
80 (east, north)
81}
82
83pub fn monitors_from_geo_csv(
88 text: &str,
89 ref_lat_deg: f64,
90 ref_lon_deg: f64,
91 north_azimuth_deg: f64,
92) -> Result<Vec<Monitor>> {
93 let mut monitors = Vec::new();
94 for (number, line) in text.lines().enumerate() {
95 let line = line.trim();
96 if line.is_empty() || line.starts_with('#') {
97 continue;
98 }
99 let fields: Vec<&str> = line.split(',').collect();
100 if fields.len() < 4 {
101 return Err(Error::invalid(
102 "monitor csv",
103 format!(
104 "line {}: expected lat,lon,speed_ms,dir_compass_deg",
105 number + 1
106 ),
107 ));
108 }
109 let num = |token: &str, what: &str| -> Result<f64> {
110 token.trim().parse().map_err(|_| {
111 Error::invalid(
112 "monitor csv",
113 format!("line {}: {what} '{token}' is not numeric", number + 1),
114 )
115 })
116 };
117 let (lat, lon) = (num(fields[0], "lat")?, num(fields[1], "lon")?);
118 let speed = num(fields[2], "speed")?;
119 let dir = num(fields[3], "direction")?;
120 if !lat.is_finite()
121 || lat.abs() > 90.0
122 || !lon.is_finite()
123 || !speed.is_finite()
124 || speed < 0.0
125 || !dir.is_finite()
126 {
127 return Err(Error::invalid(
128 "monitor csv",
129 format!(
130 "line {}: readings must be finite with nonnegative speed",
131 number + 1
132 ),
133 ));
134 }
135 monitors.push(Monitor::from_geo(
136 lat,
137 lon,
138 speed,
139 dir,
140 ref_lat_deg,
141 ref_lon_deg,
142 north_azimuth_deg,
143 ));
144 }
145 Ok(monitors)
146}
147
148#[derive(Debug, Clone)]
152pub struct HeightGrid {
153 pub origin_x: f64,
155 pub origin_y: f64,
157 pub dx: f64,
159 pub dy: f64,
161 pub ncols: usize,
163 pub nrows: usize,
165 pub heights: Vec<f64>,
167}
168
169impl HeightGrid {
170 pub fn new(
172 origin_x: f64,
173 origin_y: f64,
174 dx: f64,
175 dy: f64,
176 ncols: usize,
177 nrows: usize,
178 heights: Vec<f64>,
179 ) -> Result<Self> {
180 if dx <= 0.0 || dy <= 0.0 || !dx.is_finite() || !dy.is_finite() {
181 return Err(Error::invalid("height grid", "spacing must be positive"));
182 }
183 if ncols < 2 || nrows < 2 {
184 return Err(Error::invalid("height grid", "needs at least 2x2 cells"));
185 }
186 if heights.len() != ncols * nrows {
187 return Err(Error::invalid(
188 "height grid",
189 "height count does not match the grid shape",
190 ));
191 }
192 if !heights.iter().all(|h| h.is_finite()) {
193 return Err(Error::invalid("height grid", "heights must be finite"));
194 }
195 Ok(Self {
196 origin_x,
197 origin_y,
198 dx,
199 dy,
200 ncols,
201 nrows,
202 heights,
203 })
204 }
205
206 pub fn height_at(&self, x: f64, z: f64) -> f64 {
209 let fx = ((x - self.origin_x) / self.dx).clamp(0.0, self.ncols as f64 - 1.0);
210 let fy = ((z - self.origin_y) / self.dy).clamp(0.0, self.nrows as f64 - 1.0);
211 let (j, i) = (fx.floor() as usize, fy.floor() as usize);
212 let (rx, ry) = (fx - j as f64, fy - i as f64);
213 let j1 = (j + 1).min(self.ncols - 1);
214 let i1 = (i + 1).min(self.nrows - 1);
215 let f = |i: usize, j: usize| self.heights[i * self.ncols + j];
216 (1.0 - ry) * ((1.0 - rx) * f(i, j) + rx * f(i, j1))
217 + ry * ((1.0 - rx) * f(i1, j) + rx * f(i1, j1))
218 }
219
220 pub fn from_ascii(text: &str) -> Result<Self> {
224 let mut ncols = None;
225 let mut nrows = None;
226 let mut xll = None;
227 let mut yll = None;
228 let mut cellsize = None;
229 let mut heights = Vec::new();
230 for line in text.lines() {
231 let line = line.trim();
232 if line.is_empty() {
233 continue;
234 }
235 let mut parts = line.split_whitespace();
236 match parts.next().unwrap_or("").to_ascii_lowercase().as_str() {
237 "ncols" => ncols = parse_asc_num(parts.next()),
238 "nrows" => nrows = parse_asc_num(parts.next()),
239 "xllcorner" | "xllcenter" => xll = parse_asc_num(parts.next()),
240 "yllcorner" | "yllcenter" => yll = parse_asc_num(parts.next()),
241 "cellsize" => cellsize = parse_asc_num(parts.next()),
242 "nodata_value" => continue,
243 _ => {
244 for token in line.split_whitespace() {
245 if let Ok(v) = token.parse::<f64>() {
246 heights.push(v);
247 }
248 }
249 }
250 }
251 }
252 let ncols = ncols.ok_or_else(|| Error::invalid("ascii dem", "missing ncols"))? as usize;
253 let nrows = nrows.ok_or_else(|| Error::invalid("ascii dem", "missing nrows"))? as usize;
254 let cellsize = cellsize.ok_or_else(|| Error::invalid("ascii dem", "missing cellsize"))?;
255 let (xll, yll) = (
256 xll.ok_or_else(|| Error::invalid("ascii dem", "missing xllcorner"))?,
257 yll.ok_or_else(|| Error::invalid("ascii dem", "missing yllcorner"))?,
258 );
259 if heights.len() != ncols * nrows {
260 return Err(Error::invalid(
261 "ascii dem",
262 "height count does not match header",
263 ));
264 }
265 let mut north_up = Vec::with_capacity(heights.len());
267 for row in heights.chunks_exact(ncols).rev() {
268 north_up.extend_from_slice(row);
269 }
270 Self::new(xll, yll, cellsize, cellsize, ncols, nrows, north_up)
271 }
272}
273
274fn parse_asc_num(token: Option<&str>) -> Option<f64> {
275 token.and_then(|s| s.parse().ok())
276}
277
278#[derive(Debug, Clone)]
280pub struct TerrainFlowField {
281 grid: HeightGrid,
282 levels_agl: Vec<f64>,
284 u: Vec<f64>,
287 v: Vec<f64>,
288}
289
290impl TerrainFlowField {
291 pub fn adjust(
299 grid: HeightGrid,
300 base: &dyn WindField,
301 monitors: &[Monitor],
302 levels_agl: &[f64],
303 obs_length_m: f64,
304 surface_decay_m: f64,
305 terrain_scale_m: f64,
306 ) -> Result<Self> {
307 if levels_agl.is_empty() || levels_agl.iter().any(|h| !h.is_finite() || *h < 0.0) {
308 return Err(Error::invalid(
309 "levels_agl",
310 "must be finite and nonnegative",
311 ));
312 }
313 if obs_length_m <= 0.0 || surface_decay_m <= 0.0 || terrain_scale_m <= 0.0 {
314 return Err(Error::invalid("terrain", "length scales must be positive"));
315 }
316 if levels_agl.is_empty() || levels_agl.iter().any(|h| !h.is_finite() || *h < 0.0) {
317 return Err(Error::invalid(
318 "levels_agl",
319 "must be finite and nonnegative",
320 ));
321 }
322 if obs_length_m <= 0.0 || surface_decay_m <= 0.0 {
323 return Err(Error::invalid("terrain", "length scales must be positive"));
324 }
325 for m in monitors {
326 if !m.x_m.is_finite() || !m.z_m.is_finite() || !m.direction_from_deg.is_finite() {
327 return Err(Error::invalid("monitor", "must be finite"));
328 }
329 if !m.speed_mps.is_finite() || m.speed_mps < 0.0 {
330 return Err(Error::invalid("monitor", "speed must be nonnegative"));
331 }
332 }
333 let (ncols, nrows) = (grid.ncols, grid.nrows);
334 let n = ncols * nrows;
335 let inv_dx2 = 1.0 / (grid.dx * grid.dx);
336 let inv_dy2 = 1.0 / (grid.dy * grid.dy);
337 let diag = -2.0 * (inv_dx2 + inv_dy2);
338 let omega = 1.6;
339 let mut u = Vec::with_capacity(levels_agl.len() * n);
340 let mut v = Vec::with_capacity(levels_agl.len() * n);
341 let mut phi = vec![0.0; n];
342 for &level in levels_agl {
343 let mut u0 = vec![0.0; n];
345 let mut v0 = vec![0.0; n];
346 for i in 0..nrows {
347 for j in 0..ncols {
348 let x = grid.origin_x + j as f64 * grid.dx;
349 let z = grid.origin_y + i as f64 * grid.dy;
350 let height = grid.heights[i * ncols + j] + level;
351 let bg = base.wind(0.0, Vector3::new(x, height, z));
352 let (mut cx, mut cz, mut wsum) = (0.0, 0.0, 0.0);
353 for m in monitors {
354 let mw = horizontal(m.speed_mps, m.direction_from_deg);
355 let bg_m = base.wind(
356 0.0,
357 Vector3::new(m.x_m, grid.height_at(m.x_m, m.z_m), m.z_m),
358 );
359 let dx = x - m.x_m;
360 let dz = z - m.z_m;
361 let weight = (-(dx * dx + dz * dz) / (obs_length_m * obs_length_m)).exp()
362 * (-level / surface_decay_m).exp();
363 cx += weight * (mw.x - bg_m.x);
364 cz += weight * (mw.z - bg_m.z);
365 wsum += weight;
366 }
367 if wsum > 0.0 {
368 let w_floor = 0.1;
371 cx /= wsum + w_floor;
372 cz /= wsum + w_floor;
373 }
374 u0[i * ncols + j] = bg.x + cx;
375 v0[i * ncols + j] = bg.z + cz;
376 }
377 }
378 let level_decay = (-level / terrain_scale_m).exp() / terrain_scale_m;
383 let slopes = |u0x: f64, u0z: f64, i: usize, j: usize| -> f64 {
384 let dhdx = (grid.heights[i * ncols + (j + 1).min(ncols - 1)]
385 - grid.heights[i * ncols + j.saturating_sub(1)])
386 / (2.0 * grid.dx);
387 let dhdz = (grid.heights[(i + 1).min(nrows - 1) * ncols + j]
388 - grid.heights[i.saturating_sub(1) * ncols + j])
389 / (2.0 * grid.dy);
390 u0x * dhdx + u0z * dhdz
391 };
392 phi.fill(0.0);
393 for _ in 0..4000 {
394 let mut max_step = 0.0_f64;
395 for i in 1..nrows - 1 {
396 for j in 1..ncols - 1 {
397 let ip = (i + 1).min(nrows - 1);
398 let im = i.saturating_sub(1);
399 let jp = (j + 1).min(ncols - 1);
400 let jm = j.saturating_sub(1);
401 let lap = (phi[i * ncols + jp] + phi[i * ncols + jm]) * inv_dx2
402 + (phi[ip * ncols + j] + phi[im * ncols + j]) * inv_dy2
403 + diag * phi[i * ncols + j];
404 let div = (u0[i * ncols + jp] - u0[i * ncols + jm]) / (2.0 * grid.dx)
405 + (v0[ip * ncols + j] - v0[im * ncols + j]) / (2.0 * grid.dy);
406 let rhs =
407 div - slopes(u0[i * ncols + j], v0[i * ncols + j], i, j) * level_decay;
408 let updated = phi[i * ncols + j] + omega * (rhs - lap) / diag;
409 max_step = max_step.max((updated - phi[i * ncols + j]).abs());
410 phi[i * ncols + j] = updated;
411 }
412 }
413 if max_step < 1e-6 {
414 break;
415 }
416 }
417 for i in 0..nrows {
418 for j in 0..ncols {
419 let edge = i == 0 || i == nrows - 1 || j == 0 || j == ncols - 1;
420 if edge {
421 u.push(u0[i * ncols + j]);
424 v.push(v0[i * ncols + j]);
425 continue;
426 }
427 let jp = (j + 1).min(ncols - 1);
428 let jm = j.saturating_sub(1);
429 let ip = (i + 1).min(nrows - 1);
430 let im = i.saturating_sub(1);
431 let gx = (phi[i * ncols + jp] - phi[i * ncols + jm]) / (2.0 * grid.dx);
432 let gz = (phi[ip * ncols + j] - phi[im * ncols + j]) / (2.0 * grid.dy);
433 u.push(u0[i * ncols + j] - gx);
434 v.push(v0[i * ncols + j] - gz);
435 }
436 }
437 }
438 Ok(Self {
439 grid,
440 levels_agl: levels_agl.to_vec(),
441 u,
442 v,
443 })
444 }
445
446 fn sample_level(&self, level: usize, x: f64, z: f64) -> (f64, f64) {
447 let (ncols, nrows) = (self.grid.ncols, self.grid.nrows);
448 let fx = ((x - self.grid.origin_x) / self.grid.dx).clamp(0.0, ncols as f64 - 1.0);
449 let fy = ((z - self.grid.origin_y) / self.grid.dy).clamp(0.0, nrows as f64 - 1.0);
450 let (j, i) = (fx.floor() as usize, fy.floor() as usize);
451 let (rx, ry) = (fx - j as f64, fy - i as f64);
452 let j1 = (j + 1).min(ncols - 1);
453 let i1 = (i + 1).min(nrows - 1);
454 let base = level * ncols * nrows;
455 let g = |arr: &[f64], i: usize, j: usize| arr[base + i * ncols + j];
456 let sample = |arr: &[f64]| {
457 (1.0 - ry) * ((1.0 - rx) * g(arr, i, j) + rx * g(arr, i, j1))
458 + ry * ((1.0 - rx) * g(arr, i1, j) + rx * g(arr, i1, j1))
459 };
460 (sample(&self.u), sample(&self.v))
461 }
462
463 pub fn horizontal_at(&self, x: f64, y: f64, z: f64) -> (f64, f64) {
465 let agl = y - self.grid.height_at(x, z);
466 let mut level = 0;
467 for (k, &h) in self.levels_agl.iter().enumerate() {
468 if agl <= h {
469 level = k;
470 break;
471 }
472 level = k;
473 }
474 self.sample_level(level, x, z)
475 }
476}
477
478impl WindField for TerrainFlowField {
479 fn wind(&self, _time_s: f64, position_m: Vector3<f64>) -> Vector3<f64> {
480 let (u, v) = self.horizontal_at(position_m.x, position_m.y, position_m.z);
481 Vector3::new(u, 0.0, v)
482 }
483}