oca_bundle_semantics/state/oca/overlay/
attribute_framing.rs

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
use crate::state::{attribute::Attribute, oca::Overlay};
use isolang::Language;
use oca_ast_semantics::ast::OverlayType;
use said::derivation::HashFunctionCode;
use said::{sad::SerializationFormats, sad::SAD};
use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
use std::any::Any;
use std::collections::HashMap;

pub type Framing = HashMap<String, FramingScope>;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct FramingScope {
    pub predicate_id: String,
    pub framing_justification: String,
    #[serde(skip)]
    pub frame_meta: HashMap<String, String>,
}

pub trait Framings {
    fn set_framing(&mut self, id: String, framing: Framing);
}

impl Framings for Attribute {
    fn set_framing(&mut self, id: String, framing: Framing) {
        match self.framings {
            Some(ref mut framings) => {
                if let Some(f) = framings.get_mut(&id) {
                    f.extend(framing);
                } else {
                    framings.insert(id, framing);
                }
            }
            None => {
                let mut framings = HashMap::new();
                framings.insert(id, framing);
                self.framings = Some(framings);
            }
        }
    }
}

pub fn serialize_metadata<S>(
    metadata: &HashMap<String, String>,
    s: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    use std::collections::BTreeMap;

    let mut ser = s.serialize_map(Some(metadata.len()))?;
    let sorted_metadata: BTreeMap<_, _> = metadata.iter().collect();
    for (k, v) in sorted_metadata {
        ser.serialize_entry(k, v)?;
    }
    ser.end()
}

pub fn serialize_framing<S>(
    attributes: &HashMap<String, Framing>,
    s: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    use std::collections::BTreeMap;

    let mut ser = s.serialize_map(Some(attributes.len()))?;
    let sorted_attributes: BTreeMap<_, _> = attributes.iter().collect();
    for (k, v) in sorted_attributes {
        let sorted_framings: BTreeMap<_, _> = v.iter().collect();
        ser.serialize_entry(k, &sorted_framings)?;
    }
    ser.end()
}

#[derive(SAD, Serialize, Deserialize, Debug, Clone)]
pub struct AttributeFramingOverlay {
    #[said]
    #[serde(rename = "d")]
    said: Option<said::SelfAddressingIdentifier>,
    capture_base: Option<said::SelfAddressingIdentifier>,
    #[serde(rename = "type")]
    overlay_type: OverlayType,
    #[serde(rename = "framing_metadata", serialize_with = "serialize_metadata")]
    pub metadata: HashMap<String, String>,
    #[serde(serialize_with = "serialize_framing")]
    pub attribute_framing: HashMap<String, Framing>,
}

impl Overlay for AttributeFramingOverlay {
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn capture_base(&self) -> &Option<said::SelfAddressingIdentifier> {
        &self.capture_base
    }
    fn set_capture_base(&mut self, said: &said::SelfAddressingIdentifier) {
        self.capture_base = Some(said.clone());
    }
    fn overlay_type(&self) -> &OverlayType {
        &self.overlay_type
    }
    fn said(&self) -> &Option<said::SelfAddressingIdentifier> {
        &self.said
    }
    fn language(&self) -> Option<&Language> {
        None
    }
    fn attributes(&self) -> Vec<&String> {
        self.attribute_framing.keys().collect::<Vec<&String>>()
    }
    /// Add an attribute to the Label Overlay
    /// TODO add assignment of attribute to category
    fn add(&mut self, attribute: &Attribute) {
        if let Some(id) = self.metadata.get("frame_id") {
            if let Some(framing) = &attribute.framings {
                if let Some(value) = framing.get(id) {
                    self.attribute_framing
                        .insert(attribute.name.clone(), value.clone());

                    for framing_scope in value.values() {
                        for (k, v) in framing_scope.frame_meta.iter() {
                            self.metadata.insert(k.clone(), v.clone());
                        }
                    }
                }
            }
        }
    }
}

impl AttributeFramingOverlay {
    pub fn new(id: String) -> Self {
        let mut metadata = HashMap::new();
        metadata.insert("frame_id".to_string(), id);
        Self {
            capture_base: None,
            said: None,
            overlay_type: OverlayType::AttributeFraming,
            metadata,
            attribute_framing: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn create_attribute_framing_overlay() {
        let mut overlay = AttributeFramingOverlay::new("frame_id".to_string());
        let mut loc1 = HashMap::new();
        loc1.insert(
            "http://loc.1".to_string(),
            FramingScope {
                predicate_id: "skos:exactMatch".to_string(),
                framing_justification: "semapv:ManualMappingCuration"
                    .to_string(),
                frame_meta: HashMap::new(),
            },
        );
        let mut loc2 = HashMap::new();
        loc2.insert(
            "http://loc.2".to_string(),
            FramingScope {
                predicate_id: "skos:exactMatch".to_string(),
                framing_justification: "semapv:ManualMappingCuration"
                    .to_string(),
                frame_meta: HashMap::new(),
            },
        );
        let attr = cascade! {
            Attribute::new("attr1".to_string());
            ..set_framing("frame_id".to_string(), loc1);
            ..set_framing("frame_id".to_string(), loc2);
        };
        // even that attribute has 2 lagnuage only one attribute should be added to the overlay according to it's language
        overlay.add(&attr);

        assert_eq!(overlay.overlay_type, OverlayType::AttributeFraming);
        assert_eq!(overlay.attribute_framing.len(), 1);
    }
}