annatto 0.50.1

Converts linguistic data formats based on the graphANNIS data model as intermediate representation and can apply consistency tests.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use std::collections::BTreeMap;

use anyhow::anyhow;
use facet::Facet;
use graphannis::{
    AnnotationGraph,
    graph::{AnnoKey, EdgeContainer, NodeID},
    model::{AnnotationComponent, AnnotationComponentType},
    update::{GraphUpdate, UpdateEvent},
};
use graphannis_core::{
    dfs::{CycleSafeDFS, DFSStep},
    graph::{ANNIS_NS, NODE_NAME_KEY, storage::union::UnionEdgeContainer},
};
use itertools::Itertools;
use serde::{Deserialize, Serialize};

use crate::{manipulator::Manipulator, progress::ProgressReporter, util::update_graph_silent};

/// This graph op can be used to split segment values into multiple sub nodes holding a character
/// or a predefined value.
///
/// Example:
/// ```toml
/// source_anno = "norm::norm"
/// mode = "char"
///
/// [horizontal]
/// source = { ctype = "Ordering", layer = "default_ns", name = "norm" }
/// minimal = { ctype = "Ordering", layer = "annis", name = "" }
/// ```
///
/// This splits value of "norm::norm" along the component of "Ordering/default_ns/norm" into characters.
#[derive(Clone, Deserialize, Facet, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DivideSegments {
    /// This determines which component provides the set of nodes whose values require a smaller division
    /// and in which component the divided nodes should be organized.
    /// These are usually two orderings with the minimal being the default ordering "Ordering/annis". If
    /// you want to use the default minimal you do not need to specify a value.
    ///
    /// Example:
    /// ```toml
    /// [[graph_op]]
    /// action = "divide"
    ///
    /// [graph_op.config.horizontal]
    /// source = { ctype = "Ordering", layer = "default_ns", name = "norm" }
    /// minimal = { ctype = "Ordering", layer = "annis", name = "" }
    /// ```
    horizontal: HorizontalTargets,
    #[serde(default)]
    /// Provide the vertical component type to build edges from old segments to new ones.
    /// Default is "Coverage", but also different component type or a list of components can be provided.
    vertical: VerticalTarget,
    /// The annotation holding the value that is used for splitting into characters when mode "char" is used.
    #[serde(with = "crate::estarde::anno_key")]
    source_anno: AnnoKey,
    /// The annotation holding the newly created value (depending on the chosen mode, see below).
    #[serde(with = "crate::estarde::anno_key", default = "default_target_anno")]
    target_anno: AnnoKey,
    /// There are two modes, "char" splits values stored in the source key into characters, alternatively a dummy value
    /// can be provided and the number of segments to be used.
    ///
    /// Example:
    /// ```toml
    /// target_anno = "annis::tok"
    /// mode = { n = 3, value = " " }  # three tokens with an empty space per retrieved segment.
    /// ```
    #[serde(default)]
    mode: DivideMode,
}

fn default_target_anno() -> AnnoKey {
    AnnoKey {
        name: "tok".to_string(),
        ns: ANNIS_NS.to_string(),
    }
}

#[derive(Clone, Default, Deserialize, Facet, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
#[repr(u8)]
enum DivideMode {
    #[default]
    #[serde(rename = "char")]
    Char,
    #[serde(untagged)]
    Num {
        n: usize,
        #[serde(default = "default_segment_value")]
        value: String,
    },
}

fn default_segment_value() -> String {
    " ".to_string()
}

impl DivideMode {
    fn resolve(&self, value: &str) -> Vec<String> {
        match self {
            DivideMode::Char => value.chars().map(|c| c.to_string()).collect(),
            DivideMode::Num { n, value } => vec![value.to_string(); *n],
        }
    }
}

#[derive(Clone, Deserialize, Facet, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct HorizontalTargets {
    #[serde(with = "crate::estarde::annotation_component")]
    source: AnnotationComponent,
    #[serde(
        default = "default_minimal",
        with = "crate::estarde::annotation_component"
    )]
    minimal: AnnotationComponent,
}

fn default_minimal() -> AnnotationComponent {
    AnnotationComponent::new(
        AnnotationComponentType::Ordering,
        ANNIS_NS.to_string(),
        "".to_string(),
    )
}

#[derive(Clone, Deserialize, Facet, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
#[repr(u8)]
enum VerticalTarget {
    Ctype(AnnotationComponentType),
    Components(
        #[serde(with = "crate::estarde::annotation_component::in_sequence")]
        Vec<AnnotationComponent>,
    ),
}

impl Default for VerticalTarget {
    fn default() -> Self {
        VerticalTarget::Ctype(AnnotationComponentType::Coverage)
    }
}

impl VerticalTarget {
    fn components(&self, graph: &AnnotationGraph) -> Vec<AnnotationComponent> {
        match self {
            VerticalTarget::Ctype(annotation_component_type) => {
                graph.get_all_components(Some(annotation_component_type.clone()), None)
            }
            VerticalTarget::Components(components) => components.clone(),
        }
    }
}

impl Manipulator for DivideSegments {
    fn manipulate_corpus(
        &self,
        graph: &mut AnnotationGraph,
        _workflow_directory: &std::path::Path,
        step_id: crate::StepID,
        tx: Option<crate::workflow::StatusSender>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if self.horizontal.minimal == self.horizontal.source {
            return Err(anyhow!("Horizontal components need to be distinct.").into());
        }
        let progress = ProgressReporter::new_unknown_total_work(tx, step_id)?;
        let mut update = GraphUpdate::default();
        {
            let source_gs = graph
                .get_graphstorage(&self.horizontal.source)
                .ok_or(anyhow!("No such component: {}", &self.horizontal.source))?;
            let source_node_sequences = {
                let roots = source_gs
                    .source_nodes()
                    .flatten()
                    .filter(|n| !source_gs.has_ingoing_edges(*n).unwrap_or_default());
                roots.map(|r| {
                    source_gs
                        .find_connected(r, 0, std::ops::Bound::Unbounded)
                        .flatten()
                })
            };

            graph.get_or_create_writable(&self.horizontal.minimal)?;
            let minimal_gs = graph
                .get_graphstorage(&self.horizontal.minimal)
                .ok_or(anyhow!("No such component: {}", &self.horizontal.minimal))?;
            let minimal_is_new = minimal_gs.as_edgecontainer().source_nodes().count() == 0;

            let vertical_gss = self
                .vertical
                .components(graph)
                .iter()
                .flat_map(|c| graph.get_graphstorage(c))
                .collect_vec();
            let vertical_container = UnionEdgeContainer::new(
                vertical_gss
                    .iter()
                    .map(|gs| gs.as_edgecontainer())
                    .collect_vec(),
            );

            let part_of_gs = graph
                .get_graphstorage(&AnnotationComponent::new(
                    AnnotationComponentType::PartOf,
                    ANNIS_NS.to_string(),
                    "".to_string(),
                ))
                .ok_or(anyhow!("There is no part of storage available."))?;

            let mut deleted_minimal_nodes: BTreeMap<NodeID, String> = BTreeMap::default();

            for node_sequence in source_node_sequences {
                let mut previous = None;
                for node in node_sequence {
                    let horizontal_node_name = graph
                        .get_node_annos()
                        .get_value_for_item(&node, &NODE_NAME_KEY)?
                        .unwrap_or_default();
                    let parent = part_of_gs
                        .find_connected(node, 1, std::ops::Bound::Included(1))
                        .next()
                        .ok_or(anyhow!(
                            "Node {horizontal_node_name} has no part of-parent."
                        ))??;
                    let parent_name = graph
                        .get_node_annos()
                        .get_value_for_item(&parent, &NODE_NAME_KEY)?
                        .ok_or(anyhow!("Parent has no name."))?;
                    let anno_value = graph
                        .get_node_annos()
                        .get_value_for_item(&node, &self.source_anno)?;
                    let node_name_stem = if let Some(frag) = horizontal_node_name.split("#").last()
                    {
                        frag.to_string()
                    } else {
                        chrono::Local::now().format("%M%S%9f").to_string()
                    };

                    if let Some(value) = &anno_value {
                        let new_values = self.mode.resolve(value);
                        let names = new_values.iter().enumerate().map(|(i, v)| {
                            format!("{parent_name}#divide_{node_name_stem}_{i}_{v}")
                                .trim()
                                .to_string()
                        });
                        let mut is_tok = false;
                        let (left_most, right_most) = if !vertical_container
                            .has_outgoing_edges(node)?
                        {
                            is_tok = true;
                            (node, node)
                        } else {
                            let vertically_reachable =
                                CycleSafeDFS::new(&vertical_container, node, 1, usize::MAX)
                                    .flatten()
                                    .filter_map(|DFSStep { node: n, .. }| {
                                        if !vertical_container
                                            .has_outgoing_edges(n)
                                            .unwrap_or_default()
                                            && (minimal_gs.has_ingoing_edges(n).unwrap_or_default()
                                                || minimal_gs
                                                    .has_outgoing_edges(n)
                                                    .unwrap_or_default())
                                        {
                                            Some(n)
                                        } else {
                                            None
                                        }
                                    })
                                    .collect_vec();
                            let mut ordered_nodes = Vec::with_capacity(vertically_reachable.len());
                            let mut start_index: usize = 0;
                            let l = vertically_reachable.len();
                            while ordered_nodes.len() < l && start_index < l {
                                ordered_nodes.clear();
                                let start_node = vertically_reachable[start_index];
                                minimal_gs
                                    .find_connected(start_node, 0, std::ops::Bound::Excluded(l))
                                    .flatten()
                                    .filter(|n| vertically_reachable.contains(n))
                                    .for_each(|n| ordered_nodes.push(n));
                                start_index += 1;
                            }
                            if ordered_nodes.len() < l {
                                return Err(anyhow!(
                                "Could not obtain ordered minimal nodes from vertical container."
                            )
                            .into());
                            }
                            (ordered_nodes[0], ordered_nodes[ordered_nodes.len() - 1])
                        };
                        if left_most != right_most {
                            // problematic case, especially in "char" mode
                            return Err(anyhow!(
                            "This graph op currently does not support the provided graph structure."
                        )
                        .into());
                        } else {
                            previous = if minimal_is_new && let Some(prev_id) = previous {
                                Some(prev_id)
                            } else if let Some(prev_id) = minimal_gs
                                .find_connected_inverse(left_most, 1, std::ops::Bound::Included(1))
                                .flatten()
                                .next()
                            {
                                deleted_minimal_nodes
                                    .get(&prev_id)
                                    .map(String::to_string)
                                    .or(graph
                                        .get_node_annos()
                                        .get_value_for_item(&prev_id, &NODE_NAME_KEY)?
                                        .map(|v| v.to_string()))
                            } else {
                                None
                            };
                            for (new_node, new_value) in names.zip_eq(&new_values) {
                                update.add_event(UpdateEvent::AddNode {
                                    node_name: new_node.to_string(),
                                    node_type: "node".to_string(),
                                })?;
                                if let Some(prev_name) = previous {
                                    update.add_event(UpdateEvent::AddEdge {
                                        source_node: prev_name,
                                        target_node: new_node.to_string(),
                                        layer: self.horizontal.minimal.layer.to_string(),
                                        component_type: self
                                            .horizontal
                                            .minimal
                                            .get_type()
                                            .to_string(),
                                        component_name: self.horizontal.minimal.name.to_string(),
                                    })?;
                                }
                                update.add_event(UpdateEvent::AddEdge {
                                    source_node: new_node.to_string(),
                                    target_node: parent_name.to_string(),
                                    layer: ANNIS_NS.to_string(),
                                    component_type: AnnotationComponentType::PartOf.to_string(),
                                    component_name: "".to_string(),
                                })?;
                                update.add_event(UpdateEvent::AddNodeLabel {
                                    node_name: new_node.to_string(),
                                    anno_ns: self.target_anno.ns.to_string(),
                                    anno_name: self.target_anno.name.to_string(),
                                    anno_value: new_value.to_string(),
                                })?;
                                update.add_event(UpdateEvent::AddEdge {
                                    source_node: horizontal_node_name.to_string(),
                                    target_node: new_node.to_string(),
                                    layer: ANNIS_NS.to_string(),
                                    component_type: AnnotationComponentType::Coverage.to_string(),
                                    component_name: "".to_string(),
                                })?;
                                previous = Some(new_node);
                            }
                            if let Some(name) = &previous
                                && !is_tok
                            {
                                update.add_event(UpdateEvent::DeleteNode {
                                    node_name: graph
                                        .get_node_annos()
                                        .get_value_for_item(&left_most, &NODE_NAME_KEY)?
                                        .ok_or(anyhow!("No has no name."))?
                                        .to_string(),
                                })?;
                                deleted_minimal_nodes.insert(right_most, name.to_string());
                                // just in case the successor of left_most (== right_most) prevails,
                                // it needs to be integrated.
                                // If it gets deleted in the process, the edge will be, too
                                if let Some(successor_id) = minimal_gs
                                    .find_connected(left_most, 1, std::ops::Bound::Included(1))
                                    .flatten()
                                    .next()
                                {
                                    let successor_name = graph
                                        .get_node_annos()
                                        .get_value_for_item(&successor_id, &NODE_NAME_KEY)?
                                        .ok_or(anyhow!("Node has no name"))?
                                        .to_string();
                                    update.add_event(UpdateEvent::AddEdge {
                                        source_node: name.to_string(),
                                        target_node: successor_name,
                                        layer: self.horizontal.minimal.layer.to_string(),
                                        component_type: self
                                            .horizontal
                                            .minimal
                                            .get_type()
                                            .to_string(),
                                        component_name: self.horizontal.minimal.name.to_string(),
                                    })?;
                                }
                            }
                        }
                    } else {
                        progress.warn(format!(
                            "Source node {horizontal_node_name} has no value for key {}:{}",
                            self.source_anno.ns, self.source_anno.name
                        ))?;
                        continue;
                    }
                }
            }
        }
        update_graph_silent(graph, &mut update)?;
        Ok(())
    }

    fn requires_statistics(&self) -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use graphannis::AnnotationGraph;
    use insta::assert_snapshot;

    use crate::{
        exporter::graphml::GraphMLExporter,
        importer::{Importer, treetagger::ImportTreeTagger, xlsx::ImportSpreadsheet},
        manipulator::{Manipulator, divide::DivideSegments},
        test_util::export_to_string,
    };

    #[test]
    fn single_tok() {
        let import: Result<ImportTreeTagger, _> =
            toml::from_str(r#"column_names = ["annis::tok", "default_ns::pos"]"#);
        assert!(import.is_ok());
        let import = import.unwrap();
        let g = AnnotationGraph::with_default_graphstorages(false);
        assert!(g.is_ok());
        let mut graph = g.unwrap();
        let u = import.import_corpus(
            Path::new("tests/data/graph_op/divide/single-tok/"),
            crate::StepID {
                module_name: "test_import".to_string(),
                path: None,
            },
            import.default_configuration(),
            None,
        );
        assert!(u.is_ok());
        assert!(graph.apply_update(&mut u.unwrap(), |_| {}).is_ok());
        let manip: Result<DivideSegments, _> = toml::from_str(
            r#"
        source_anno = "annis::tok"
        mode = "char"

        [horizontal]
        source = { ctype = "Ordering", layer = "annis", name = "" }
        minimal = { ctype = "Ordering", layer = "annis", name = "new" }
        "#,
        );
        assert!(
            manip.is_ok(),
            "Err deserializing: {:?}",
            manip.err().unwrap()
        );
        let manip = manip.unwrap();
        let appl = manip.manipulate_corpus(
            &mut graph,
            Path::new("./"),
            crate::StepID {
                module_name: "test_divide".to_string(),
                path: None,
            },
            None,
        );
        assert!(
            appl.is_ok(),
            "Error performing divide: {:?}",
            appl.err().unwrap()
        );
        let exporter: Result<GraphMLExporter, _> = toml::from_str("stable_order = true");
        assert!(exporter.is_ok());
        let exporter = exporter.unwrap();
        assert_snapshot!(export_to_string(&graph, exporter).unwrap());
    }

    #[test]
    fn offset_tok() {
        let import: Result<ImportSpreadsheet, _> = toml::from_str(
            r#"
            [column_map]
            norm = ["pos", "lemma"]
            "#,
        );
        assert!(import.is_ok());
        let import = import.unwrap();
        let g = AnnotationGraph::with_default_graphstorages(false);
        assert!(g.is_ok());
        let mut graph = g.unwrap();
        let u = import.import_corpus(
            Path::new("tests/data/graph_op/divide/offset-tok/"),
            crate::StepID {
                module_name: "test_import".to_string(),
                path: None,
            },
            import.default_configuration(),
            None,
        );
        assert!(u.is_ok());
        assert!(graph.apply_update(&mut u.unwrap(), |_| {}).is_ok());
        let manip: Result<DivideSegments, _> = toml::from_str(
            r#"
        source_anno = "norm::norm"
        mode = "char"

        [horizontal]
        source = { ctype = "Ordering", layer = "default_ns", name = "norm" }
        minimal = { ctype = "Ordering", layer = "annis", name = "" }
        "#,
        );
        assert!(
            manip.is_ok(),
            "Err deserializing: {:?}",
            manip.err().unwrap()
        );
        let manip = manip.unwrap();
        let appl = manip.manipulate_corpus(
            &mut graph,
            Path::new("./"),
            crate::StepID {
                module_name: "test_divide".to_string(),
                path: None,
            },
            None,
        );
        assert!(
            appl.is_ok(),
            "Error performing divide: {:?}",
            appl.err().unwrap()
        );
        let exporter: Result<GraphMLExporter, _> = toml::from_str("stable_order = true");
        assert!(exporter.is_ok());
        let exporter = exporter.unwrap();
        assert_snapshot!(export_to_string(&graph, exporter).unwrap());
    }

    #[test]
    fn offset_tok_fixed_n() {
        let import: Result<ImportSpreadsheet, _> = toml::from_str(
            r#"
            [column_map]
            norm = ["pos", "lemma"]
            "#,
        );
        assert!(import.is_ok());
        let import = import.unwrap();
        let g = AnnotationGraph::with_default_graphstorages(false);
        assert!(g.is_ok());
        let mut graph = g.unwrap();
        let u = import.import_corpus(
            Path::new("tests/data/graph_op/divide/offset-tok/"),
            crate::StepID {
                module_name: "test_import".to_string(),
                path: None,
            },
            import.default_configuration(),
            None,
        );
        assert!(u.is_ok());
        assert!(graph.apply_update(&mut u.unwrap(), |_| {}).is_ok());
        let manip: Result<DivideSegments, _> = toml::from_str(
            r#"
        source_anno = "norm::norm"
        mode = { n = 3, value = " " }

        [horizontal]
        source = { ctype = "Ordering", layer = "default_ns", name = "norm" }
        minimal = { ctype = "Ordering", layer = "annis", name = "" }
        "#,
        );
        assert!(
            manip.is_ok(),
            "Err deserializing: {:?}",
            manip.err().unwrap()
        );
        let manip = manip.unwrap();
        let appl = manip.manipulate_corpus(
            &mut graph,
            Path::new("./"),
            crate::StepID {
                module_name: "test_divide".to_string(),
                path: None,
            },
            None,
        );
        assert!(
            appl.is_ok(),
            "Error performing divide: {:?}",
            appl.err().unwrap()
        );
        let exporter: Result<GraphMLExporter, _> = toml::from_str("stable_order = true");
        assert!(exporter.is_ok());
        let exporter = exporter.unwrap();
        assert_snapshot!(export_to_string(&graph, exporter).unwrap());
    }

    #[test]
    fn multi_tok_err() {
        let import: Result<ImportSpreadsheet, _> = toml::from_str(
            r#"
            [column_map]
            dipl = ["sentence", "seg"]
            norm = ["pos", "lemma"]
            "#,
        );
        assert!(import.is_ok());
        let import = import.unwrap();
        let g = AnnotationGraph::with_default_graphstorages(false);
        assert!(g.is_ok());
        let mut graph = g.unwrap();
        let u = import.import_corpus(
            Path::new("tests/data/graph_op/divide/multi-tok/"),
            crate::StepID {
                module_name: "test_import".to_string(),
                path: None,
            },
            import.default_configuration(),
            None,
        );
        assert!(u.is_ok());
        assert!(graph.apply_update(&mut u.unwrap(), |_| {}).is_ok());
        let manip: Result<DivideSegments, _> = toml::from_str(
            r#"
        source_anno = "norm::norm"
        mode = "char"

        [horizontal]
        source = { ctype = "Ordering", layer = "default_ns", name = "norm" }
        minimal = { ctype = "Ordering", layer = "annis", name = "" }
        "#,
        );
        assert!(
            manip.is_ok(),
            "Err deserializing: {:?}",
            manip.err().unwrap()
        );
        let manip = manip.unwrap();
        let appl = manip.manipulate_corpus(
            &mut graph,
            Path::new("./"),
            crate::StepID {
                module_name: "test_divide".to_string(),
                path: None,
            },
            None,
        );
        assert!(appl.is_err());
    }
}