Source

wdmmg / wdmmg / lib / aggregator.py

Full commit
w...@eu5.okfn.or… e983466 







rgrp 56a247a 

















w...@eu5.okfn.or… e983466 






w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 
w...@eu5.okfn.or… 5908d2a 
w...@eu5.okfn.or… e983466 


w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 











































rgrp 56a247a 
w...@eu5.okfn.or… e983466 




w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 












w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 
w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 






w...@eu5.okfn.or… dbdd679 

w...@eu5.okfn.or… e983466 











w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 


w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 


w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 


w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 


w...@eu5.okfn.or… dbdd679 
















w...@eu5.okfn.or… e983466 


w...@eu5.okfn.or… dbdd679 
w...@eu5.okfn.or… e983466 






rgrp 56a247a 



















































































































w...@eu5.okfn.or… e983466 
rgrp 56a247a 























































































































  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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
from wdmmg.vocab import cra
from ordf.graph import Graph
from ordf.namespace import Namespace, CRA, CRADATA, SDMX, SDMXATTR, SDMXDIM, RDF, RDFS, OWL
from ordf.vocab.skos import NotationCache
from ordf.vocab.sdmx import TimeSeries, Observation, DataStructureDefinition, DataSet
from ordf.term import BNode, Variable, Literal
from telescope import Select, v
from pylons import config

# This is the deflator used in PESA. It is normalised to 2006-07 using a
# measure of inflation suitable for measuring GDP. A value of 'x' in year 'y'
# means that 1 pound from year 2006 was worth 'x' pounds from year 'y'.
# The figures were reverse-engineered from the PESA 2008-09 report, by dividing
# table 1.2 by table 1.1.
gdp_deflator2006 = {
  '2002-2003': 1.0/1.1098,
  '2003-2004': 1.0/1.0786,
  '2004-2005': 1.0/1.0496,
  '2005-2006': 1.0/1.0274,
  '2006-2007': 1.0/1.0000,
  '2007-2008': 1.0/0.9690,
  '2008-2009': 1.0/0.9399,
  '2009-2010': 1.0/0.9150,
  '2010-2011': 1.0/0.8911
}

class SeriesCache(object):
    def __init__(self, namespace, nc, store=None):
        self.namespace = namespace
        self.nc = nc
        self._seriesCache = {}
        self._seriesFactory = TimeSeries()
        self._obsFactory = Observation()
        self._store = store
    def getSeries(self, attrs):
        path = "/".join([self.nc.get(val) for (attr, val) in attrs]).replace(" ", "")
        ident = self.namespace[path]
        series = self._seriesCache.get(ident)
        if series is None:
            print "Series:", ident
            series = self._seriesFactory.get(ident, Graph(self._store, identifier=ident))
            for attr, val in attrs:
                series.graph.add((series.identifier, attr, val))
                series._namespace = Namespace(ident + "#")
                series._obsCache = {}
            self._seriesCache[ident] = series
        return series
    def getObs(self, series, refPeriod, obsValue, attrs=[], op=lambda x,y: x+y.toPython()):
        obs = series._obsCache.get(refPeriod)
        if obs is None:
            _unused, yearspec = refPeriod.rsplit("/", 1)
            obs = self._obsFactory.get(series._namespace[yearspec], graph=series.graph)
            obs.addDimension(SDMXDIM.refPeriod, refPeriod)
            for attr, val in attrs:
                obs.graph.add((obs.identifier, attr, val))
                obs._valueCache = 0.0
            series.observation = obs
            series._obsCache[refPeriod] = obs
        obs._valueCache = op(obs._valueCache, obsValue)
        return obs
    def finalise(self):
        for series in self._seriesCache.values():
            for obs in series._obsCache.values():
                obs.graph.add((obs.identifier, SDMX.obsValue, Literal(obs._valueCache)))
    def __iter__(self):
        for series in self._seriesCache.values():
            yield series
            
def randvar(): return Variable(BNode())
def project(store, namespace, dataset, compact=[], flatten=[]):
    compact_bindings = [(x, randvar()) for x in compact]
    flatten_bindings = [(x, randvar()) for x in flatten]
    bindings = [(SDMX.slice, v.slice), (SDMXDIM.refPeriod, v.refPeriod), (SDMX.obsValue, v.value)] + \
               compact_bindings + flatten_bindings
    where = [
        (dataset, SDMX.slice, v.slice),
        (v.slice, SDMX.observation, v.obs),
        (v.obs, SDMXDIM.refPeriod, v.refPeriod),
        (v.obs, SDMX.obsValue, v.value)
        ]
    where += [(v.slice, pred, var) for (pred, var) in compact_bindings]
    where += [(v.obs, pred, var) for (pred, var) in flatten_bindings]
    
    q = Select([var for (pred, var) in bindings], distinct=True).where(*where)

    result_indices = dict(zip([pred for (pred, var) in bindings], range(len(bindings))))
    def result(row, pred):
        return row[result_indices[pred]]
    
    nc = NotationCache(store)
    sc = SeriesCache(namespace, nc, store)

    for row in store.query(q.compile()):
        series_attrs = [(x, result(row, x)) for x in compact]
        series = sc.getSeries(series_attrs)
        refPeriod = result(row, SDMXDIM.refPeriod)
        obsValue = result(row, SDMX.obsValue)
        obs_attrs = [(x, result(row, x)) for x in flatten]
        obs = sc.getObs(series, refPeriod, obsValue, obs_attrs)
    sc.finalise()
    
    return sc

def aggregate(store, src_ds, dst_ds, compact=[], flatten=[], label=None, comment=None, namespace=None):
    print "Aggregating", dst_ds
    _ds = DataSet()
    ds = _ds.get(dst_ds, Graph(store, identifier=dst_ds))
    if label: ds.label = label
    if comment: ds.comment = comment
    ds.source = src_ds

    namespace = namespace if namespace else Namespace(dst_ds + "/")
    for series in project(store, namespace, src_ds, compact=compact, flatten=flatten):
        ds.series = series
        series.dataSet = ds
    print "Done."
    return ds

if __name__ == '__main__':
    from py4s import FourStore
    store = FourStore("wdmmg,soft_limit=-1")
    from ordf.vocab.void import Dataset as VoidDataSet
    crads = VoidDataSet().get(CRADATA["2009"], graph=Graph(store, identifier=CRADATA["2009"]))
    
    aggregates = [
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/entity"],
                  compact=[CRA.entity],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by entity")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/region"],
                  compact=[CRA.region],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by region")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/function"],
                  compact=[CRA.function],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by function")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/pog"],
                  compact=[CRA.pog],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by programme object group")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/er"],
                  compact=[CRA.entity, CRA.region],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by entity and region")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/ef"],
                  compact=[CRA.entity, CRA.function],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by entity and function")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/ep"],
                  compact=[CRA.entity, CRA.pog],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by entity and programme object group")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/rf"],
                  compact=[CRA.region, CRA.function],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by region and function")),
        aggregate(store, CRADATA["2009/entries"], CRADATA["2009/rp"],
                  compact=[CRA.region, CRA.pog],
                  flatten=[SDMXATTR.unitMeasure],
                  label=Literal("CRA 2009 by region and programme object group")),
        ]
    for dataset in aggregates:
        crads.subset = dataset
        dataset.isPartOf = crads
    print crads.graph.serialize(format="n3")
    
#    print dataset.graph.serialize(format="n3")

    from sys import exit
    exit(0)
    
class Results:
    '''
    Represents the result of a call to `aggregate()`. This class has the
    following fields:
    
    dates - a list of the distinct transaction dates. These are unicode strings,
        and they are returned in sorted order.
    
    axes - a list of key names. Does not include 'time', which is treated
        specially.
    
    matrix - a sparse matrix. This takes the form of a list of (coordinates,
        time series) pairs. The "coordinates" are a list giving the values of
        the Keys in the same order as they appear in `axes`. If no KeyValue
        exists for a given Key, the value `None` is supplied. The "time series"
        is a list of spending totals, one for each date in `dates`. If there
        was no spending on a given date, then `0.0` is supplied.
    '''
    
    def __init__(self, dates, axes, matrix=None):
        '''
        Do not construct a Results directly - call `aggregate()` instead.
        
        dates - a sorted list of unicode strings, representing all the distinct
            transaction dates needed.
        
        axes - a list of unicode strings, representing Key names.
        '''
        self.dates = dates
        self.date_index = dict([(date, index)
            for index, date in enumerate(self.dates)])
        self.axes = axes
        self.axis_index = dict([(axis, i) for i, axis in enumerate(axes)])
        self.matrix = matrix or {}
    
    def _add_spending(self, coordinates, amount, timestamp):
        '''
        For use by `aggregate()`.
        '''
        assert amount is not None, (coordinates, amount, timestamp)
        if coordinates not in self.matrix:
            self.matrix[coordinates] = [0.0] * len(self.dates)
        self.matrix[coordinates][self.date_index[timestamp]] += amount
    
    def divide_by_statistic(self, axis, statistic):
        '''
        Divides spending by a property of a coordinate. This is useful for
        computing statistics such as per-capita spending.
        
        axis - a Key, representing the coordinate to use, e.g. region.
        
        statistic - a Key, representing the statistic to use, e.g. population.
        
        The Key `axis` selects a property of spending (e.g. geographical
        region). The value of that property (e.g. 'NORTHERN IRELAND') is
        retrieved for each Transaction. Then, the Key `statistic` selects a
        property of those values (e.g. population). Finally, the aggregated
        spending is divided by the aggregated statistic. There are two cases,
        depending on whether `axis` is in `self.axes`:
        
         - If it is, then each spending item is divided by e.g. the population
        of its own region.
        
         - If it is not, then each spending item is divided by e.g. the total
        population of all regions.
        '''
        def to_float(x):
            try: return float(x)
            except ValueError: return None
        index = dict([
            (ev.code, to_float(ev.keyvalues[statistic]))
            for ev in model.Session.query(model.EnumerationValue).filter_by(key=axis)
            if statistic in ev.keyvalues
        ])
        if axis.name in self.axes:
            n = self.axis_index[axis.name] # Which coordinate?
            for coordinates, amounts in self.matrix.items():
                divisor = index.get(coordinates[n])
                for i in range(len(self.dates)):
#                    print "Dividing %r by %r" % (amounts[i], divisor)
                    if divisor and amounts[i] is not None: amounts[i] /= divisor
                    else: amounts[i] = None
        else:
            # FIXME: Does not work for hierarchical keys.
            divisor = sum(index.values())
            for coordinates, amounts in self.matrix.items():
                for i in range(len(self.dates)):
#                    print "Dividing %r by total %r" % (amounts[i], divisor)
                    if divisor and amounts[i] is not None: amounts[i] /= divisor
                    else: amounts[i] = None
    
    def divide_by_time_statistic(self, statistic_name):
        '''
        Divides spending by a property of a coordinate. This is useful for
        computing statistics such as spending in real terms.
        
        statistic_name - the name of a time-dependent statistic. The supported
            statistics are: 'gdp_deflator2006'.
        '''
        statistic = time_series.get(statistic_name, {})
        divisors = [statistic.get(date, None) for date in self.dates]
        for coordinates, amounts in self.matrix.items():
            for i in range(len(self.dates)):
#                print "Dividing %r by total %r" % (amounts[i], divisors[i])
                if divisors[i] and amounts[i]: amounts[i] /= divisors[i]
                else: amounts[i] = None

    def __str__(self):
        return repr(self)
    
    def __repr__(self):
        return (
            'Results(\n\t%r,\n\t%r,\n\tmatrix=%r)' %
            (self.dates, self.axes, self.matrix)
        )

def _aggregate(
    slice_,
    include={}, # list((Key, unicode))
    axes=[], # list(Key)
):
    '''
    Returns the dataset `slice_`, converted to a pivot table. Transactions are
    filtered and then classified according to their properties, and summarised
    by summing over all variables apart from those of interest.
    
    Arguments:
    
    slice_ - a Slice object representing the dataset of interest.
    
    include - rules for including postings. This is a list of (key, value)
        pairs. A transaction will be excluded unless the value matches the
        transaction's value for the key.
    
    axes - a list of Key objects representing the desired axes of the pivot
        table. Do not include 'time', which is treated specially.
    
    Returns a Results object.
    '''
    query, params = _make_aggregate_query(
        slice_,
        include,
        axes,
    )
#    print query
#    for k, v in params.items():
#        print k, v
    results = list(model.Session.execute(query, params))
    dates = sorted(set([row['time'] for row in results]))
    ans = Results(dates, [key.name for key in axes])
    for row in results:
        ans._add_spending(
            tuple([row[i] for i in range(len(axes))]),
            row['amount'],
            row['time'],
        )
    return ans

def _make_aggregate_query(
    slice_,
    include,
    axes,
):
    '''
    Uses string manipulation to construct the SQL query needed by
    `aggregate()`.
    
    Parameters: same as `aggregate()`.
    Returns: (string, dict) pair representing the query and its params.
    '''
    # N.B. Don't attempt to alchemise the raw SQL. Two reasons:
    #  - The query is not primitive-recursive. The subselect beginning
    #    "SELECT ev.code FROM" mentions "t.id" but does not bind it.
    #  - It is likely to be far too slow.
    
    # Retrieve the 'time' Key.
    key_time = model.Session.query(model.Key).filter_by(name=u'time').one()
    assert key_time not in axes, '''No need to break down by Key 'time'.'''

    # Compute some useful strings for each breakdown key.
    bds = [{
        'id': key.id, # The database `id` of the Key.
        'param': 'ak_%d' % i, # The SQL bind parameter whose value is `id`.
        'name': 'axis_%d' % i, # The SQL alias used for this coordinate.
    } for i, key in enumerate(axes)]

    # Compile an SQL query and its bind parameters at the same time.
    query, params = StringIO(), {}

    # Utility function that computes some useful strings for filter subselects.
    subselect_count = [0] # Use a singleton list for a mutable up-value.
    def subselect_params(key, value):
        # Update counter, and choose unambiguous SQL bind parameter names.
        n = subselect_count[0]
        subselect_count[0] += 1
        kv = {
            'k_param': 'k_%d' % n, # The SQL bind parameter whose value is `key.id`.
            'v_param': 'v_%d' % n, # The SQL bind parameter whose value is `value`.
        }
        params[kv['k_param']] = key.id
        params[kv['v_param']] = value
        return kv
    # SELECT
    query.write('''\
SELECT''')
    for bd in bds:
        query.write('''
    (SELECT ev.code FROM classification_item ci, enumeration_value ev
        WHERE ev.key_id = :%(param)s
        AND ci.transaction_id = t.id AND ci.value_id = ev.id) AS %(name)s,''' % bd)
        params[bd['param']] = bd['id']
    query.write('''
    SUM(t.amount) as amount,
    (SELECT ev.code FROM classification_item ci, enumeration_value ev
        WHERE ev.key_id = :key_time_id
        AND ci.transaction_id = t.id AND ci.value_id = ev.id) AS time''')
    params['key_time_id'] = key_time.id
    # FROM
    query.write('''
FROM "transaction" t''')
    # WHERE
    query.write('''
WHERE t.slice_id = :slice_id''')
    params['slice_id'] = slice_.id
    for key, value in include:
        query.write('''
AND t.id IN (SELECT ci.transaction_id FROM classification_item ci, enumeration_value ev
    WHERE ev.key_id = :%(k_param)s
    AND ev.code = :%(v_param)s AND ci.value_id = ev.id)''' %
            subselect_params(key, value))
    # GROUP BY
    query.write('''
GROUP BY time''')
    for bd in bds:
        query.write(', %(name)s' % bd)

    return (query.getvalue(), params)