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 | const EPSILON = 1e-14;
|
40 |
|
41 | inherits(Quantile, Transform, {
|
42 | transform(_, pulse) {
|
43 | const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
|
44 | as = _.as || ['prob', 'value'];
|
45 |
|
46 | if (this.value && !_.modified() && !pulse.changed()) {
|
47 | out.source = this.value;
|
48 | return out;
|
49 | }
|
50 |
|
51 | const source = pulse.materialize(pulse.SOURCE).source,
|
52 | groups = partition(source, _.groupby, _.field),
|
53 | names = (_.groupby || []).map(accessorName),
|
54 | values = [],
|
55 | step = _.step || 0.01,
|
56 | p = _.probs || range(step/2, 1 - EPSILON, step),
|
57 | n = p.length;
|
58 |
|
59 | groups.forEach(g => {
|
60 | const q = quantiles(g, p);
|
61 |
|
62 | for (let i=0; i<n; ++i) {
|
63 | const t = {};
|
64 | for (let i=0; i<names.length; ++i) {
|
65 | t[names[i]] = g.dims[i];
|
66 | }
|
67 | t[as[0]] = p[i];
|
68 | t[as[1]] = q[i];
|
69 | values.push(ingest(t));
|
70 | }
|
71 | });
|
72 |
|
73 | if (this.value) out.rem = this.value;
|
74 | this.value = out.add = out.source = values;
|
75 |
|
76 | return out;
|
77 | }
|
78 | });
|