-
Notifications
You must be signed in to change notification settings - Fork 53
/
gridScale.js
373 lines (323 loc) · 11.6 KB
/
gridScale.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Grid scale is a part of layout that can vary
// depending on overlay (values that correspond to y-axis)
// TODO: feature: display only overlays on the current scale
import Const from '../stuff/constants.js'
import Utils from '../stuff/utils.js'
import math from '../stuff/math.js'
import logScale from './logScale.js'
import MetaHub from '../core/metaHub.js'
import ScriptHub from '../core/scripts.js'
const { $SCALES } = Const
const MAX_INT = Number.MAX_SAFE_INTEGER
export default function Scale(id, src, specs) {
let { hub, props, settings, height } = specs
let { ctx } = props
let meta = MetaHub.instance(props.id)
let prefabs = ScriptHub.instance(props.id).prefabs
let self = {}
let yt = (meta.yTransforms[src.gridId] || [])[id]
let gridId = src.gridId
let ovs = src.ovs
let ls = src.log
const SAMPLE = props.config.AUTO_PRE_SAMPLE
function calcSidebar() {
let maxlen = Math.max(...ovs.map(x => x.dataSubset.length))
if (maxlen < 2) {
self.prec = 0
self.sb = props.config.SBMIN
return
}
// TODO: add custom formatter f()
if (src.precision !== undefined) {
self.prec = src.precision
} else {
self.prec = 0
// Find max precision over all overlays on
// this scale
for (var ov of ovs) {
if (ov.settings.precision !== undefined) {
var prec = ov.settings.precision
} else {
var prec = calcPrecision(ov)
}
if (prec > self.prec) self.prec = prec
}
}
if (!isFinite(self.$hi) || !isFinite(self.$lo) ) {
self.sb = props.config.SBMIN
return
}
let lens = []
lens.push(self.$hi.toFixed(self.prec).length)
lens.push(self.$lo.toFixed(self.prec).length)
let str = '0'.repeat(Math.max(...lens)) + ' '
self.sb = ctx.measureText(str).width
self.sb = Math.max(Math.floor(self.sb), props.config.SBMIN)
self.sb = Math.min(self.sb, props.config.SBMAX)
// Prevent sb calculation before meta data
// extracted from the scripts
// if (!meta.ready) self.sb = props.config.SBMIN
}
// Calc vertical value range
function calc$Range() {
// Need to find minimum & maximum of selected
// set of overlays (on the same scale)
var hi = -Infinity, lo = Infinity
for (var ov of ovs) {
if (ov.settings.display === false) continue
let yfn = (meta.yRangeFns[gridId] || [])[ov.id]
let yfnStatic = prefabs[ov.type].static.yRange
if (yfnStatic) {
yfn = {
exec: yfnStatic,
preCalc: yfnStatic.length > 1 // Do we need h & l
}
}
let data = ov.dataSubset
// Intermediate hi & lo
var h = -Infinity, l = Infinity
// Look for a user-defined y-range f()
// or calculate through iteration. 'preCalc'
// flag tells if pre-calculated h&l needed
// TODO: implement a global auto-precision algo
if (!yfn || (yfn && yfn.preCalc)) {
for (var i = 0; i < data.length; i++) {
for (var j = 1; j < data[i].length; j++) {
let v = data[i][j]
if (v > h) h = v
if (v < l) l = v
}
}
}
if (yfn) {
// Check if result is 'null', then this overlay
// should not affect the range at all
var yfnResult = yfn.exec(data, h, l)
if (yfnResult) {
var [h, l, exp] = yfnResult
} else {
var [h, l] = [hi, lo]
}
}
// maximum & minimum over all overlays
if (h > hi) hi = h
if (l < lo) lo = l
}
// Fixed y-range in non-auto mode
if (yt && !yt.auto && yt.range) {
self.$hi = yt.range[0]
self.$lo = yt.range[1]
} else {
if (!ls) {
exp = exp === false ? 0 : 1
self.$hi = hi + (hi - lo) * props.config.EXPAND * exp
self.$lo = lo - (hi - lo) * props.config.EXPAND * exp
} else {
self.$hi = hi
self.$lo = lo
logScale.expand(self, height)
}
if (self.$hi === self.$lo) {
if (!ls) {
self.$hi *= 1.05 // Expand if height range === 0
self.$lo *= 0.95
} else {
logScale.expand(self, height)
}
}
}
}
// Calculate $ precision for the Y-axis of an overlay
function calcPrecision(ov) {
// Maximum digits after floating point
let maxR = 0
let sample = []
// Sample N random elements from the current subset
let f = meta.getPreSampler(gridId, ov.id)
f = f || prefabs[ov.type].static.preSampler
f = f || Utils.defaultPreSampler
for (var i = 0; i < SAMPLE; i++) {
// Random element n
let n = Math.floor(Math.random() * ov.dataSubset.length)
let x = f(ov.dataSubset[n])
if (typeof x === 'number') sample.push(x)
else sample = sample.concat(x)
}
sample.forEach(x => {
let right = Utils.numberLR(x)[1]
if (right > maxR) maxR = right
})
// Update stored auto-precision
let aprec = meta.getAutoPrec(gridId, ov.id)
if (aprec === undefined || maxR > aprec) {
meta.setAutoPrec(gridId, ov.id, maxR)
return maxR
}
return aprec
}
function calcTransform() {
// Candle Y-transform: (A = scale, B = shift)
if (!ls) {
self.A = - height / (self.$hi - self.$lo)
self.B = - self.$hi * self.A
} else {
self.A = - height / (math.log(self.$hi) -
math.log(self.$lo))
self.B = - math.log(self.$hi) * self.A
}
}
// Select nearest good-loking $ step (m is target scale)
function dollarStep() {
let yrange = self.$hi - self.$lo
let m = yrange * (props.config.GRIDY / height)
let p = parseInt(yrange.toExponential().split('e')[1])
let d = Math.pow(10, p)
let s = $SCALES.map(x => x * d)
// TODO: center the range (look at RSI for example,
// it looks ugly when "80" is near the top)
return Utils.strip(Utils.nearestA(m, s)[1])
}
function dollarMult() {
let mult_hi = dollarMultHi()
let mult_lo = dollarMultLo()
return Math.max(mult_hi, mult_lo)
}
// Price step multiplier (for the log-scale mode)
function dollarMultHi() {
let h = Math.min(self.B, height)
if (h < props.config.GRIDY) return 1
let n = h / props.config.GRIDY // target grid N
let yrange = self.$hi
if (self.$lo > 0) {
var yratio = self.$hi / self.$lo
} else {
yratio = self.$hi / 1 // TODO: small values
}
let m = yrange * (props.config.GRIDY / h)
let p = parseInt(yrange.toExponential().split('e')[1])
return Math.pow(yratio, 1/n)
}
function dollarMultLo() {
let h = Math.min(height - self.B, height)
if (h < props.config.GRIDY) return 1
let n = h / props.config.GRIDY // target grid N
let yrange = Math.abs(self.$lo)
if (self.$hi < 0 && self.$lo < 0) {
var yratio = Math.abs(self.$lo / self.$hi)
} else {
yratio = Math.abs(self.$lo) / 1
}
let m = yrange * (props.config.GRIDY / h)
let p = parseInt(yrange.toExponential().split('e')[1])
return Math.pow(yratio, 1/n)
}
// Build the Y-axis grid (non-log mode)
function gridY() {
// Prevent duplicate levels
let m = Math.pow(10, -self.prec)
self.$step = Math.max(m, dollarStep())
self.ys = []
let y1 = self.$lo - self.$lo % self.$step
for (var y$ = y1; y$ <= self.$hi; y$ += self.$step) {
let y = Math.floor(y$ * self.A + self.B)
if (y > height) continue
self.ys.push([y, Utils.strip(y$)])
}
}
// Build the Y-axis grid (log mode)
function gridYLog() {
// TODO: Prevent duplicate levels, is this even
// a problem here ?
self.$_mult = dollarMult()
self.ys = []
let v = (self.$hi + self.$lo) / 2 // Use mid point
let y1 = searchStartPos(v)
let y2 = searchStartNeg(-v)
let yp = -Infinity // Previous y value
let n = height / props.config.GRIDY // target grid N
let q = 1 + (self.$_mult - 1) / 2
// Over 0
for (var y$ = y1; y$ > 0; y$ /= self.$_mult) {
y$ = logRounder(y$, q)
let y = Math.floor(math.log(y$) * self.A + self.B)
self.ys.push([y, Utils.strip(y$)])
if (y > height) break
if (y - yp < props.config.GRIDY * 0.7) break
if (self.ys.length > n + 1) break
yp = y
}
// Under 0
yp = Infinity
for (var y$ = y2; y$ < 0; y$ /= self.$_mult) {
y$ = logRounder(y$, q)
let y = Math.floor(math.log(y$) * self.A + self.B)
if (yp - y < props.config.GRIDY * 0.7) break
self.ys.push([y, Utils.strip(y$)])
if (y < 0) break
if (self.ys.length > n * 3 + 1) break
yp = y
}
// TODO: remove lines near to 0
}
// Search a start for the top grid so that
// the fixed value always included
function searchStartPos(value) {
let N = height / props.config.GRIDY // target grid N
var y = Infinity, y$ = value, count = 0
while (y > 0) {
y = Math.floor(math.log(y$) * self.A + self.B)
y$ *= self.$_mult
if (count++ > N * 3) return 0 // Prevents deadloops
}
return y$
}
function searchStartNeg(value) {
let N = height / props.config.GRIDY // target grid N
var y = -Infinity, y$ = value, count = 0
while (y < height) {
y = Math.floor(math.log(y$) * self.A + self.B)
y$ *= self.$_mult
if (count++ > N * 3) break // Prevents deadloops
}
return y$
}
// Make log scale levels look great again
function logRounder(x, quality) {
let s = Math.sign(x)
x = Math.abs(x)
if (x > 10) {
for (var div = 10; div < MAX_INT; div *= 10) {
let nice = Math.floor(x / div) * div
if (x / nice > quality) { // More than 10% off
break
}
}
div /= 10
return s * Math.floor(x / div) * div
} else if (x < 1) {
for (var ro = 10; ro >= 1; ro--) {
let nice = Utils.round(x, ro)
if (x / nice > quality) { // More than 10% off
break
}
}
return s * Utils.round(x, ro + 1)
} else {
return s * Math.floor(x)
}
}
calc$Range()
calcSidebar()
calcTransform()
;ls ? gridYLog() : gridY()
// Indices of the overlays using this scale (ovIdxs).
// Needed when the final layout is built
// (see overlayEnv)
self.scaleSpecs = {
id: id,
log: src.log,
ovIdxs: src.ovIdxs
}
self.height = height
return self
}