copernicus_viewer 0.2.0

GUI viewer and library for inspecting and comparing EOPF Zarr products from the Copernicus ecosystem
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
//! Product comparison logic (ported from sentineltoolbox `compare_product_datatrees`).

use crate::product::Product;

use super::data::{
    DataReport, compare_variable_data, format_variable_detail, global_relative_score,
};
use super::flags::{FlagReport, compare_flag_variables, global_flag_score as median_flag_score};
use super::options::CompareOptions;
use super::product_label;
use super::structure::{
    StructureReport, StructureStatus, collect_data_variables, collect_flag_variables,
    compare_structure, is_comparable_for_comparison,
};

pub use super::options::CompareOptions as ComparisonOptions;

/// Outcome of comparing two open EOPF Zarr products.
#[derive(Clone, Debug)]
pub struct ComparisonResult {
    /// Display label for the reference product (final path segment).
    pub reference_label: String,
    /// Display label for the new product.
    pub new_label: String,
    /// Pre-formatted summary report (non-verbose).
    pub summary: String,
    /// Overall pass when structure, data, and flags all succeed.
    pub success: bool,
    /// Whether the new product contains every comparable (non-coordinate) array from the reference.
    pub isomorphic: bool,
    /// `true` when fatal structure differences prevented data comparison.
    pub skip_data: bool,
    /// Structure and metadata comparison details.
    pub structure: StructureReport,
    /// Measurement variable data comparison details.
    pub data: DataReport,
    /// CF flag variable comparison details.
    pub flags: FlagReport,
    /// Median relative score across variables (relative mode only).
    pub global_score: Option<f64>,
    /// Median equal-percentage score across flag variables.
    pub global_flag_score: Option<f64>,
    /// Outlier ratio threshold used for this run.
    pub threshold_nb_outliers: f64,
    /// Coverage difference threshold used for this run.
    pub threshold_coverage: f64,
}

impl ComparisonResult {
    /// Re-format the report; set `verbose` to list every variable and flag bit.
    pub fn formatted_summary(&self, verbose: bool) -> String {
        format_summary(self, verbose)
    }
}

/// Compare two loaded EOPF Zarr products using default sentineltoolbox thresholds.
pub fn compare_products(left: &Product, right: &Product) -> ComparisonResult {
    compare_products_with_options(left, right, &CompareOptions::default())
}

/// Compare two loaded products with explicit options.
pub fn compare_products_with_options(
    left: &Product,
    right: &Product,
    options: &CompareOptions,
) -> ComparisonResult {
    compare_product_trees(left, right, options)
}

/// Rust port of `compare_product_datatrees` (structure, data, flags).
fn compare_product_trees(
    left: &Product,
    right: &Product,
    options: &CompareOptions,
) -> ComparisonResult {
    let left_label = product_label(left);
    let right_label = product_label(right);

    let isomorphic = is_comparable_for_comparison(&left.tree().root, &right.tree().root);
    if !isomorphic {
        let result = ComparisonResult {
            reference_label: left_label,
            new_label: right_label,
            summary: String::new(),
            success: false,
            isomorphic: false,
            skip_data: true,
            structure: StructureReport::default(),
            data: DataReport::default(),
            flags: FlagReport::default(),
            global_score: None,
            global_flag_score: None,
            threshold_nb_outliers: options.threshold_nb_outliers,
            threshold_coverage: options.threshold_coverage,
        };
        return ComparisonResult {
            summary: result.formatted_summary(false),
            ..result
        };
    }

    let mut skip_data = false;
    let structure = if options.structure {
        let report = compare_structure(left, right, options);
        skip_data = report.skip_data_comparison;
        report
    } else {
        StructureReport::default()
    };

    let data_paths = collect_data_variables(&left.tree().root);
    let flag_paths = collect_flag_variables(&left.tree().root);

    let data = if options.data && !skip_data {
        compare_variable_data(left, right, &data_paths, options)
    } else {
        DataReport::default()
    };

    let flags = if options.flags && !skip_data {
        compare_flag_variables(left, right, &flag_paths, options)
    } else {
        FlagReport::default()
    };

    let global_score = if options.relative {
        global_relative_score(&data)
    } else {
        None
    };
    let global_flag_score = median_flag_score(&flags);

    let success = isomorphic
        && structure.failed_count() == 0
        && data.failed_count() == 0
        && flags.failed_count() == 0
        && !skip_data;

    let mut result = ComparisonResult {
        reference_label: left_label,
        new_label: right_label,
        summary: String::new(),
        success,
        isomorphic,
        skip_data,
        structure,
        data,
        flags,
        global_score,
        global_flag_score,
        threshold_nb_outliers: options.threshold_nb_outliers,
        threshold_coverage: options.threshold_coverage,
    };
    result.summary = result.formatted_summary(false);
    result
}

fn format_summary(result: &ComparisonResult, verbose: bool) -> String {
    let left = &result.reference_label;
    let right = &result.new_label;
    let structure = &result.structure;
    let data = &result.data;
    let flags = &result.flags;

    let mut lines = vec![
        format!("Compare “{right}” to reference “{left}"),
        format!(
            "Overall: {}",
            if result.success { "PASSED" } else { "FAILED" }
        ),
    ];

    if !result.isomorphic {
        lines.push(
            "Products are not comparable (reference arrays missing in new product).".to_string(),
        );
        return lines.join("\n");
    }

    if result.skip_data {
        lines.push(
            "Fatal structure differences — variable data comparison was skipped.".to_string(),
        );
    }

    lines.push(format!(
        "Structure: {} passed, {} warnings, {} failed",
        structure.passed_count(),
        structure.warning_count(),
        structure.failed_count()
    ));
    for issue in structure
        .issues
        .iter()
        .filter(|i| i.status == StructureStatus::Warning)
        .take(8)
    {
        lines.push(format!(
            "  ⚠ [{}][{}] {}",
            issue.path, issue.field, issue.detail
        ));
    }
    for issue in structure
        .issues
        .iter()
        .filter(|i| {
            matches!(
                i.status,
                StructureStatus::Failed | StructureStatus::MissingInNew
            )
        })
        .take(12)
    {
        lines.push(format!(
            "  ✗ [{}][{}] {}",
            issue.path, issue.field, issue.detail
        ));
    }
    if structure.failed_count() > 12 {
        lines.push(format!(
            "  … and {} more structure issues",
            structure.failed_count() - 12
        ));
    }

    lines.push(format!(
        "Variables: {} passed, {} failed, {} skipped",
        data.passed_count(),
        data.failed_count(),
        data.skipped_count()
    ));
    for skipped in data.skipped.iter().take(8) {
        lines.push(format!("{}{}", skipped.path, skipped.reason));
    }
    if data.skipped_count() > 8 {
        lines.push(format!(
            "  … and {} more skipped variables",
            data.skipped_count() - 8
        ));
    }
    let failed_vars: Vec<_> = data.variables.iter().filter(|v| !v.passed).collect();
    let passed_vars: Vec<_> = data.variables.iter().filter(|v| v.passed).collect();
    let failed_limit = if verbose {
        failed_vars.len()
    } else {
        failed_vars.len().min(12)
    };
    let passed_limit = if verbose {
        passed_vars.len()
    } else {
        passed_vars.len().min(6)
    };

    for var in failed_vars.iter().take(failed_limit) {
        lines.push(format!(
            "{}",
            format_variable_detail(var, result.threshold_nb_outliers, result.threshold_coverage)
        ));
    }
    if failed_vars.len() > failed_limit {
        lines.push(format!(
            "  … and {} more failed variables",
            failed_vars.len() - failed_limit
        ));
    }

    if !passed_vars.is_empty() && !verbose && failed_vars.is_empty() {
        lines.push("  (passed variables omitted — use --verbose to list them)".to_string());
    } else if !passed_vars.is_empty() && !verbose && !failed_vars.is_empty() {
        lines.push("  Passed:".to_string());
    }

    for var in passed_vars.iter().take(passed_limit) {
        if verbose {
            lines.push(format!(
                "{}",
                format_variable_detail(
                    var,
                    result.threshold_nb_outliers,
                    result.threshold_coverage
                )
            ));
        } else {
            lines.push(format!("{}", var.path));
        }
    }
    if passed_vars.len() > passed_limit {
        lines.push(format!(
            "  … and {} more passed variables (use --verbose to list all)",
            passed_vars.len() - passed_limit
        ));
    }

    lines.push(format!(
        "Flags: {} bits passed, {} bits failed",
        flags.passed_count(),
        flags.failed_count()
    ));
    for var in flags.variables.iter() {
        for bit in var.bits.iter().filter(|b| !b.passed) {
            lines.push(format!(
                "{}{} different {:.2}%",
                var.path, bit.meaning, bit.different_percentage
            ));
        }
    }
    if verbose {
        for var in flags.variables.iter() {
            for bit in var.bits.iter().filter(|b| b.passed) {
                lines.push(format!(
                    "{}{} equal {:.2}%",
                    var.path, bit.meaning, bit.equal_percentage
                ));
            }
        }
    }

    if let Some(score) = result.global_score {
        lines.push(format!("Global relative score: {score:.6}%"));
    }
    if let Some(score) = result.global_flag_score {
        lines.push(format!("Global flag score (median): {score:.6}%"));
    }

    lines.join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::product::open_product;
    use std::path::Path;

    #[test]
    fn identical_sample_products_pass() {
        let path = Path::new("sample_data/S03OLCEFR_sample.zarr");
        if !path.exists() {
            return;
        }

        let left = open_product(path.to_str().unwrap()).expect("open left");
        let right = open_product(path.to_str().unwrap()).expect("open right");
        let result = compare_products(&left, &right);
        assert!(result.isomorphic);
        assert!(result.success, "{}", result.summary);
    }

    #[test]
    fn slstr_products_compare_data_variables() {
        let ref_path = Path::new(
            "/tmp/s3slstr_data_verification/reference/fixed/S03SLSLST_20230514T074253_0180_A377_SBBE.zarr",
        );
        let new_path = Path::new(
            "/tmp/s3slstr_data_verification/output_dpr/S03SLSLST_20230514T074253_0180_A377_S000.zarr",
        );
        if !ref_path.exists() || !new_path.exists() {
            return;
        }

        let left = open_product(ref_path.to_str().unwrap()).expect("open reference");
        let right = open_product(new_path.to_str().unwrap()).expect("open new");
        let result = compare_products(&left, &right);

        assert!(result.isomorphic, "{}", result.summary);
        assert!(
            !result.skip_data,
            "data comparison should not be skipped: {}",
            result.summary
        );
        assert!(
            !result.data.variables.is_empty(),
            "expected compared variables: {}",
            result.summary
        );
    }

    #[cfg(feature = "safe")]
    #[test]
    fn slstr_zarr_and_safe_products_are_comparable() {
        let ref_path =
            Path::new("/home/vincent/Data/SLSTR/S03SLSLST_20260622T102053_0180_A008_T96C.zarr");
        let new_path = Path::new(
            "/home/vincent/Data/SLSTR/S3A_SL_2_LST____20260622T102053_20260622T102353_20260622T123949_0179_141_008_2160_PS1_O_NR_005.SEN3",
        );
        if !ref_path.exists() || !new_path.exists() {
            return;
        }

        let left = open_product(ref_path.to_str().unwrap()).expect("open zarr reference");
        let right = open_product(new_path.to_str().unwrap()).expect("open safe new");
        let result = compare_products(&left, &right);

        assert!(result.isomorphic, "{}", result.summary);
        assert!(
            !result.skip_data,
            "data comparison should not be skipped: {}",
            result.summary
        );
        assert!(
            !result.data.variables.is_empty(),
            "expected compared variables: {}",
            result.summary
        );
    }
}