-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathquantitative.js
More file actions
347 lines (317 loc) · 11.3 KB
/
quantitative.js
File metadata and controls
347 lines (317 loc) · 11.3 KB
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
import {
descending,
extent,
interpolateHcl,
interpolateHsl,
interpolateLab,
interpolateNumber,
interpolateRgb,
interpolateRound,
max,
median,
min,
piecewise,
quantile,
quantize,
reverse as reverseof,
scaleIdentity,
scaleLinear,
scaleLog,
scalePow,
scaleQuantile,
scaleSymlog,
scaleThreshold,
ticks
} from "d3";
import {finite, negative, positive} from "../defined.js";
import {arrayify, constant, maybeNiceInterval, maybeRangeInterval, slice} from "../options.js";
import {orderof} from "../order.js";
import {color, length, opacity, radius, registry, hasNumericRange} from "./index.js";
import {ordinalRange, quantitativeScheme} from "./schemes.js";
export const flip = (i) => (t) => i(1 - t);
const unit = [0, 1];
const interpolators = new Map([
// numbers
["number", interpolateNumber],
// color spaces
["rgb", interpolateRgb],
["hsl", interpolateHsl],
["hcl", interpolateHcl],
["lab", interpolateLab]
]);
export function maybeInterpolator(interpolate) {
const i = `${interpolate}`.toLowerCase();
if (!interpolators.has(i)) throw new Error(`unknown interpolator: ${i}`);
return interpolators.get(i);
}
export function createScaleQ(
key,
scale,
channels,
{
type,
nice,
clamp,
zero,
domain = inferAutoDomain(key, channels),
unknown,
round,
scheme,
interval,
range = registry.get(key) === radius
? inferRadialRange(channels, domain)
: registry.get(key) === length
? inferLengthRange(channels, domain)
: registry.get(key) === opacity
? unit
: undefined,
interpolate = registry.get(key) === color
? scheme == null && range !== undefined
? interpolateRgb
: quantitativeScheme(scheme !== undefined ? scheme : type === "cyclical" ? "rainbow" : "turbo")
: round
? interpolateRound
: interpolateNumber,
reverse
}
) {
domain = maybeRepeat(domain);
interval = maybeRangeInterval(interval, type);
if (type === "cyclical" || type === "sequential") type = "linear"; // shorthand for color schemes
if (typeof interpolate !== "function") interpolate = maybeInterpolator(interpolate); // named interpolator
reverse = !!reverse;
// If an explicit range is specified, and it has a different length than the
// domain, then redistribute the range using a piecewise interpolator.
if (range !== undefined) {
const n = domain.length;
const m = (range = maybeRepeat(range)).length;
if (n !== m) {
if (interpolate.length === 1) throw new Error("invalid piecewise interpolator"); // e.g., turbo
interpolate = piecewise(interpolate, range);
range = undefined;
}
}
// Disambiguate between a two-argument interpolator that is used in
// conjunction with the range, and a one-argument “fixed” interpolator on the
// [0, 1] interval as with the RdBu color scheme.
if (interpolate.length === 1) {
if (reverse) {
interpolate = flip(interpolate);
reverse = false;
}
if (range === undefined) {
range = Float64Array.from(domain, (_, i) => i / (domain.length - 1));
if (range.length === 2) range = unit; // optimize common case of [0, 1]
}
scale.interpolate((range === unit ? constant : interpolatePiecewise)(interpolate));
} else {
scale.interpolate(interpolate);
}
// If the zero option is not specified, then implicitly extend the domain to
// include zero if the minimum is less than 7% of the spread (and similarly
// for negative domains).
if (zero === undefined && type === "linear") {
const [min, max] = extent(domain);
zero = min > 0 ? min < 0.07 * (max - min) : max < 0 ? max > 0.07 * (min - max) : false;
}
// If a zero option is specified, we assume that the domain is numeric, and we
// want to ensure that the domain crosses zero. However, note that the domain
// may be reversed (descending) so we shouldn’t assume that the first value is
// smaller than the last; and also it’s possible that the domain has more than
// two values for a “poly” scale. And lastly be careful not to mutate input!
if (zero) {
const [min, max] = extent(domain);
if (min > 0 || max < 0) {
domain = slice(domain);
const o = orderof(domain) || 1; // treat degenerate as ascending
if (o === Math.sign(min)) domain[0] = 0; // [1, 2] or [-1, -2]
else domain[domain.length - 1] = 0; // [2, 1] or [-2, -1]
}
}
if (reverse) domain = reverseof(domain);
scale.domain(domain).unknown(unknown);
if (nice) scale.nice(maybeNice(nice, type)), (domain = scale.domain());
if (range !== undefined) scale.range(range);
if (clamp) scale.clamp(clamp);
return {type, domain, range, scale, interpolate, interval};
}
function maybeRepeat(values) {
values = arrayify(values);
return values.length >= 2 ? values : [values[0], values[0]];
}
function maybeNice(nice, type) {
return nice === true ? undefined : typeof nice === "number" ? nice : maybeNiceInterval(nice, type);
}
export function createScaleLinear(key, channels, options) {
return createScaleQ(key, scaleLinear(), channels, options);
}
export function createScaleSqrt(key, channels, options) {
return createScalePow(key, channels, {...options, exponent: 0.5});
}
export function createScalePow(key, channels, {exponent = 1, ...options}) {
return createScaleQ(key, scalePow().exponent(exponent), channels, {...options, type: "pow"});
}
export function createScaleLog(key, channels, {base = 10, domain = inferLogDomain(channels), ...options}) {
return createScaleQ(key, scaleLog().base(base), channels, {...options, domain});
}
export function createScaleSymlog(key, channels, {constant = 1, ...options}) {
return createScaleQ(key, scaleSymlog().constant(constant), channels, options);
}
export function createScaleQuantile(
key,
channels,
{
range,
quantiles = range === undefined ? 5 : (range = [...range]).length, // deprecated; use n instead
n = quantiles,
scheme = "rdylbu",
domain = inferQuantileDomain(channels),
unknown,
interpolate,
reverse
}
) {
if (range === undefined) {
range =
interpolate !== undefined
? quantize(interpolate, n)
: registry.get(key) === color
? ordinalRange(scheme, n)
: undefined;
}
if (domain.length > 0) {
domain = scaleQuantile(domain, range === undefined ? {length: n} : range).quantiles();
}
return createScaleThreshold(key, channels, {domain, range, reverse, unknown});
}
export function createScaleQuantize(
key,
channels,
{
range,
n = range === undefined ? 5 : (range = [...range]).length,
scheme = "rdylbu",
domain = inferAutoDomain(key, channels),
unknown,
interpolate,
reverse
}
) {
const [min, max] = extent(domain);
let thresholds;
if (range === undefined) {
thresholds = ticks(min, max, n); // approximate number of nice, round thresholds
if (thresholds[0] <= min) thresholds.splice(0, 1); // drop exact lower bound
if (thresholds[thresholds.length - 1] >= max) thresholds.pop(); // drop exact upper bound
n = thresholds.length + 1;
range =
interpolate !== undefined
? quantize(interpolate, n)
: registry.get(key) === color
? ordinalRange(scheme, n)
: undefined;
} else {
thresholds = quantize(interpolateNumber(min, max), n + 1).slice(1, -1); // exactly n - 1 thresholds to match range
if (min instanceof Date) thresholds = thresholds.map((x) => new Date(x)); // preserve date types
}
if (orderof(arrayify(domain)) < 0) thresholds.reverse(); // preserve descending domain
return createScaleThreshold(key, channels, {domain: thresholds, range, reverse, unknown});
}
export function createScaleThreshold(
key,
channels,
{
domain = [0], // explicit thresholds in ascending order
unknown,
scheme = "rdylbu",
interpolate,
range = interpolate !== undefined
? quantize(interpolate, domain.length + 1)
: registry.get(key) === color
? ordinalRange(scheme, domain.length + 1)
: undefined,
reverse
}
) {
domain = arrayify(domain);
const sign = orderof(domain); // preserve descending domain
if (!isNaN(sign) && !isOrdered(domain, sign)) throw new Error(`the ${key} scale has a non-monotonic domain`);
if (reverse) range = reverseof(range); // domain ascending, so reverse range
return {
type: "threshold",
scale: scaleThreshold(sign < 0 ? reverseof(domain) : domain, range === undefined ? [] : range).unknown(unknown),
domain,
range
};
}
function isOrdered(domain, sign) {
for (let i = 1, n = domain.length, d = domain[0]; i < n; ++i) {
const s = descending(d, (d = domain[i]));
if (s !== 0 && s !== sign) return false;
}
return true;
}
// For non-numeric identity scales such as color and symbol, we can’t use D3’s
// identity scale because it coerces to number; and we can’t compute the domain
// (and equivalently range) since we can’t know whether the values are
// continuous or discrete.
export function createScaleIdentity(key) {
return {type: "identity", scale: hasNumericRange(registry.get(key)) ? scaleIdentity() : (d) => d};
}
export function inferDomain(channels, f = finite) {
return channels.length
? [
min(channels, ({value}) => (value === undefined ? value : min(value, f))),
max(channels, ({value}) => (value === undefined ? value : max(value, f)))
]
: [0, 1];
}
function inferAutoDomain(key, channels) {
const type = registry.get(key);
return (type === radius || type === opacity || type === length ? inferZeroDomain : inferDomain)(channels);
}
function inferZeroDomain(channels) {
return [0, channels.length ? max(channels, ({value}) => (value === undefined ? value : max(value, finite))) : 1];
}
// We don’t want the upper bound of the radial domain to be zero, as this would
// be degenerate, so we ignore nonpositive values. We also don’t want the
// maximum default radius to exceed 30px.
function inferRadialRange(channels, domain) {
const hint = channels.find(({radius}) => radius !== undefined);
if (hint !== undefined) return [0, hint.radius]; // a natural maximum radius, e.g. hexbins
const h25 = quantile(channels, 0.5, ({value}) => (value === undefined ? NaN : quantile(value, 0.25, positive)));
const range = domain.map((d) => 3 * Math.sqrt(d / h25));
const k = 30 / max(range);
return k < 1 ? range.map((r) => r * k) : range;
}
// We want a length scale’s domain to go from zero to a positive value, and to
// treat negative lengths if any as inverted vectors of equivalent magnitude. We
// also don’t want the maximum default length to exceed 60px.
function inferLengthRange(channels, domain) {
const h50 = median(channels, ({value}) => (value === undefined ? NaN : median(value, Math.abs)));
const range = domain.map((d) => (12 * d) / h50);
const k = 60 / max(range);
return k < 1 ? range.map((r) => r * k) : range;
}
function inferLogDomain(channels) {
for (const {value} of channels) {
if (value !== undefined) {
for (let v of value) {
if (v > 0) return inferDomain(channels, positive);
if (v < 0) return inferDomain(channels, negative);
}
}
}
return [1, 10];
}
function inferQuantileDomain(channels) {
const domain = [];
for (const {value} of channels) {
if (value === undefined) continue;
for (const v of value) domain.push(v);
}
return domain;
}
export function interpolatePiecewise(interpolate) {
return (i, j) => (t) => interpolate(i + t * (j - i));
}