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
//! Label encoders.

use std::error::Error;

use udgraph::graph::Sentence;

pub mod categorical;

pub mod dependency;

pub mod depseq;

pub mod layer;

pub mod lemma;

/// An encoding with its probability.
#[derive(Debug)]
pub struct EncodingProb<E> {
    encoding: E,
    prob: f32,
}

impl<E> EncodingProb<E>
where
    E: ToOwned,
{
    /// Create an encoding with its probability.
    ///
    /// This constructor takes an owned encoding.
    pub fn new(encoding: E, prob: f32) -> Self {
        EncodingProb { encoding, prob }
    }

    /// Get the encoding.
    pub fn encoding(&self) -> &E {
        &self.encoding
    }

    /// Get the probability of the encoding.
    pub fn prob(&self) -> f32 {
        self.prob
    }
}

impl<E> From<EncodingProb<E>> for (String, f32)
where
    E: Clone + ToString,
{
    fn from(prob: EncodingProb<E>) -> Self {
        (prob.encoding().to_string(), prob.prob())
    }
}

/// Trait for sentence decoders.
///
/// A sentence decoder adds a representation to each token in a
/// sentence, such as a part-of-speech tag or a topological field.
pub trait SentenceDecoder {
    type Encoding: ToOwned;

    /// The decoding error type.
    type Error: Error;

    fn decode<S>(&self, labels: &[S], sentence: &mut Sentence) -> Result<(), Self::Error>
    where
        S: AsRef<[EncodingProb<Self::Encoding>]>;
}

/// Trait for sentence encoders.
///
/// A sentence encoder extracts a representation of each token in a
/// sentence, such as a part-of-speech tag or a topological field.
pub trait SentenceEncoder {
    type Encoding;

    /// The encoding error type.
    type Error: Error;

    /// Encode the given sentence.
    fn encode(&self, sentence: &Sentence) -> Result<Vec<Self::Encoding>, Self::Error>;
}