|
5 | 5 | * Copyright 2021 GraphMetrics for modifications |
6 | 6 | */ |
7 | 7 |
|
8 | | -import { KeyMapping, MIN_INT_16, MAX_INT_16 } from './KeyMapping'; |
| 8 | +import { |
| 9 | + EXP_OVERFLOW, |
| 10 | + MAX_INT_16, |
| 11 | + MIN_INT_16, |
| 12 | + MIN_SAFE_FLOAT, |
| 13 | + withinTolerance |
| 14 | +} from './helpers'; |
| 15 | +import { IndexMapping } from './types'; |
9 | 16 |
|
10 | 17 | /** |
11 | 18 | * A memory-optimal KeyMapping, i.e., given a targeted relative accuracy, it |
12 | 19 | * requires the least number of keys to cover a given range of values. This is |
13 | 20 | * done by logarithmically mapping floating-point values to integers. |
14 | 21 | */ |
15 | | -export class LogarithmicMapping extends KeyMapping { |
16 | | - constructor(relativeAccuracy: number, offset = 0) { |
17 | | - super(relativeAccuracy, offset); |
18 | | - this._multiplier *= Math.log(2); |
19 | | - this.minPossible = Math.max( |
20 | | - Math.pow(2, (MIN_INT_16 - this._offset) / this._multiplier + 1), |
21 | | - this.minPossible |
| 22 | +export class LogarithmicMapping implements IndexMapping { |
| 23 | + public readonly relativeAccuracy: number; |
| 24 | + public readonly minIndexableValue: number; |
| 25 | + public readonly maxIndexableValue: number; |
| 26 | + private readonly multiplier: number; |
| 27 | + |
| 28 | + constructor(relativeAccuracy: number) { |
| 29 | + this.relativeAccuracy = relativeAccuracy; |
| 30 | + this.multiplier = |
| 31 | + 1 / Math.log1p((2 * relativeAccuracy) / (1 - relativeAccuracy)); |
| 32 | + this.minIndexableValue = Math.max( |
| 33 | + Math.exp(MIN_INT_16 / this.multiplier + 1), |
| 34 | + (MIN_SAFE_FLOAT * (1 + relativeAccuracy)) / (1 - relativeAccuracy) |
22 | 35 | ); |
23 | | - this.maxPossible = Math.min( |
24 | | - Math.pow(2, (MAX_INT_16 - this._offset) / this._multiplier - 1), |
25 | | - this.maxPossible |
| 36 | + this.maxIndexableValue = Math.min( |
| 37 | + Math.exp(MAX_INT_16 / this.multiplier - 1), |
| 38 | + Math.exp(EXP_OVERFLOW) / (1 + relativeAccuracy) |
26 | 39 | ); |
27 | 40 | } |
28 | 41 |
|
29 | | - _logGamma(value: number): number { |
30 | | - return Math.log2(value) * this._multiplier; |
| 42 | + public index(value: number): number { |
| 43 | + const index = Math.log(value) * this.multiplier; |
| 44 | + if (index >= 0) { |
| 45 | + return ~~index; |
| 46 | + } else { |
| 47 | + return ~~index - 1; // faster than Math.Floor |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public value(index: number): number { |
| 52 | + return Math.exp(index / this.multiplier) * (1 + this.relativeAccuracy); |
31 | 53 | } |
32 | 54 |
|
33 | | - _powGamma(value: number): number { |
34 | | - return Math.pow(2, value / this._multiplier); |
| 55 | + public equals(other: IndexMapping): boolean { |
| 56 | + if (!(other instanceof LogarithmicMapping)) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + return withinTolerance(this.multiplier, other.multiplier, 1e-12); |
35 | 60 | } |
36 | 61 | } |
0 commit comments