1#[derive(Clone, Debug, Default)]
6pub struct HealthStore {
7 raw_turtle: String,
8 triples: Vec<(String, String, String)>,
9}
10
11impl HealthStore {
12 pub fn new() -> Result<Self, String> {
14 Ok(Self {
15 raw_turtle: String::new(),
16 triples: Vec::new(),
17 })
18 }
19
20 pub fn load_turtle(&mut self, turtle: &str) -> Result<(), String> {
22 self.raw_turtle.push_str(turtle);
23 self.raw_turtle.push('\n');
24
25 let mut current_subj = String::new();
27 for line in turtle.lines() {
28 let trimmed = line.trim();
29 if trimmed.is_empty()
30 || trimmed.starts_with('@')
31 || trimmed.starts_with("PREFIX")
32 || trimmed.starts_with('#')
33 {
34 continue;
35 }
36
37 let tokens: Vec<&str> = trimmed.split_whitespace().collect();
39 if tokens.is_empty() {
40 continue;
41 }
42
43 let mut idx = 0;
44 if !line.starts_with(' ') && !line.starts_with('\t') && tokens.len() >= 3 {
46 current_subj = tokens[0].trim_matches(|c| c == '<' || c == '>').to_string();
47 idx = 1;
48 }
49
50 while idx + 1 < tokens.len() {
51 let pred = tokens[idx].trim_matches(|c| c == '<' || c == '>');
52 let obj =
53 tokens[idx + 1].trim_matches(|c| c == '<' || c == '>' || c == ';' || c == '.');
54
55 if !current_subj.is_empty() && !pred.is_empty() {
56 self.triples
57 .push((current_subj.clone(), pred.to_string(), obj.to_string()));
58 }
59 idx += 2;
60 if idx < tokens.len() && tokens[idx] == ";" {
61 idx += 1;
62 }
63 }
64 }
65 Ok(())
66 }
67
68 pub fn query(&self, sparql: &str) -> Result<String, String> {
70 let sparql_clean = sparql.trim();
71
72 if sparql_clean.starts_with("ASK") {
74 let is_violated = self.eval_ask(sparql_clean);
75 return Ok(format!("{{\"boolean\":{}}}", is_violated));
76 }
77
78 if sparql_clean.contains("AVG(") {
80 let avg_val = self.eval_avg(sparql_clean);
81 return match avg_val {
82 Some(val) => Ok(format!(
83 "{{\"head\":{{\"vars\":[\"avg\"]}},\"results\":{{\"bindings\":[{{\"avg\":{{\"type\":\"typed-literal\",\"datatype\":\"http://www.w3.org/2001/XMLSchema#double\",\"value\":\"{:.2}\"}}}}]}}}}",
84 val
85 )),
86 None => {
87 Ok("{\"head\":{\"vars\":[\"avg\"]},\"results\":{\"bindings\":[]}}".to_string())
88 }
89 };
90 }
91
92 if sparql_clean.contains("SELECT ?s") || sparql_clean.contains("SELECT ?obs") {
94 let mut matches = Vec::new();
95 for (s, p, o) in &self.triples {
96 if p == "a" && (o.contains("Observation") || sparql_clean.contains(o)) {
97 matches.push(s.clone());
98 }
99 }
100 if matches.is_empty() {
102 for line in self.raw_turtle.lines() {
103 if line.contains("Observation") {
104 if let Some(start) = line.find('<') {
105 if let Some(end) = line[start..].find('>') {
106 matches.push(line[start + 1..start + end].to_string());
107 }
108 }
109 }
110 }
111 }
112
113 let bindings: Vec<String> = matches
114 .into_iter()
115 .map(|m| format!("{{\"s\":{{\"type\":\"uri\",\"value\":\"{}\"}}}}", m))
116 .collect();
117 return Ok(format!(
118 "{{\"head\":{{\"vars\":[\"s\"]}},\"results\":{{\"bindings\":[{}]}}}}",
119 bindings.join(",")
120 ));
121 }
122
123 Ok("{\"head\":{\"vars\":[]},\"results\":{\"bindings\":[]}}".to_string())
125 }
126
127 fn eval_ask(&self, query: &str) -> bool {
128 for line in self.raw_turtle.lines() {
130 let trimmed = line.trim();
131 if query.contains("sleepEfficiency") && trimmed.contains("sleepEfficiency") {
133 if let Some(val) = extract_num_after(trimmed, "sleepEfficiency") {
134 if val < 0.0 || val > 100.0 {
135 return true;
136 }
137 }
138 }
139 if query.contains("bodyFatPercentage") && trimmed.contains("bodyFatPercentage") {
141 if let Some(val) = extract_num_after(trimmed, "bodyFatPercentage") {
142 if val < 0.0 || val > 100.0 {
143 return true;
144 }
145 }
146 }
147 if query.contains("Observation.valueQuantity")
149 && trimmed.contains("Observation.valueQuantity")
150 {
151 if let Some(val) = extract_num_after(trimmed, "Observation.valueQuantity") {
152 if query.contains("364075005") {
153 if val < 20.0 || val > 300.0 {
155 return true;
156 }
157 } else if query.contains("256235009") {
158 if val < 0.0 {
160 return true;
161 }
162 } else if val <= 0.0 {
163 return true;
164 }
165 }
166 }
167 }
168 false
169 }
170
171 fn eval_avg(&self, query: &str) -> Option<f64> {
172 let mut values = Vec::new();
173
174 if query.contains("sleepEfficiency") {
176 for line in self.raw_turtle.lines() {
177 if line.contains("sleepEfficiency") {
178 if let Some(v) = extract_num_after(line, "sleepEfficiency") {
179 values.push(v);
180 }
181 }
182 }
183 } else if query.contains("sleepHours") {
184 for line in self.raw_turtle.lines() {
185 if line.contains("sleepHours") {
186 if let Some(v) = extract_num_after(line, "sleepHours") {
187 values.push(v);
188 }
189 }
190 }
191 } else if query.contains("stressScore") {
192 for line in self.raw_turtle.lines() {
193 if line.contains("stressScore") {
194 if let Some(v) = extract_num_after(line, "stressScore") {
195 values.push(v);
196 }
197 }
198 }
199 } else if query.contains("maslowSafetyScore") {
200 for line in self.raw_turtle.lines() {
201 if line.contains("maslowSafetyScore") {
202 if let Some(v) = extract_num_after(line, "maslowSafetyScore") {
203 values.push(v);
204 }
205 }
206 }
207 } else if query.contains("364075005") {
208 values.extend(self.extract_quantities_for_concept("364075005"));
210 } else if query.contains("256235009") {
211 values.extend(self.extract_quantities_for_concept("256235009"));
213 }
214
215 if values.is_empty() {
216 None
217 } else {
218 let sum: f64 = values.iter().sum();
219 Some(sum / values.len() as f64)
220 }
221 }
222
223 fn extract_quantities_for_concept(&self, concept_id: &str) -> Vec<f64> {
224 let mut vals = Vec::new();
225 let mut in_target_block = false;
226
227 for line in self.raw_turtle.lines() {
228 if line.contains(concept_id) {
229 in_target_block = true;
230 }
231 if in_target_block {
232 if let Some(v) = extract_num_after(line, "Observation.valueQuantity") {
233 vals.push(v);
234 in_target_block = false;
235 } else if let Some(v) = extract_num_after(line, "valueQuantity") {
236 vals.push(v);
237 in_target_block = false;
238 }
239 }
240 if line.trim().ends_with('.') {
241 in_target_block = false;
242 }
243 }
244 vals
245 }
246
247 pub fn check_shape(
250 &mut self,
251 prefixes: &str,
252 turtle_data: &str,
253 ask_query: &str,
254 ) -> Result<bool, String> {
255 let full_ttl = format!("{}\n{}", prefixes, turtle_data);
256 self.load_turtle(&full_ttl)?;
257 let result = self.query(ask_query)?;
258 Ok(result.contains("true"))
259 }
260}
261
262fn extract_num_after(line: &str, key: &str) -> Option<f64> {
263 if let Some(idx) = line.find(key) {
264 let remainder = &line[idx + key.len()..];
265 let clean: String = remainder
267 .chars()
268 .map(|c| {
269 if c.is_ascii_digit() || c == '.' || c == '-' {
270 c
271 } else {
272 ' '
273 }
274 })
275 .collect();
276 for word in clean.split_whitespace() {
277 if let Ok(num) = word.parse::<f64>() {
278 return Some(num);
279 }
280 }
281 }
282 None
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288 use crate::rdf::generate_rdf_prefixes;
289
290 #[test]
291 fn test_load_and_query() {
292 let mut store = HealthStore::new().unwrap();
293 let ttl = format!(
294 "{}\n<urn:health:sleep:test1> a fhir:Observation ; health:sleepEfficiency 85 .\n",
295 generate_rdf_prefixes()
296 );
297 store.load_turtle(&ttl).unwrap();
298 let result = store
299 .query("SELECT ?s WHERE { ?s a <http://hl7.org/fhir/Observation> }")
300 .unwrap();
301 assert!(result.contains("sleep:test1"));
302 }
303
304 #[test]
305 fn test_ask_shape_violation() {
306 let mut store = HealthStore::new().unwrap();
307 let prefixes = generate_rdf_prefixes();
308 let data = "<urn:health:sleep:bad1> a <http://hl7.org/fhir/Observation> ; \
309 <https://health.example.org/ns#sleepEfficiency> 150 .";
310 let ask = "ASK { ?obs <https://health.example.org/ns#sleepEfficiency> ?e \
311 FILTER(?e < 0 || ?e > 100) }";
312 let violated = store.check_shape(&prefixes, data, ask).unwrap();
313 assert!(violated);
314 }
315}