forked from manzt/zarrita.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixedscaleoffset.ts
More file actions
56 lines (48 loc) · 1.64 KB
/
fixedscaleoffset.ts
File metadata and controls
56 lines (48 loc) · 1.64 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
import type { Chunk, NumberDataType, TypedArrayConstructor } from "../metadata.js"
import { coerce_dtype, get_ctr } from "../util.js"
type FixedScaleOffsetConfig = {
offset: number;
scale: number;
dtype: string;
astype?: string;
}
export class FixedScaleOffsetCodec<D extends NumberDataType, A extends NumberDataType> {
readonly kind = "array_to_array";
#offset: number;
#scale: number;
#TypedArrayIn: TypedArrayConstructor<D>
#TypedArrayOut: TypedArrayConstructor<A>
constructor(configuration: FixedScaleOffsetConfig) {
const { data_type } = coerce_dtype(configuration.dtype);
this.#TypedArrayIn = get_ctr(data_type as NumberDataType);
const { data_type: as_data_type } = coerce_dtype(configuration.astype ?? configuration.dtype);
this.#TypedArrayOut = get_ctr(as_data_type as NumberDataType);
this.#offset = configuration.offset;
this.#scale = configuration.scale;
}
static fromConfig(configuration: FixedScaleOffsetConfig) {
return new FixedScaleOffsetCodec(configuration);
}
encode(arr: Chunk<D>): Chunk<A> {
const data = new this.#TypedArrayOut(arr.data.length);
arr.data.forEach((value: number, i: number) => {
data[i] = (value - this.#offset) * this.#scale;
});
return {
data,
shape: arr.shape,
stride: arr.stride
}
}
decode(arr: Chunk<A>): Chunk<D> {
const out_data = new this.#TypedArrayIn(arr.data.length);
arr.data.forEach((value: number, i: number) => {
out_data[i] = (value / this.#scale) + this.#offset;
});
return {
data: out_data,
shape: arr.shape,
stride: arr.stride,
};
}
}