1 | import {partition} from './util/util';
|
2 | import {Transform, ingest} from 'vega-dataflow';
|
3 | import {quantiles} from 'vega-statistics';
|
4 | import {accessorName, inherits} from 'vega-util';
|
5 | import {range} from 'd3-array';
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | export default function Quantile(params) {
|
24 | Transform.call(this, null, params);
|
25 | }
|
26 |
|
27 | Quantile.Definition = {
|
28 | 'type': 'Quantile',
|
29 | 'metadata': {'generates': true, 'changes': true},
|
30 | 'params': [
|
31 | { 'name': 'groupby', 'type': 'field', 'array': true },
|
32 | { 'name': 'field', 'type': 'field', 'required': true },
|
33 | { 'name': 'probs', 'type': 'number', 'array': true },
|
34 | { 'name': 'step', 'type': 'number', 'default': 0.01 },
|
35 | { 'name': 'as', 'type': 'string', 'array': true, 'default': ['prob', 'value'] }
|
36 | ]
|
37 | };
|
38 |
|
39 | var prototype = inherits(Quantile, Transform);
|
40 |
|
41 | var EPSILON = 1e-14;
|
42 |
|
43 | prototype.transform = function(_, pulse) {
|
44 | var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
|
45 | as = _.as || ['prob', 'value'];
|
46 |
|
47 | if (this.value && !_.modified() && !pulse.changed()) {
|
48 | out.source = this.value;
|
49 | return out;
|
50 | }
|
51 |
|
52 | const source = pulse.materialize(pulse.SOURCE).source,
|
53 | groups = partition(source, _.groupby, _.field),
|
54 | names = (_.groupby || []).map(accessorName),
|
55 | values = [],
|
56 | step = _.step || 0.01,
|
57 | p = _.probs || range(step/2, 1 - EPSILON, step),
|
58 | n = p.length;
|
59 |
|
60 | groups.forEach(g => {
|
61 | const q = quantiles(g, p);
|
62 |
|
63 | for (let i=0; i<n; ++i) {
|
64 | const t = {};
|
65 | for (let i=0; i<names.length; ++i) {
|
66 | t[names[i]] = g.dims[i];
|
67 | }
|
68 | t[as[0]] = p[i];
|
69 | t[as[1]] = q[i];
|
70 | values.push(ingest(t));
|
71 | }
|
72 | });
|
73 |
|
74 | if (this.value) out.rem = this.value;
|
75 | this.value = out.add = out.source = values;
|
76 |
|
77 | return out;
|
78 | };
|