-
Notifications
You must be signed in to change notification settings - Fork 115
/
scale_continuous.ts
310 lines (295 loc) · 9.03 KB
/
scale_continuous.ts
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
import { bisectLeft } from 'd3-array';
import {
scaleLinear,
scaleLog,
scaleSqrt,
scaleUtc,
ScaleLinear,
ScaleLogarithmic,
ScalePower,
ScaleTime,
} from 'd3-scale';
import { clamp, mergePartial } from '../commons';
import { ScaleContinuousType, ScaleType, Scale } from './scales';
import { getMomentWithTz } from '../data/date_time';
/**
* d3 scales excluding time scale
*/
type D3ScaleNonTime = ScaleLinear<any, any> | ScaleLogarithmic<any, any> | ScalePower<any, any>;
/**
* All possible d3 scales
*/
type D3Scale = D3ScaleNonTime | ScaleTime<any, any>;
const SCALES = {
[ScaleType.Linear]: scaleLinear,
[ScaleType.Log]: scaleLog,
[ScaleType.Sqrt]: scaleSqrt,
[ScaleType.Time]: scaleUtc,
};
/**
* As log(0) = -Infinite, a log scale domain must be strictly-positive
* or strictly-negative; the domain must not include or cross zero value.
* We need to limit the domain scale to the right value on all possible cases.
* @param domain the domain to limit
*/
export function limitLogScaleDomain(domain: any[]) {
if (domain[0] === 0) {
if (domain[1] > 0) {
return [1, domain[1]];
} else if (domain[1] < 0) {
return [-1, domain[1]];
} else {
return [1, 1];
}
}
if (domain[1] === 0) {
if (domain[0] > 0) {
return [domain[0], 1];
} else if (domain[0] < 0) {
return [domain[0], -1];
} else {
return [1, 1];
}
}
if (domain[0] < 0 && domain[1] > 0) {
const isD0Min = Math.abs(domain[1]) - Math.abs(domain[0]) >= 0;
if (isD0Min) {
return [1, domain[1]];
} else {
return [domain[0], -1];
}
}
if (domain[0] > 0 && domain[1] < 0) {
const isD0Max = Math.abs(domain[0]) - Math.abs(domain[1]) >= 0;
if (isD0Max) {
return [domain[0], 1];
} else {
return [-1, domain[1]];
}
}
return domain;
}
interface ScaleData {
/** The Type of continuous scale */
type: ScaleContinuousType;
/** The data input domain */
domain: any[];
/** The data output range */
range: [number, number];
}
interface ScaleOptions {
/**
* The desidered bandwidth for a linear band scale.
* @default 0
*/
bandwidth: number;
/**
* The min interval computed on the XDomain. Not available for yDomains.
* @default 0
*/
minInterval: number;
/**
* A time zone identifier. Can be any IANA zone supported by he host environment,
* or a fixed-offset name of the form 'utc+3', or the strings 'local' or 'utc'.
* @default 'utc'
*/
timeZone: string;
/**
* The number of bars in the cluster. Used to correctly compute scales when
* using padding between bars.
* @default 1
*/
totalBarsInCluster: number;
/**
* The proportion of the range that is reserved for blank space between bands
* A number between 0 and 1.
* @default 0
*/
barsPadding: number;
/**
* The approximated number of ticks.
* @default 10
*/
ticks: number;
/** true if the scale was adjusted to fit one single value histogram */
isSingleValueHistogram: boolean;
/** Show only integer values **/
integersOnly?: boolean;
}
const defaultScaleOptions: ScaleOptions = {
bandwidth: 0,
minInterval: 0,
timeZone: 'utc',
totalBarsInCluster: 1,
barsPadding: 0,
ticks: 10,
isSingleValueHistogram: false,
integersOnly: false,
};
export class ScaleContinuous implements Scale {
readonly bandwidth: number;
readonly totalBarsInCluster: number;
readonly bandwidthPadding: number;
readonly minInterval: number;
readonly step: number;
readonly type: ScaleType;
readonly domain: any[];
readonly range: number[];
readonly isInverted: boolean;
readonly tickValues: number[];
readonly timeZone: string;
readonly barsPadding: number;
readonly isSingleValueHistogram: boolean;
private readonly d3Scale: D3Scale;
constructor(scaleData: ScaleData, options?: Partial<ScaleOptions>) {
const { type, domain, range } = scaleData;
const {
bandwidth,
minInterval,
timeZone,
totalBarsInCluster,
barsPadding,
ticks,
isSingleValueHistogram,
integersOnly,
} = mergePartial(defaultScaleOptions, options);
this.d3Scale = SCALES[type]();
const cleanDomain = type === ScaleType.Log ? limitLogScaleDomain(domain) : domain;
this.domain = cleanDomain;
this.d3Scale.domain(cleanDomain);
const safeBarPadding = clamp(barsPadding, 0, 1);
this.barsPadding = safeBarPadding;
this.bandwidth = bandwidth * (1 - safeBarPadding);
this.bandwidthPadding = bandwidth * safeBarPadding;
this.d3Scale.range(range);
this.step = 0;
this.type = type;
this.range = range;
this.minInterval = minInterval;
this.isInverted = this.domain[0] > this.domain[1];
this.timeZone = timeZone;
this.totalBarsInCluster = totalBarsInCluster;
this.isSingleValueHistogram = isSingleValueHistogram;
if (type === ScaleType.Time) {
const startDomain = getMomentWithTz(this.domain[0], this.timeZone);
const endDomain = getMomentWithTz(this.domain[1], this.timeZone);
const offset = startDomain.utcOffset();
const shiftedDomainMin = startDomain.add(offset, 'minutes').valueOf();
const shiftedDomainMax = endDomain.add(offset, 'minutes').valueOf();
const tzShiftedScale = scaleUtc().domain([shiftedDomainMin, shiftedDomainMax]);
const rawTicks = tzShiftedScale.ticks(ticks);
const timePerTick = (shiftedDomainMax - shiftedDomainMin) / rawTicks.length;
const hasHourTicks = timePerTick < 1000 * 60 * 60 * 12;
this.tickValues = rawTicks.map((d: Date) => {
const currentDateTime = getMomentWithTz(d, this.timeZone);
const currentOffset = hasHourTicks ? offset : currentDateTime.utcOffset();
return currentDateTime.subtract(currentOffset, 'minutes').valueOf();
});
} else {
/**
* This case is for the xScale (minInterval is > 0) when we want to show bars (bandwidth > 0)
*
* We want to avoid displaying inner ticks between bars in a bar chart when using linear x scale
*/
if (minInterval > 0 && bandwidth > 0) {
const intervalCount = Math.floor((this.domain[1] - this.domain[0]) / this.minInterval);
this.tickValues = new Array(intervalCount + 1).fill(0).map((_, i) => {
return this.domain[0] + i * this.minInterval;
});
} else {
this.tickValues = this.getTicks(ticks, integersOnly!);
}
}
}
getTicks(ticks: number, integersOnly: boolean) {
return integersOnly
? (this.d3Scale as D3ScaleNonTime)
.ticks(ticks)
.filter((item: number) => typeof item === 'number' && item % 1 === 0)
.map((item: number) => parseInt(item.toFixed(0)))
: (this.d3Scale as D3ScaleNonTime).ticks(ticks);
}
scale(value: any) {
return this.d3Scale(value) + (this.bandwidthPadding / 2) * this.totalBarsInCluster;
}
pureScale(value: any) {
if (this.bandwidth === 0) {
return this.d3Scale(value);
}
return this.d3Scale(value + this.minInterval / 2);
}
ticks() {
return this.tickValues;
}
invert(value: number): number {
let invertedValue = this.d3Scale.invert(value);
if (this.type === ScaleType.Time) {
invertedValue = getMomentWithTz(invertedValue, this.timeZone).valueOf();
}
return invertedValue as number;
}
invertWithStep(
value: number,
data: number[],
): {
value: number;
withinBandwidth: boolean;
} | null {
if (data.length === 0) {
return null;
}
const invertedValue = this.invert(value);
const bisectValue = this.bandwidth === 0 ? invertedValue + this.minInterval / 2 : invertedValue;
const leftIndex = bisectLeft(data, bisectValue);
if (leftIndex === 0) {
if (invertedValue < data[0]) {
return {
value: data[0] - this.minInterval * Math.ceil((data[0] - invertedValue) / this.minInterval),
withinBandwidth: false,
};
}
return {
value: data[0],
withinBandwidth: true,
};
}
const currentValue = data[leftIndex - 1];
// pure linear scale
if (this.minInterval === 0) {
const nextValue = data[leftIndex];
const nextDiff = Math.abs(nextValue - invertedValue);
const prevDiff = Math.abs(invertedValue - currentValue);
return {
value: nextDiff <= prevDiff ? nextValue : currentValue,
withinBandwidth: true,
};
}
if (invertedValue - currentValue <= this.minInterval) {
return {
value: currentValue,
withinBandwidth: true,
};
}
return {
value: currentValue + this.minInterval * Math.floor((invertedValue - currentValue) / this.minInterval),
withinBandwidth: false,
};
}
isSingleValue() {
if (this.isSingleValueHistogram) {
return true;
}
if (this.domain.length < 2) {
return true;
}
const min = this.domain[0];
const max = this.domain[this.domain.length - 1];
return max === min;
}
isValueInDomain(value: number) {
return value >= this.domain[0] && value <= this.domain[1];
}
}
export function isLogarithmicScale(scale: Scale) {
return scale.type === ScaleType.Log;
}