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
|
from rdflib import Literal, XSD
from rdflib.plugins.sparql.evalutils import _eval, NotBoundError, _val
from rdflib.plugins.sparql.operators import numeric
from rdflib.plugins.sparql.datatypes import type_promotion
from rdflib.plugins.sparql.sparql import SPARQLTypeError
from decimal import Decimal
"""
Aggregation functions
"""
class Accumulator(object):
"""abstract base class for different aggregation functions"""
def __init__(self, aggregation):
self.var = aggregation.res
self.expr = aggregation.vars
if not aggregation.distinct:
self.use_row = self.dont_care
self.distinct = False
else:
self.distinct = aggregation.distinct
self.seen = set()
def dont_care(self, row):
"""skips distinct test"""
return True
def use_row(self, row):
"""tests distinct with set"""
return _eval(self.expr, row) not in self.seen
def set_value(self, bindings):
"""sets final value in bindings"""
bindings[self.var] = self.get_value()
class Counter(Accumulator):
def __init__(self, aggregation):
super(Counter, self).__init__(aggregation)
self.value = 0
if self.expr == "*":
# cannot eval "*" => always use the full row
self.eval_row = self.eval_full_row
def update(self, row, aggregator):
try:
val = self.eval_row(row)
except NotBoundError:
# skip UNDEF
return
self.value += 1
if self.distinct:
self.seen.add(val)
def get_value(self):
return Literal(self.value)
def eval_row(self, row):
return _eval(self.expr, row)
def eval_full_row(self, row):
return row
def use_row(self, row):
return self.eval_row(row) not in self.seen
def type_safe_numbers(*args):
if any(isinstance(arg, float) for arg in args) and any(
isinstance(arg, Decimal) for arg in args
):
return map(float, args)
return args
class Sum(Accumulator):
def __init__(self, aggregation):
super(Sum, self).__init__(aggregation)
self.value = 0
self.datatype = None
def update(self, row, aggregator):
try:
value = _eval(self.expr, row)
dt = self.datatype
if dt is None:
dt = value.datatype
else:
dt = type_promotion(dt, value.datatype)
self.datatype = dt
self.value = sum(type_safe_numbers(self.value, numeric(value)))
if self.distinct:
self.seen.add(value)
except NotBoundError:
# skip UNDEF
pass
def get_value(self):
return Literal(self.value, datatype=self.datatype)
class Average(Accumulator):
def __init__(self, aggregation):
super(Average, self).__init__(aggregation)
self.counter = 0
self.sum = 0
self.datatype = None
def update(self, row, aggregator):
try:
value = _eval(self.expr, row)
dt = self.datatype
self.sum = sum(type_safe_numbers(self.sum, numeric(value)))
if dt is None:
dt = value.datatype
else:
dt = type_promotion(dt, value.datatype)
self.datatype = dt
if self.distinct:
self.seen.add(value)
self.counter += 1
# skip UNDEF or BNode => SPARQLTypeError
except NotBoundError:
pass
except SPARQLTypeError:
pass
def get_value(self):
if self.counter == 0:
return Literal(0)
if self.datatype in (XSD.float, XSD.double):
return Literal(self.sum / self.counter)
else:
return Literal(Decimal(self.sum) / Decimal(self.counter))
class Extremum(Accumulator):
"""abstract base class for Minimum and Maximum"""
def __init__(self, aggregation):
super(Extremum, self).__init__(aggregation)
self.value = None
# DISTINCT would not change the value for MIN or MAX
self.use_row = self.dont_care
def set_value(self, bindings):
if self.value is not None:
# simply do not set if self.value is still None
bindings[self.var] = Literal(self.value)
def update(self, row, aggregator):
try:
if self.value is None:
self.value = _eval(self.expr, row)
else:
# self.compare is implemented by Minimum/Maximum
self.value = self.compare(self.value, _eval(self.expr, row))
# skip UNDEF or BNode => SPARQLTypeError
except NotBoundError:
pass
except SPARQLTypeError:
pass
class Minimum(Extremum):
def compare(self, val1, val2):
return min(val1, val2, key=_val)
class Maximum(Extremum):
def compare(self, val1, val2):
return max(val1, val2, key=_val)
class Sample(Accumulator):
"""takes the first eligible value"""
def __init__(self, aggregation):
super(Sample, self).__init__(aggregation)
# DISTINCT would not change the value
self.use_row = self.dont_care
def update(self, row, aggregator):
try:
# set the value now
aggregator.bindings[self.var] = _eval(self.expr, row)
# and skip this accumulator for future rows
del aggregator.accumulators[self.var]
except NotBoundError:
pass
def get_value(self):
# set None if no value was set
return None
class GroupConcat(Accumulator):
def __init__(self, aggregation):
super(GroupConcat, self).__init__(aggregation)
# only GROUPCONCAT needs to have a list as accumulator
self.value = []
self.separator = aggregation.separator or " "
def update(self, row, aggregator):
try:
value = _eval(self.expr, row)
self.value.append(value)
if self.distinct:
self.seen.add(value)
# skip UNDEF
except NotBoundError:
pass
def get_value(self):
return Literal(self.separator.join(str(v) for v in self.value))
class Aggregator(object):
"""combines different Accumulator objects"""
accumulator_classes = {
"Aggregate_Count": Counter,
"Aggregate_Sample": Sample,
"Aggregate_Sum": Sum,
"Aggregate_Avg": Average,
"Aggregate_Min": Minimum,
"Aggregate_Max": Maximum,
"Aggregate_GroupConcat": GroupConcat,
}
def __init__(self, aggregations):
self.bindings = {}
self.accumulators = {}
for a in aggregations:
accumulator_class = self.accumulator_classes.get(a.name)
if accumulator_class is None:
raise Exception("Unknown aggregate function " + a.name)
self.accumulators[a.res] = accumulator_class(a)
def update(self, row):
"""update all own accumulators"""
# SAMPLE accumulators may delete themselves
# => iterate over list not generator
for acc in list(self.accumulators.values()):
if acc.use_row(row):
acc.update(row, self)
def get_bindings(self):
"""calculate and set last values"""
for acc in self.accumulators.values():
acc.set_value(self.bindings)
return self.bindings
|