comparison service/mqtt_to_rdf/inference/inference_functions.py @ 1727:23e6154e6c11

file moves
author drewp@bigasterisk.com
date Tue, 20 Jun 2023 23:26:24 -0700
parents service/mqtt_to_rdf/inference_functions.py@7a61113fd17d
children
comparison
equal deleted inserted replaced
1726:7d3797ed6681 1727:23e6154e6c11
1 """
2 Some of these are from https://www.w3.org/2000/10/swap/doc/CwmBuiltins
3 """
4 import urllib.parse
5 from decimal import Decimal
6 from typing import Optional, cast
7
8 from rdflib import Literal, Namespace, URIRef
9
10 from inference.candidate_binding import CandidateBinding
11 from inference.lhs_evaluation import (ListFunction, SubjectFunction, SubjectObjectFunction, register)
12
13 MATH = Namespace('http://www.w3.org/2000/10/swap/math#')
14 ROOM = Namespace("http://projects.bigasterisk.com/room/")
15
16
17 @register
18 class Gt(SubjectObjectFunction):
19 pred = MATH['greaterThan']
20
21 def bind(self, existingBinding: CandidateBinding) -> Optional[CandidateBinding]:
22 [x, y] = self.getNumericOperands(existingBinding)
23 if x > y:
24 return CandidateBinding({}) # no new values; just allow matching to keep going
25
26
27 @register
28 class AsFarenheit(SubjectFunction):
29 pred = ROOM['asFarenheit']
30
31 def bind(self, existingBinding: CandidateBinding) -> Optional[CandidateBinding]:
32 [x] = self.getNumericOperands(existingBinding)
33 f = cast(Literal, Literal(Decimal(x) * 9 / 5 + 32))
34 return self.valueInObjectTerm(f)
35
36
37 @register
38 class Sum(ListFunction):
39 pred = MATH['sum']
40
41 def bind(self, existingBinding: CandidateBinding) -> Optional[CandidateBinding]:
42 f = Literal(sum(self.getNumericOperands(existingBinding)))
43 return self.valueInObjectTerm(f)
44
45
46 @register
47 class ChildResource(ListFunction):
48 pred = ROOM['childResource']
49
50 def bind(self, existingBinding: CandidateBinding) -> Optional[CandidateBinding]:
51 ops = self.getOperandNodes(existingBinding)
52 if len(ops) != 2 or not isinstance(ops[0], URIRef) or not isinstance(ops[1], Literal):
53 raise ValueError(f'expected (?baseUri ?nextSegmentString) as subject to {self}')
54 newUri = URIRef(ops[0].rstrip('/') + '/' + urllib.parse.quote(ops[1].toPython(), safe=''))
55 return self.valueInObjectTerm(newUri)