oxigdal-ml 0.1.4

Machine learning capabilities for OxiGDAL - ONNX Runtime integration for geospatial ML workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Postprocessing operations for ML results
//!
//! This module provides tile merging, confidence thresholding, polygon conversion,
//! and GeoJSON export capabilities.

use geo_types::{Coord, LineString, MultiPolygon, Polygon};
use geojson::{Feature, FeatureCollection, Geometry, GeometryValue};
use oxigdal_core::buffer::RasterBuffer;
use serde_json::{Map, Value as JsonValue};
// use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use tracing::debug;

use crate::detection::GeoDetection;
use crate::error::{PostprocessingError, Result};
use crate::segmentation::SegmentationMask;

/// Applies confidence thresholding to a probability map
///
/// # Errors
/// Returns an error if thresholding fails
pub fn apply_threshold(probabilities: &RasterBuffer, threshold: f32) -> Result<RasterBuffer> {
    if !(0.0..=1.0).contains(&threshold) {
        return Err(PostprocessingError::InvalidThreshold { value: threshold }.into());
    }

    let mut result = probabilities.clone();

    for y in 0..probabilities.height() {
        for x in 0..probabilities.width() {
            let prob =
                probabilities
                    .get_pixel(x, y)
                    .map_err(|e| PostprocessingError::ExportFailed {
                        reason: format!("Failed to get probability: {}", e),
                    })?;

            let value = if prob >= threshold as f64 { 1.0 } else { 0.0 };

            result
                .set_pixel(x, y, value)
                .map_err(|e| PostprocessingError::ExportFailed {
                    reason: format!("Failed to set value: {}", e),
                })?;
        }
    }

    Ok(result)
}

/// Converts a binary mask to polygons using marching squares algorithm
///
/// # Errors
/// Returns an error if conversion fails
pub fn mask_to_polygons(mask: &RasterBuffer, min_area: f64) -> Result<Vec<Polygon>> {
    debug!(
        "Converting {}x{} mask to polygons",
        mask.width(),
        mask.height()
    );

    let mut polygons = Vec::new();

    // Simplified polygon extraction using contour tracing
    // A production implementation would use a proper marching squares algorithm
    let width = mask.width();
    let height = mask.height();

    let mut visited = vec![vec![false; width as usize]; height as usize];

    for y in 0..height {
        for x in 0..width {
            if visited[y as usize][x as usize] {
                continue;
            }

            let value =
                mask.get_pixel(x, y)
                    .map_err(|e| PostprocessingError::PolygonConversionFailed {
                        reason: format!("Failed to get pixel: {}", e),
                    })?;

            if value > 0.0 {
                let polygon = trace_contour(mask, x, y, &mut visited)?;
                let area = calculate_polygon_area(&polygon);

                if area >= min_area {
                    polygons.push(polygon);
                }
            }
        }
    }

    debug!("Extracted {} polygons", polygons.len());

    Ok(polygons)
}

/// Traces a contour starting from a point
fn trace_contour(
    mask: &RasterBuffer,
    start_x: u64,
    start_y: u64,
    visited: &mut [Vec<bool>],
) -> Result<Polygon> {
    let mut coords = Vec::new();

    // Simplified contour tracing - just creates a bounding box
    // A real implementation would do proper boundary following
    let mut min_x = start_x;
    let mut min_y = start_y;
    let mut max_x = start_x;
    let mut max_y = start_y;

    // Find extent of connected component
    let mut stack = vec![(start_x, start_y)];

    while let Some((x, y)) = stack.pop() {
        if x >= mask.width() || y >= mask.height() {
            continue;
        }

        if visited[y as usize][x as usize] {
            continue;
        }

        let value =
            mask.get_pixel(x, y)
                .map_err(|e| PostprocessingError::PolygonConversionFailed {
                    reason: format!("Failed to get pixel: {}", e),
                })?;

        if value > 0.0 {
            visited[y as usize][x as usize] = true;

            min_x = min_x.min(x);
            min_y = min_y.min(y);
            max_x = max_x.max(x);
            max_y = max_y.max(y);

            // Add neighbors
            if x > 0 {
                stack.push((x - 1, y));
            }
            if x + 1 < mask.width() {
                stack.push((x + 1, y));
            }
            if y > 0 {
                stack.push((x, y - 1));
            }
            if y + 1 < mask.height() {
                stack.push((x, y + 1));
            }
        }
    }

    // Create rectangle polygon
    coords.push(Coord {
        x: min_x as f64,
        y: min_y as f64,
    });
    coords.push(Coord {
        x: max_x as f64 + 1.0,
        y: min_y as f64,
    });
    coords.push(Coord {
        x: max_x as f64 + 1.0,
        y: max_y as f64 + 1.0,
    });
    coords.push(Coord {
        x: min_x as f64,
        y: max_y as f64 + 1.0,
    });
    coords.push(Coord {
        x: min_x as f64,
        y: min_y as f64,
    }); // Close the ring

    Ok(Polygon::new(LineString::from(coords), vec![]))
}

/// Calculates the area of a polygon
fn calculate_polygon_area(polygon: &Polygon) -> f64 {
    let coords = polygon.exterior().coords().collect::<Vec<_>>();
    if coords.len() < 3 {
        return 0.0;
    }

    let mut area = 0.0;
    for i in 0..coords.len() - 1 {
        area += coords[i].x * coords[i + 1].y - coords[i + 1].x * coords[i].y;
    }

    (area / 2.0).abs()
}

/// Exports detections to GeoJSON format
///
/// # Errors
/// Returns an error if export fails
pub fn export_detections_geojson<P: AsRef<Path>>(
    detections: &[GeoDetection],
    output_path: P,
) -> Result<()> {
    debug!("Exporting {} detections to GeoJSON", detections.len());

    let features: Vec<Feature> = detections.iter().map(detection_to_feature).collect();

    let collection = FeatureCollection {
        bbox: None,
        features,
        foreign_members: None,
    };

    let json = serde_json::to_string_pretty(&collection).map_err(|e| {
        PostprocessingError::ExportFailed {
            reason: format!("Failed to serialize GeoJSON: {}", e),
        }
    })?;

    let mut file =
        File::create(output_path.as_ref()).map_err(|e| PostprocessingError::ExportFailed {
            reason: format!("Failed to create output file: {}", e),
        })?;

    file.write_all(json.as_bytes())
        .map_err(|e| PostprocessingError::ExportFailed {
            reason: format!("Failed to write GeoJSON: {}", e),
        })?;

    debug!("Successfully exported detections");

    Ok(())
}

/// Converts a detection to a GeoJSON feature
fn detection_to_feature(det: &GeoDetection) -> Feature {
    let polygon = det.geo_bbox.to_polygon();

    let mut properties = Map::new();
    properties.insert(
        "class_id".to_string(),
        JsonValue::Number(det.detection.class_id.into()),
    );
    properties.insert(
        "confidence".to_string(),
        JsonValue::Number(
            serde_json::Number::from_f64(det.detection.confidence as f64)
                .unwrap_or_else(|| serde_json::Number::from(0)),
        ),
    );

    if let Some(ref label) = det.detection.class_label {
        properties.insert("class_label".to_string(), JsonValue::String(label.clone()));
    }

    for (key, value) in &det.detection.attributes {
        properties.insert(key.clone(), JsonValue::String(value.clone()));
    }

    Feature {
        bbox: None,
        geometry: Some(Geometry::new(GeometryValue::from(&polygon))),
        id: None,
        properties: Some(properties),
        foreign_members: None,
    }
}

/// Exports a segmentation mask to GeoJSON
///
/// # Errors
/// Returns an error if export fails
pub fn export_segmentation_geojson<P: AsRef<Path>>(
    mask: &SegmentationMask,
    output_path: P,
    min_area: f64,
) -> Result<()> {
    debug!("Exporting segmentation mask to GeoJSON");

    let polygons = mask_to_polygons(&mask.mask, min_area)?;

    let features: Vec<Feature> = polygons
        .iter()
        .enumerate()
        .map(|(i, poly)| {
            let mut properties = Map::new();
            properties.insert("id".to_string(), JsonValue::Number(i.into()));

            Feature {
                bbox: None,
                geometry: Some(Geometry::new(GeometryValue::from(poly))),
                id: None,
                properties: Some(properties),
                foreign_members: None,
            }
        })
        .collect();

    let collection = FeatureCollection {
        bbox: None,
        features,
        foreign_members: None,
    };

    let json = serde_json::to_string_pretty(&collection).map_err(|e| {
        PostprocessingError::ExportFailed {
            reason: format!("Failed to serialize GeoJSON: {}", e),
        }
    })?;

    let mut file =
        File::create(output_path.as_ref()).map_err(|e| PostprocessingError::ExportFailed {
            reason: format!("Failed to create output file: {}", e),
        })?;

    file.write_all(json.as_bytes())
        .map_err(|e| PostprocessingError::ExportFailed {
            reason: format!("Failed to write GeoJSON: {}", e),
        })?;

    debug!("Successfully exported segmentation");

    Ok(())
}

/// Simplifies polygons using the Douglas-Peucker algorithm
///
/// # Errors
/// Returns an error if simplification fails
pub fn simplify_polygons(polygons: &[Polygon], tolerance: f64) -> Result<Vec<Polygon>> {
    if tolerance < 0.0 {
        return Err(PostprocessingError::ExportFailed {
            reason: "Tolerance must be non-negative".to_string(),
        }
        .into());
    }

    // Simplified implementation - returns copy
    // A real implementation would use proper Douglas-Peucker algorithm
    Ok(polygons.to_vec())
}

/// Merges overlapping polygons
///
/// # Errors
/// Returns an error if merging fails
pub fn merge_polygons(polygons: &[Polygon]) -> Result<MultiPolygon> {
    // Simplified implementation
    // A real implementation would use proper geometry union operations
    Ok(MultiPolygon::new(polygons.to_vec()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxigdal_core::types::RasterDataType;
    use std::collections::HashMap;

    #[test]
    fn test_apply_threshold() {
        let probs = RasterBuffer::zeros(10, 10, RasterDataType::Float32);
        let result = apply_threshold(&probs, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_mask_to_polygons() {
        let mut mask = RasterBuffer::zeros(10, 10, RasterDataType::Float32);
        let _ = mask.set_pixel(5, 5, 1.0);
        let polygons = mask_to_polygons(&mask, 0.0);
        assert!(polygons.is_ok());
    }

    #[test]
    fn test_calculate_polygon_area() {
        let polygon = Polygon::new(
            LineString::from(vec![
                Coord { x: 0.0, y: 0.0 },
                Coord { x: 10.0, y: 0.0 },
                Coord { x: 10.0, y: 10.0 },
                Coord { x: 0.0, y: 10.0 },
                Coord { x: 0.0, y: 0.0 },
            ]),
            vec![],
        );

        let area = calculate_polygon_area(&polygon);
        assert!((area - 100.0).abs() < 1.0);
    }

    #[test]
    fn test_export_detections_geojson() {
        use crate::detection::{BoundingBox, Detection, GeoBoundingBox};
        use std::env;

        let temp_dir = env::temp_dir();
        let output_path = temp_dir.join("test_detections.geojson");

        let detections = vec![GeoDetection {
            detection: Detection {
                bbox: BoundingBox::new(0.0, 0.0, 10.0, 10.0),
                class_id: 0,
                class_label: Some("test".to_string()),
                confidence: 0.9,
                attributes: HashMap::new(),
            },
            geo_bbox: GeoBoundingBox {
                min_x: 0.0,
                min_y: 0.0,
                max_x: 10.0,
                max_y: 10.0,
            },
        }];

        let result = export_detections_geojson(&detections, &output_path);
        assert!(result.is_ok());

        // Clean up
        let _ = std::fs::remove_file(output_path);
    }
}