graphannis 4.1.4

This is a new backend implementation of the ANNIS linguistic search and visualization system.
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use crate::annis::db::aql::{model::AnnotationComponentType, operators::RangeSpec};
use crate::annis::db::exec::CostEstimate;
use crate::annis::errors::GraphAnnisError;
use crate::annis::operator::{
    BinaryOperator, BinaryOperatorBase, BinaryOperatorIndex, BinaryOperatorSpec,
    EdgeAnnoSearchSpec, EstimationType,
};
use crate::errors::Result;
use crate::graph::{GraphStatistic, GraphStorage, Match};
use crate::{AnnotationGraph, try_as_boxed_iter};
use graphannis_core::{
    graph::{ANNIS_NS, DEFAULT_ANNO_KEY, NODE_TYPE_KEY},
    types::{Component, Edge, NodeID},
};
use itertools::Itertools;
use std::collections::{HashSet, VecDeque};
use std::iter::FromIterator;
use std::sync::Arc;

#[derive(Clone, Debug)]
struct BaseEdgeOpSpec {
    pub components: Vec<Component<AnnotationComponentType>>,
    pub dist: RangeSpec,
    pub edge_anno: Option<EdgeAnnoSearchSpec>,
    pub is_reflexive: bool,
    pub op_str: Option<String>,
    pub inverse_operator_needs_cost_check: bool,
}

struct BaseEdgeOp {
    gs: Vec<Arc<dyn GraphStorage>>,
    spec: BaseEdgeOpSpec,
    max_nodes_estimate: usize,
    inverse: bool,
}

impl BaseEdgeOp {
    pub fn new(db: &AnnotationGraph, spec: BaseEdgeOpSpec) -> Result<BaseEdgeOp> {
        let mut gs: Vec<Arc<dyn GraphStorage>> = Vec::new();
        for c in &spec.components {
            let gs_for_component = db.get_graphstorage(c).ok_or_else(|| {
                GraphAnnisError::ImpossibleSearch(format!("Component {} does not exist", &c))
            })?;

            gs.push(gs_for_component);
        }

        let max_nodes_estimate = calculate_max_node_estimate(db, &spec, &gs, false)?;
        Ok(BaseEdgeOp {
            gs,
            spec,
            max_nodes_estimate,
            inverse: false,
        })
    }
}

fn calculate_max_node_estimate(
    db: &AnnotationGraph,
    spec: &BaseEdgeOpSpec,
    gs: &[Arc<dyn GraphStorage>],
    inverse: bool,
) -> Result<usize> {
    let all_components_are_partof = spec
        .components
        .iter()
        .all(|c| c.get_type() == AnnotationComponentType::PartOf);
    let max_nodes_estimate = if all_components_are_partof && gs.len() == 1 {
        // PartOf components have a very skewed distribution of root nodes vs.
        // the actual possible targets, thus do not use all nodes as population
        // but only the non-roots. We can only use this formula for the actual
        // @* operator, but not the inverted one.
        if !inverse && let Some(stats) = gs[0].get_statistics() {
            stats.nodes - stats.root_nodes
        } else {
            // Fallback to guessing how many nodes have the node type "corpus"
            // or "datasource" and thus could be reachable as RHS in a worst case
            // scenario. Since a node can't be part of itself, subtract 1 for
            // the node on the LHS.
            db.get_node_annos()
                .guess_max_count(
                    Some(&NODE_TYPE_KEY.ns),
                    &NODE_TYPE_KEY.name,
                    "corpus",
                    "datasource",
                )?
                .saturating_sub(1)
        }
    } else {
        db.get_node_annos().guess_max_count(
            Some(&NODE_TYPE_KEY.ns),
            &NODE_TYPE_KEY.name,
            "node",
            "node",
        )?
    };
    Ok(max_nodes_estimate)
}

impl BinaryOperatorSpec for BaseEdgeOpSpec {
    fn necessary_components(
        &self,
        _db: &AnnotationGraph,
    ) -> HashSet<Component<AnnotationComponentType>> {
        HashSet::from_iter(self.components.clone())
    }

    fn create_operator<'a>(
        &self,
        db: &'a AnnotationGraph,
        _cost_estimate: Option<(&CostEstimate, &CostEstimate)>,
    ) -> Result<BinaryOperator<'a>> {
        let optional_op = BaseEdgeOp::new(db, self.clone());
        optional_op.map(|op| BinaryOperator::Index(Box::new(op)))
    }

    fn get_edge_anno_spec(&self) -> Option<EdgeAnnoSearchSpec> {
        self.edge_anno.clone()
    }

    #[cfg(test)]
    fn into_any(self: Arc<Self>) -> Arc<dyn std::any::Any> {
        self
    }

    #[cfg(test)]
    fn any_ref(&self) -> &dyn std::any::Any {
        self
    }
}

fn check_edge_annotation(
    edge_anno: &Option<EdgeAnnoSearchSpec>,
    gs: &dyn GraphStorage,
    source: NodeID,
    target: NodeID,
) -> Result<bool> {
    match edge_anno {
        Some(EdgeAnnoSearchSpec::ExactValue { ns, name, val }) => {
            for a in gs
                .get_anno_storage()
                .get_annotations_for_item(&Edge { source, target })?
            {
                if name != &a.key.name {
                    continue;
                }
                if let Some(template_ns) = ns
                    && template_ns != &a.key.ns
                {
                    continue;
                }
                if let Some(template_val) = val
                    && template_val != &*a.val
                {
                    continue;
                }
                // all checks passed, this edge has the correct annotation
                return Ok(true);
            }
            Ok(false)
        }
        Some(EdgeAnnoSearchSpec::NotExactValue { ns, name, val }) => {
            for a in gs
                .get_anno_storage()
                .get_annotations_for_item(&Edge { source, target })?
            {
                if name != &a.key.name {
                    continue;
                }
                if let Some(template_ns) = ns
                    && template_ns != &a.key.ns
                {
                    continue;
                }
                if val.as_str() == a.val.as_str() {
                    continue;
                }

                // all checks passed, this edge has the correct annotation
                return Ok(true);
            }
            Ok(false)
        }
        Some(EdgeAnnoSearchSpec::RegexValue { ns, name, val }) => {
            let full_match_pattern = graphannis_core::util::regex_full_match(val);
            let re = regex::Regex::new(&full_match_pattern);
            if let Ok(re) = re {
                for a in gs
                    .get_anno_storage()
                    .get_annotations_for_item(&Edge { source, target })?
                {
                    if name != &a.key.name {
                        continue;
                    }
                    if let Some(template_ns) = ns
                        && template_ns != &a.key.ns
                    {
                        continue;
                    }

                    if !re.is_match(&a.val) {
                        continue;
                    }

                    // all checks passed, this edge has the correct annotation
                    return Ok(true);
                }
            }
            Ok(false)
        }
        Some(EdgeAnnoSearchSpec::NotRegexValue { ns, name, val }) => {
            let full_match_pattern = graphannis_core::util::regex_full_match(val);
            let re = regex::Regex::new(&full_match_pattern);
            if let Ok(re) = re {
                for a in gs
                    .get_anno_storage()
                    .get_annotations_for_item(&Edge { source, target })?
                {
                    if name != &a.key.name {
                        continue;
                    }
                    if let Some(template_ns) = ns
                        && template_ns != &a.key.ns
                    {
                        continue;
                    }

                    if re.is_match(&a.val) {
                        continue;
                    }

                    // all checks passed, this edge has the correct annotation
                    return Ok(true);
                }
            }
            Ok(false)
        }
        None => Ok(true),
    }
}

impl BaseEdgeOp {}

impl std::fmt::Display for BaseEdgeOp {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let anno_frag = if let Some(ref edge_anno) = self.spec.edge_anno {
            format!("[{}]", edge_anno)
        } else {
            String::from("")
        };

        if let Some(ref op_str) = self.spec.op_str {
            if self.inverse {
                write!(f, "{}\u{20D6}{}{}", op_str, self.spec.dist, anno_frag)
            } else {
                write!(f, "{}{}{}", op_str, self.spec.dist, anno_frag)
            }
        } else {
            write!(f, "?")
        }
    }
}

impl BinaryOperatorBase for BaseEdgeOp {
    fn filter_match(&self, lhs: &Match, rhs: &Match) -> Result<bool> {
        for e in &self.gs {
            if self.inverse {
                if e.is_connected(
                    rhs.node,
                    lhs.node,
                    self.spec.dist.min_dist(),
                    self.spec.dist.max_dist(),
                )? && check_edge_annotation(
                    &self.spec.edge_anno,
                    e.as_ref(),
                    rhs.node,
                    lhs.node,
                )? {
                    return Ok(true);
                }
            } else if e.is_connected(
                lhs.node,
                rhs.node,
                self.spec.dist.min_dist(),
                self.spec.dist.max_dist(),
            )? && check_edge_annotation(
                &self.spec.edge_anno,
                e.as_ref(),
                lhs.node,
                rhs.node,
            )? {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn is_reflexive(&self) -> bool {
        self.spec.is_reflexive
    }

    fn get_inverse_operator<'a>(
        &self,
        graph: &'a AnnotationGraph,
    ) -> Result<Option<BinaryOperator<'a>>> {
        let inverse = !self.inverse;

        // Check if all graph storages have the same inverse cost. If not, we
        // don't provide an inverse operator, because the plans would not
        // account for the different costs
        for g in &self.gs {
            if self.spec.inverse_operator_needs_cost_check && !g.inverse_has_same_cost() {
                return Ok(None);
            }
            if let Some(stat) = g.get_statistics() {
                // If input and output estimations are too different, also don't provide a more costly inverse operator
                if stat.inverse_fan_out_99_percentile > stat.fan_out_99_percentile {
                    return Ok(None);
                }
            }
        }
        let max_nodes_estimate = calculate_max_node_estimate(graph, &self.spec, &self.gs, inverse)?;
        let edge_op = BaseEdgeOp {
            gs: self.gs.clone(),
            spec: self.spec.clone(),
            max_nodes_estimate,
            inverse,
        };
        Ok(Some(BinaryOperator::Index(Box::new(edge_op))))
    }

    fn estimation_type(&self) -> Result<EstimationType> {
        if self.gs.is_empty() {
            // will not find anything
            return Ok(EstimationType::Selectivity(0.0));
        }

        let mut max_nodes: f64 = self.max_nodes_estimate as f64;
        // Avoid division by 0
        if max_nodes == 0.0 {
            max_nodes = 1.0;
        }

        let mut worst_sel: f64 = 0.0;

        for g in &self.gs {
            let g: &Arc<dyn GraphStorage> = g;

            let mut gs_selectivity = 0.01;

            if let Some(stats) = g.get_statistics() {
                let stats: &GraphStatistic = stats;
                if stats.cyclic {
                    // can get all other nodes
                    return Ok(EstimationType::Selectivity(1.0));
                }
                // get number of nodes reachable from min to max distance
                let max_dist = match self.spec.dist.max_dist() {
                    std::ops::Bound::Unbounded => usize::MAX,
                    std::ops::Bound::Included(max_dist) => max_dist,
                    std::ops::Bound::Excluded(max_dist) => max_dist - 1,
                };
                let max_path_length = std::cmp::min(max_dist, stats.max_depth) as i32;
                let min_path_length = std::cmp::max(0, self.spec.dist.min_dist() - 1) as i32;

                if stats.avg_fan_out > 1.0 {
                    // Assume two complete k-ary trees (with the average fan-out
                    // as k) as defined in "Thomas Cormen: Introduction to
                    // algorithms (2009), page 1179) with the maximum and
                    // minimum height. Calculate the number of nodes for both
                    // complete trees and subtract them to get an estimation of
                    // the number of nodes that fullfull the path length
                    // criteria.
                    let k = stats.avg_fan_out;

                    let reachable_max: f64 = ((k.powi(max_path_length) - 1.0) / (k - 1.0)).ceil();
                    let reachable_min: f64 = ((k.powi(min_path_length) - 1.0) / (k - 1.0)).ceil();

                    let reachable = reachable_max - reachable_min;

                    gs_selectivity = reachable / max_nodes;
                } else {
                    // We can't use the formula for complete k-ary trees because
                    // we can't divide by zero and don't want negative numbers.
                    // Use the simplified estimation with multiplication
                    // instead.
                    let reachable_max: f64 =
                        (stats.avg_fan_out * f64::from(max_path_length)).ceil();
                    let reachable_min: f64 =
                        (stats.avg_fan_out * f64::from(min_path_length)).ceil();

                    gs_selectivity = (reachable_max - reachable_min) / max_nodes;
                }
            }

            if worst_sel < gs_selectivity {
                worst_sel = gs_selectivity;
            }
        } // end for

        Ok(EstimationType::Selectivity(worst_sel))
    }

    fn edge_anno_selectivity(&self) -> Result<Option<f64>> {
        if let Some(ref edge_anno) = self.spec.edge_anno {
            let mut worst_sel = 0.0;
            for g in &self.gs {
                let g: &Arc<dyn GraphStorage> = g;
                let anno_storage = g.get_anno_storage();
                let num_of_annos = anno_storage.number_of_annotations()?;
                if num_of_annos == 0 {
                    // we won't be able to find anything if there are no
                    // annotations
                    return Ok(Some(0.0));
                } else {
                    let guessed_count = match edge_anno {
                        EdgeAnnoSearchSpec::ExactValue { val, ns, name } => {
                            if let Some(val) = val {
                                anno_storage.guess_max_count(
                                    ns.as_ref().map(String::as_str),
                                    name,
                                    val,
                                    val,
                                )?
                            } else {
                                anno_storage.number_of_annotations_by_name(
                                    ns.as_ref().map(String::as_str),
                                    name,
                                )?
                            }
                        }
                        EdgeAnnoSearchSpec::NotExactValue { val, ns, name } => {
                            let total = anno_storage.number_of_annotations_by_name(
                                ns.as_ref().map(String::as_str),
                                name,
                            )?;
                            total
                                - anno_storage.guess_max_count(
                                    ns.as_ref().map(String::as_str),
                                    name,
                                    val,
                                    val,
                                )?
                        }
                        EdgeAnnoSearchSpec::RegexValue { val, ns, name } => anno_storage
                            .guess_max_count_regex(ns.as_ref().map(String::as_str), name, val)?,
                        EdgeAnnoSearchSpec::NotRegexValue { val, ns, name } => {
                            let total = anno_storage.number_of_annotations_by_name(
                                ns.as_ref().map(String::as_str),
                                name,
                            )?;
                            total
                                - anno_storage.guess_max_count_regex(
                                    ns.as_ref().map(String::as_str),
                                    name,
                                    val,
                                )?
                        }
                    };
                    let g_sel: f64 = (guessed_count as f64) / (num_of_annos as f64);
                    if g_sel > worst_sel {
                        worst_sel = g_sel;
                    }
                }
            }
            Ok(Some(worst_sel))
        } else {
            Ok(Some(1.0))
        }
    }
}

impl BinaryOperatorIndex for BaseEdgeOp {
    fn retrieve_matches(&self, lhs: &Match) -> Box<dyn Iterator<Item = Result<Match>>> {
        let lhs = lhs.clone();
        let spec = self.spec.clone();

        if self.gs.len() == 1 {
            // directly return all matched nodes since when having only one component
            // no duplicates are possible
            let result: Result<VecDeque<_>> = if self.inverse {
                self.gs[0]
                    .find_connected_inverse(lhs.node, spec.dist.min_dist(), spec.dist.max_dist())
                    .fuse()
                    .map(move |candidate| {
                        let candidate = candidate?;
                        let has_annotation = check_edge_annotation(
                            &self.spec.edge_anno,
                            self.gs[0].as_ref(),
                            candidate,
                            lhs.node,
                        )?;
                        Ok((candidate, has_annotation))
                    })
                    .filter_map_ok(move |(n, has_annotation)| {
                        if has_annotation {
                            Some(Match {
                                node: n,
                                anno_key: DEFAULT_ANNO_KEY.clone(),
                            })
                        } else {
                            None
                        }
                    })
                    .collect()
            } else {
                self.gs[0]
                    .find_connected(lhs.node, spec.dist.min_dist(), spec.dist.max_dist())
                    .fuse()
                    .map(move |candidate| {
                        let candidate = candidate?;
                        let has_annotation = check_edge_annotation(
                            &self.spec.edge_anno,
                            self.gs[0].as_ref(),
                            lhs.node,
                            candidate,
                        )?;
                        Ok((candidate, has_annotation))
                    })
                    .filter_map_ok(move |(n, has_annotation)| {
                        if has_annotation {
                            Some(Match {
                                node: n,
                                anno_key: DEFAULT_ANNO_KEY.clone(),
                            })
                        } else {
                            None
                        }
                    })
                    .collect()
            };
            let result = try_as_boxed_iter!(result);
            Box::new(result.into_iter().map(Ok))
        } else {
            let all: Result<Vec<_>> = if self.inverse {
                self.gs
                    .iter()
                    .flat_map(move |e| {
                        let lhs = lhs.clone();

                        e.as_ref()
                            .find_connected_inverse(
                                lhs.node,
                                spec.dist.min_dist(),
                                spec.dist.max_dist(),
                            )
                            .fuse()
                            .map(move |candidate| {
                                let candidate = candidate?;
                                let has_annotation = check_edge_annotation(
                                    &self.spec.edge_anno,
                                    e.as_ref(),
                                    candidate,
                                    lhs.node,
                                )?;
                                Ok((candidate, has_annotation))
                            })
                            .filter_map_ok(move |(n, has_annotation)| {
                                if has_annotation {
                                    Some(Match {
                                        node: n,
                                        anno_key: DEFAULT_ANNO_KEY.clone(),
                                    })
                                } else {
                                    None
                                }
                            })
                    })
                    .collect()
            } else {
                self.gs
                    .iter()
                    .flat_map(move |e| {
                        let lhs = lhs.clone();

                        e.as_ref()
                            .find_connected(lhs.node, spec.dist.min_dist(), spec.dist.max_dist())
                            .fuse()
                            .map(move |candidate| {
                                let candidate = candidate?;
                                let has_annotation = check_edge_annotation(
                                    &self.spec.edge_anno,
                                    e.as_ref(),
                                    lhs.node,
                                    candidate,
                                )?;
                                Ok((candidate, has_annotation))
                            })
                            .filter_map_ok(move |(n, has_annotation)| {
                                if has_annotation {
                                    Some(Match {
                                        node: n,
                                        anno_key: DEFAULT_ANNO_KEY.clone(),
                                    })
                                } else {
                                    None
                                }
                            })
                    })
                    .collect()
            };
            let mut all = try_as_boxed_iter!(all);
            all.sort_unstable();
            all.dedup();
            Box::new(all.into_iter().map(Ok))
        }
    }

    fn as_binary_operator(&self) -> &dyn BinaryOperatorBase {
        self
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct DominanceSpec {
    pub name: String,
    pub dist: RangeSpec,
    pub edge_anno: Option<EdgeAnnoSearchSpec>,
}

impl BinaryOperatorSpec for DominanceSpec {
    fn necessary_components(
        &self,
        db: &AnnotationGraph,
    ) -> HashSet<Component<AnnotationComponentType>> {
        HashSet::from_iter(
            db.get_all_components(Some(AnnotationComponentType::Dominance), Some(&self.name)),
        )
    }

    fn create_operator<'a>(
        &self,
        db: &'a AnnotationGraph,
        cost_estimate: Option<(&CostEstimate, &CostEstimate)>,
    ) -> Result<BinaryOperator<'a>> {
        let components =
            db.get_all_components(Some(AnnotationComponentType::Dominance), Some(&self.name));
        let op_str = if self.name.is_empty() {
            String::from(">")
        } else {
            format!(">{} ", &self.name)
        };
        let base = BaseEdgeOpSpec {
            op_str: Some(op_str),
            components,
            dist: self.dist.clone(),
            edge_anno: self.edge_anno.clone(),
            is_reflexive: true,
            inverse_operator_needs_cost_check: true,
        };
        base.create_operator(db, cost_estimate)
    }

    #[cfg(test)]
    fn into_any(self: Arc<Self>) -> Arc<dyn std::any::Any> {
        self
    }

    #[cfg(test)]
    fn any_ref(&self) -> &dyn std::any::Any {
        self
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct PointingSpec {
    pub name: String,
    pub dist: RangeSpec,
    pub edge_anno: Option<EdgeAnnoSearchSpec>,
}

impl BinaryOperatorSpec for PointingSpec {
    fn necessary_components(
        &self,
        db: &AnnotationGraph,
    ) -> HashSet<Component<AnnotationComponentType>> {
        HashSet::from_iter(
            db.get_all_components(Some(AnnotationComponentType::Pointing), Some(&self.name)),
        )
    }

    fn create_operator<'a>(
        &self,
        db: &'a AnnotationGraph,
        cost_estimate: Option<(&CostEstimate, &CostEstimate)>,
    ) -> Result<BinaryOperator<'a>> {
        let components =
            db.get_all_components(Some(AnnotationComponentType::Pointing), Some(&self.name));
        let op_str = if self.name.is_empty() {
            String::from("->")
        } else {
            format!("->{} ", self.name)
        };

        let base = BaseEdgeOpSpec {
            components,
            dist: self.dist.clone(),
            edge_anno: self.edge_anno.clone(),
            is_reflexive: true,
            op_str: Some(op_str),
            inverse_operator_needs_cost_check: true,
        };
        base.create_operator(db, cost_estimate)
    }

    #[cfg(test)]
    fn into_any(self: Arc<Self>) -> Arc<dyn std::any::Any> {
        self
    }

    #[cfg(test)]
    fn any_ref(&self) -> &dyn std::any::Any {
        self
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct PartOfSubCorpusSpec {
    pub dist: RangeSpec,
}

impl BinaryOperatorSpec for PartOfSubCorpusSpec {
    fn necessary_components(
        &self,
        _db: &AnnotationGraph,
    ) -> HashSet<Component<AnnotationComponentType>> {
        let mut components = HashSet::default();
        components.insert(Component::new(
            AnnotationComponentType::PartOf,
            ANNIS_NS.into(),
            "".into(),
        ));
        components
    }

    fn create_operator<'a>(
        &self,
        db: &'a AnnotationGraph,
        cost_estimate: Option<(&CostEstimate, &CostEstimate)>,
    ) -> Result<BinaryOperator<'a>> {
        let components = vec![Component::new(
            AnnotationComponentType::PartOf,
            ANNIS_NS.into(),
            "".into(),
        )];
        let inverse_operator_needs_cost_check = if let Some((_, rhs)) = cost_estimate {
            // Only ignore different cost and risk a nested loop join if the RHS
            // has an estimated output size of 1 and thus a nested loop is not
            // as costly.
            rhs.output > 1
        } else {
            true
        };
        let base = BaseEdgeOpSpec {
            op_str: Some(String::from("@")),
            components,
            dist: self.dist.clone(),
            edge_anno: None,
            is_reflexive: false,
            inverse_operator_needs_cost_check,
        };

        base.create_operator(db, cost_estimate)
    }

    #[cfg(test)]
    fn into_any(self: Arc<Self>) -> Arc<dyn std::any::Any> {
        self
    }

    #[cfg(test)]
    fn any_ref(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(test)]
mod tests;