forked from observablehq/plot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroup.js
359 lines (325 loc) · 10 KB
/
group.js
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
import {group as grouper, sort, sum, deviation, min, max, mean, median, mode, variance, InternSet, minIndex, maxIndex, rollup} from "d3";
import {ascendingDefined} from "../defined.js";
import {valueof, maybeColorChannel, maybeInput, maybeTuple, maybeColumn, column, first, identity, take, labelof, range, second, percentile} from "../options.js";
import {basic} from "./basic.js";
// Group on {z, fill, stroke}.
export function groupZ(outputs, options) {
return groupn(null, null, outputs, options);
}
// Group on {z, fill, stroke}, then on x.
export function groupX(outputs = {y: "count"}, options = {}) {
const {x = identity} = options;
if (x == null) throw new Error("missing channel: x");
return groupn(x, null, outputs, options);
}
// Group on {z, fill, stroke}, then on y.
export function groupY(outputs = {x: "count"}, options = {}) {
const {y = identity} = options;
if (y == null) throw new Error("missing channel: y");
return groupn(null, y, outputs, options);
}
// Group on {z, fill, stroke}, then on x and y.
export function group(outputs = {fill: "count"}, options = {}) {
let {x, y} = options;
([x, y] = maybeTuple(x, y));
if (x == null) throw new Error("missing channel: x");
if (y == null) throw new Error("missing channel: y");
return groupn(x, y, outputs, options);
}
function groupn(
x, // optionally group on x
y, // optionally group on y
{
data: reduceData = reduceIdentity,
filter,
sort,
reverse,
...outputs // output channel definitions
} = {},
inputs = {} // input channels and options
) {
// Compute the outputs.
outputs = maybeOutputs(outputs, inputs);
reduceData = maybeReduce(reduceData, identity);
sort = sort == null ? undefined : maybeOutput("sort", sort, inputs);
filter = filter == null ? undefined : maybeEvaluator("filter", filter, inputs);
// Produce x and y output channels as appropriate.
const [GX, setGX] = maybeColumn(x);
const [GY, setGY] = maybeColumn(y);
// Greedily materialize the z, fill, and stroke channels (if channels and not
// constants) so that we can reference them for subdividing groups without
// computing them more than once.
const {
z,
fill,
stroke,
x1, x2, // consumed if x is an output
y1, y2, // consumed if y is an output
...options
} = inputs;
const [GZ, setGZ] = maybeColumn(z);
const [vfill] = maybeColorChannel(fill);
const [vstroke] = maybeColorChannel(stroke);
const [GF, setGF] = maybeColumn(vfill);
const [GS, setGS] = maybeColumn(vstroke);
return {
..."z" in inputs && {z: GZ || z},
..."fill" in inputs && {fill: GF || fill},
..."stroke" in inputs && {stroke: GS || stroke},
...basic(options, (data, facets) => {
const X = valueof(data, x);
const Y = valueof(data, y);
const Z = valueof(data, z);
const F = valueof(data, vfill);
const S = valueof(data, vstroke);
const G = maybeSubgroup(outputs, {z: Z, fill: F, stroke: S});
const groupFacets = [];
const groupData = [];
const GX = X && setGX([]);
const GY = Y && setGY([]);
const GZ = Z && setGZ([]);
const GF = F && setGF([]);
const GS = S && setGS([]);
let i = 0;
for (const o of outputs) o.initialize(data);
if (sort) sort.initialize(data);
if (filter) filter.initialize(data);
for (const facet of facets) {
const groupFacet = [];
for (const o of outputs) o.scope("facet", facet);
if (sort) sort.scope("facet", facet);
if (filter) filter.scope("facet", facet);
for (const [f, I] of maybeGroup(facet, G)) {
for (const [y, gg] of maybeGroup(I, Y)) {
for (const [x, g] of maybeGroup(gg, X)) {
if (filter && !filter.reduce(g)) continue;
groupFacet.push(i++);
groupData.push(reduceData.reduce(g, data));
if (X) GX.push(x);
if (Y) GY.push(y);
if (Z) GZ.push(G === Z ? f : Z[g[0]]);
if (F) GF.push(G === F ? f : F[g[0]]);
if (S) GS.push(G === S ? f : S[g[0]]);
for (const o of outputs) o.reduce(g);
if (sort) sort.reduce(g);
}
}
}
groupFacets.push(groupFacet);
}
maybeSort(groupFacets, sort, reverse);
return {data: groupData, facets: groupFacets};
}),
...!hasOutput(outputs, "x") && (GX ? {x: GX} : {x1, x2}),
...!hasOutput(outputs, "y") && (GY ? {y: GY} : {y1, y2}),
...Object.fromEntries(outputs.map(({name, output}) => [name, output]))
};
}
export function hasOutput(outputs, ...names) {
for (const {name} of outputs) {
if (names.includes(name)) {
return true;
}
}
return false;
}
export function maybeOutputs(outputs, inputs) {
const entries = Object.entries(outputs);
// Propagate standard mark channels by default.
if (inputs.title != null && outputs.title === undefined) entries.push(["title", reduceTitle]);
if (inputs.href != null && outputs.href === undefined) entries.push(["href", reduceFirst]);
return entries.map(([name, reduce]) => {
return reduce == null
? {name, initialize() {}, scope() {}, reduce() {}}
: maybeOutput(name, reduce, inputs);
});
}
export function maybeOutput(name, reduce, inputs) {
const evaluator = maybeEvaluator(name, reduce, inputs);
const [output, setOutput] = column(evaluator.label);
let O;
return {
name,
output,
initialize(data) {
evaluator.initialize(data);
O = setOutput([]);
},
scope(scope, I) {
evaluator.scope(scope, I);
},
reduce(I, extent) {
O.push(evaluator.reduce(I, extent));
}
};
}
export function maybeEvaluator(name, reduce, inputs) {
const input = maybeInput(name, inputs);
const reducer = maybeReduce(reduce, input);
let V, context;
return {
label: labelof(reducer === reduceCount ? null : input, reducer.label),
initialize(data) {
V = input === undefined ? data : valueof(data, input);
if (reducer.scope === "data") {
context = reducer.reduce(range(data), V);
}
},
scope(scope, I) {
if (reducer.scope === scope) {
context = reducer.reduce(I, V);
}
},
reduce(I, extent) {
return reducer.scope == null
? reducer.reduce(I, V, extent)
: reducer.reduce(I, V, context, extent);
}
};
}
export function maybeGroup(I, X) {
return X ? sort(grouper(I, i => X[i]), first) : [[, I]];
}
export function maybeReduce(reduce, value) {
if (reduce && typeof reduce.reduce === "function") return reduce;
if (typeof reduce === "function") return reduceFunction(reduce);
if (/^p\d{2}$/i.test(reduce)) return reduceAccessor(percentile(reduce));
switch (`${reduce}`.toLowerCase()) {
case "first": return reduceFirst;
case "last": return reduceLast;
case "count": return reduceCount;
case "distinct": return reduceDistinct;
case "sum": return value == null ? reduceCount : reduceSum;
case "proportion": return reduceProportion(value, "data");
case "proportion-facet": return reduceProportion(value, "facet");
case "deviation": return reduceAccessor(deviation);
case "min": return reduceAccessor(min);
case "min-index": return reduceAccessor(minIndex);
case "max": return reduceAccessor(max);
case "max-index": return reduceAccessor(maxIndex);
case "mean": return reduceAccessor(mean);
case "median": return reduceAccessor(median);
case "variance": return reduceAccessor(variance);
case "mode": return reduceAccessor(mode);
case "x": return reduceX;
case "x1": return reduceX1;
case "x2": return reduceX2;
case "y": return reduceY;
case "y1": return reduceY1;
case "y2": return reduceY2;
}
throw new Error(`invalid reduce: ${reduce}`);
}
export function maybeSubgroup(outputs, inputs) {
for (const name in inputs) {
const value = inputs[name];
if (value !== undefined && !outputs.some(o => o.name === name)) {
return value;
}
}
}
export function maybeSort(facets, sort, reverse) {
if (sort) {
const S = sort.output.transform();
const compare = (i, j) => ascendingDefined(S[i], S[j]);
facets.forEach(f => f.sort(compare));
}
if (reverse) {
facets.forEach(f => f.reverse());
}
}
function reduceFunction(f) {
return {
reduce(I, X, extent) {
return f(take(X, I), extent);
}
};
}
function reduceAccessor(f) {
return {
reduce(I, X) {
return f(I, i => X[i]);
}
};
}
export const reduceIdentity = {
reduce(I, X) {
return take(X, I);
}
};
export const reduceFirst = {
reduce(I, X) {
return X[I[0]];
}
};
const reduceTitle = {
reduce(I, X) {
const n = 5;
const groups = sort(rollup(I, V => V.length, i => X[i]), second);
const top = groups.slice(-n).reverse();
if (top.length < groups.length) {
const bottom = groups.slice(0, 1 - n);
top[n - 1] = [`… ${bottom.length.toLocaleString("en-US")} more`, sum(bottom, second)];
}
return top.map(([key, value]) => `${key} (${value.toLocaleString("en-US")})`).join("\n");
}
};
const reduceLast = {
reduce(I, X) {
return X[I[I.length - 1]];
}
};
export const reduceCount = {
label: "Frequency",
reduce(I) {
return I.length;
}
};
const reduceDistinct = {
label: "Distinct",
reduce: (I, X) => {
const s = new InternSet();
for (const i of I) s.add(X[i]);
return s.size;
}
};
const reduceSum = reduceAccessor(sum);
function reduceProportion(value, scope) {
return value == null
? {scope, label: "Frequency", reduce: (I, V, basis = 1) => I.length / basis}
: {scope, reduce: (I, V, basis = 1) => sum(I, i => V[i]) / basis};
}
function mid(x1, x2) {
const m = (+x1 + +x2) / 2;
return x1 instanceof Date ? new Date(m) : m;
}
const reduceX = {
reduce(I, X, {x1, x2}) {
return mid(x1, x2);
}
};
const reduceY = {
reduce(I, X, {y1, y2}) {
return mid(y1, y2);
}
};
const reduceX1 = {
reduce(I, X, {x1}) {
return x1;
}
};
const reduceX2 = {
reduce(I, X, {x2}) {
return x2;
}
};
const reduceY1 = {
reduce(I, X, {y1}) {
return y1;
}
};
const reduceY2 = {
reduce(I, X, {y2}) {
return y2;
}
};