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
//! Triple type for knowledge graphs.
//!
//! A triple represents a (subject, predicate, object) statement.
use crate::{EntityId, Error, RelationType, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
/// A (subject, predicate, object) triple.
///
/// This is the fundamental unit of a knowledge graph.
///
/// # Example
///
/// ```rust
/// use lattix::Triple;
///
/// let triple = Triple::new("Apple", "founded_by", "Steve Jobs");
/// assert_eq!(triple.subject().as_str(), "Apple");
/// assert_eq!(triple.predicate().as_str(), "founded_by");
/// assert_eq!(triple.object().as_str(), "Steve Jobs");
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Triple {
/// Subject entity.
subject: EntityId,
/// Predicate (relation type).
predicate: RelationType,
/// Object entity.
object: EntityId,
/// Optional confidence score in `[0.0, 1.0]`. Defaults to `None`, which is
/// treated as full confidence (`1.0`) when the triple is added to a
/// [`KnowledgeGraph`].
confidence: Option<f32>,
/// Source document or provenance.
source: Option<String>,
}
impl Triple {
/// Create a new triple.
pub fn new(
subject: impl Into<EntityId>,
predicate: impl Into<RelationType>,
object: impl Into<EntityId>,
) -> Self {
Self {
subject: subject.into(),
predicate: predicate.into(),
object: object.into(),
confidence: None,
source: None,
}
}
/// Get the subject entity.
pub fn subject(&self) -> &EntityId {
&self.subject
}
/// Get the predicate (relation type).
pub fn predicate(&self) -> &RelationType {
&self.predicate
}
/// Get the object entity.
pub fn object(&self) -> &EntityId {
&self.object
}
/// Get the confidence score.
pub fn confidence(&self) -> Option<f32> {
self.confidence
}
/// Get the source/provenance.
pub fn source(&self) -> Option<&str> {
self.source.as_deref()
}
/// Set confidence score.
pub fn with_confidence(mut self, confidence: f32) -> Self {
self.confidence = Some(confidence.clamp(0.0, 1.0));
self
}
/// Set source/provenance.
pub fn with_source(mut self, source: impl Into<String>) -> Self {
self.source = Some(source.into());
self
}
/// Parse from N-Triples format.
///
/// Format: `<subject> <predicate> <object> .`
///
/// # Example
///
/// ```rust
/// use lattix::Triple;
///
/// let line = r#"<http://example.org/Apple> <http://example.org/founded_by> <http://example.org/Steve_Jobs> ."#;
/// let triple = Triple::from_ntriples(line).unwrap();
/// ```
pub fn from_ntriples(line: &str) -> Result<Self> {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return Err(Error::ParseTriple("Empty or comment line".into()));
}
// Simple N-Triples parser
// Format: <subject> <predicate> <object> .
// Handles IRIs (<...>), blank nodes (_:xxx), and literals ("...")
let mut parts = Vec::new();
let mut current = String::new();
let mut in_uri = false;
let mut in_literal = false;
let mut in_bnode = false;
let mut escape_next = false;
for c in line.chars() {
if escape_next {
current.push(c);
escape_next = false;
continue;
}
match c {
'\\' => {
escape_next = true;
current.push(c);
}
'<' if !in_literal && !in_bnode && current.is_empty() => {
in_uri = true;
}
// Datatype IRI in literal suffix: "42"^^<xsd:integer>
'<' if !in_literal && !in_bnode && !current.is_empty() => {
current.push(c);
}
'>' if in_uri && !in_literal => {
in_uri = false;
parts.push(current.clone());
current.clear();
}
// Closing > for datatype IRI in literal suffix
'>' if !in_uri && !in_literal && !current.is_empty() => {
current.push(c);
}
'"' if !in_uri && !in_bnode => {
in_literal = !in_literal;
current.push(c);
}
// Blank node: starts with _: when not inside another term
'_' if !in_uri && !in_literal && !in_bnode && current.is_empty() => {
in_bnode = true;
current.push(c);
}
// Blank node ends at whitespace
' ' | '\t' if in_bnode => {
in_bnode = false;
parts.push(current.clone());
current.clear();
}
// Whitespace outside any term: flush accumulated token (literal suffix, etc.)
' ' | '\t' if !in_uri && !in_literal && !in_bnode && !current.is_empty() => {
parts.push(current.clone());
current.clear();
}
'.' if !in_uri && !in_literal && !in_bnode && current.is_empty() => {
// End of triple
break;
}
_ if in_uri || in_literal || in_bnode => {
current.push(c);
}
// Accumulate literal suffixes (@en, ^^<datatype>) after closing quote
_ if !current.is_empty() => {
current.push(c);
}
_ => {}
}
}
if parts.len() < 3 {
return Err(Error::InvalidNTriples(format!(
"Expected 3 parts, got {}: {}",
parts.len(),
line
)));
}
Ok(Self::new(
parts[0].clone(),
parts[1].clone(),
parts[2].clone(),
))
}
/// Convert to N-Triples format.
pub fn to_ntriples(&self) -> String {
// Minimal RDF-ish rendering:
// - Named nodes (IRIs) are written as `<iri>`
// - Blank nodes are written as `_:id`
// - Literals are written as-is if `self.object` already starts with `"`
//
// This keeps `Triple` usable in both “simple KG” mode and the `formats` module
// (which may store literals in the object position).
fn render_iri_or_blank(s: &str) -> String {
if s.starts_with("_:") {
s.to_string()
} else if s.starts_with('<') && s.ends_with('>') {
// Accept bracketed form defensively.
s.to_string()
} else {
format!("<{}>", s)
}
}
fn render_object(s: &str) -> String {
if s.starts_with('"') || s.starts_with("_:") || (s.starts_with('<') && s.ends_with('>'))
{
s.to_string()
} else {
format!("<{}>", s)
}
}
format!(
"{} {} {} .",
render_iri_or_blank(self.subject.as_str()),
render_iri_or_blank(self.predicate.as_str()),
render_object(self.object.as_str())
)
}
}
impl fmt::Display for Triple {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {}, {})", self.subject, self.predicate, self.object)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_triple_creation() {
let t = Triple::new("Apple", "founded_by", "Steve Jobs");
assert_eq!(t.subject().as_str(), "Apple");
assert_eq!(t.predicate().as_str(), "founded_by");
assert_eq!(t.object().as_str(), "Steve Jobs");
}
#[test]
fn test_ntriples_roundtrip() {
let original = Triple::new(
"http://example.org/Apple",
"http://example.org/founded_by",
"http://example.org/Steve_Jobs",
);
let ntriples = original.to_ntriples();
let parsed = Triple::from_ntriples(&ntriples).unwrap();
assert_eq!(original.subject(), parsed.subject());
assert_eq!(original.predicate(), parsed.predicate());
assert_eq!(original.object(), parsed.object());
}
#[test]
fn test_parse_ntriples() {
let line = r#"<http://example.org/Apple> <http://example.org/type> <http://example.org/Company> ."#;
let triple = Triple::from_ntriples(line).unwrap();
assert_eq!(triple.subject().as_str(), "http://example.org/Apple");
assert_eq!(triple.predicate().as_str(), "http://example.org/type");
assert_eq!(triple.object().as_str(), "http://example.org/Company");
}
}