-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhierarchy.ts
236 lines (217 loc) · 6.47 KB
/
hierarchy.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
import type { AbsolutePath, Readable } from "@zarrita/storage";
import { create_codec_pipeline } from "./codecs.js";
import { create_sharded_chunk_getter } from "./codecs/sharding.js";
import type {
ArrayMetadata,
Attributes,
Chunk,
CodecMetadata,
DataType,
GroupMetadata,
Scalar,
TypedArrayConstructor,
} from "./metadata.js";
import {
type DataTypeQuery,
type NarrowDataType,
is_dtype,
is_sharding_codec,
} from "./util.js";
import {
create_chunk_key_encoder,
ensure_correct_scalar,
get_ctr,
get_strides,
} from "./util.js";
export class Location<Store> {
constructor(
public readonly store: Store,
public readonly path: AbsolutePath = "/",
) {}
resolve(path: string): Location<Store> {
// reuse URL resolution logic built into the browser
// handles relative paths, absolute paths, etc.
let root = new URL(
`file://${this.path.endsWith("/") ? this.path : `${this.path}/`}`,
);
return new Location(
this.store,
new URL(path, root).pathname as AbsolutePath,
);
}
}
export function root<Store>(store: Store): Location<Store>;
export function root(): Location<Map<string, Uint8Array>>;
export function root<Store>(
store?: Store,
): Location<Store | Map<string, Uint8Array>> {
return new Location(store ?? new Map());
}
export class Group<Store extends Readable> extends Location<Store> {
readonly kind = "group";
#metadata: GroupMetadata;
constructor(store: Store, path: AbsolutePath, metadata: GroupMetadata) {
super(store, path);
this.#metadata = metadata;
}
get attrs(): Attributes {
return this.#metadata.attributes;
}
}
function get_array_order(
codecs: CodecMetadata[],
): "C" | "F" | globalThis.Array<number> {
const maybe_transpose_codec = codecs.find((c) => c.name === "transpose");
// @ts-expect-error - TODO: Should validate?
return maybe_transpose_codec?.configuration?.order ?? "C";
}
const CONTEXT_MARKER = Symbol("zarrita.context");
export function get_context<T>(obj: { [CONTEXT_MARKER]: T }): T {
return obj[CONTEXT_MARKER];
}
function create_context<Store extends Readable, D extends DataType>(
location: Location<Readable>,
metadata: ArrayMetadata<D>,
): ArrayContext<Store, D> {
let { configuration } = metadata.codecs.find(is_sharding_codec) ?? {};
let shared_context = {
encode_chunk_key: create_chunk_key_encoder(metadata.chunk_key_encoding),
TypedArray: get_ctr(metadata.data_type),
fill_value: metadata.fill_value,
};
if (configuration) {
let native_order = get_array_order(configuration.codecs);
return {
...shared_context,
kind: "sharded",
chunk_shape: configuration.chunk_shape,
codec: create_codec_pipeline({
data_type: metadata.data_type,
shape: configuration.chunk_shape,
codecs: configuration.codecs,
}),
get_strides(shape: number[], order?: "C" | "F") {
return get_strides(shape, order ?? native_order);
},
get_chunk_bytes: create_sharded_chunk_getter(
location,
metadata.chunk_grid.configuration.chunk_shape,
shared_context.encode_chunk_key,
configuration,
),
};
}
let native_order = get_array_order(metadata.codecs);
return {
...shared_context,
kind: "regular",
chunk_shape: metadata.chunk_grid.configuration.chunk_shape,
codec: create_codec_pipeline({
data_type: metadata.data_type,
shape: metadata.chunk_grid.configuration.chunk_shape,
codecs: metadata.codecs,
}),
get_strides(shape: number[], order?: "C" | "F") {
return get_strides(shape, order ?? native_order);
},
async get_chunk_bytes(chunk_coords, options) {
let chunk_key = shared_context.encode_chunk_key(chunk_coords);
let chunk_path = location.resolve(chunk_key).path;
return location.store.get(chunk_path, options);
},
};
}
/** For internal use only, and is subject to change. */
interface ArrayContext<Store extends Readable, D extends DataType> {
kind: "sharded" | "regular";
/** The codec pipeline for this array. */
codec: ReturnType<typeof create_codec_pipeline<D>>;
/** Encode a chunk key from chunk coordinates. */
encode_chunk_key(chunk_coords: number[]): string;
/** The TypedArray constructor for this array chunks. */
TypedArray: TypedArrayConstructor<D>;
/** A function to get the strides for a given shape, using the array order */
get_strides(shape: number[], order?: "C" | "F"): number[];
/** The fill value for this array. */
fill_value: Scalar<D> | null;
/** A function to get the bytes for a given chunk. */
get_chunk_bytes(
chunk_coords: number[],
options?: Parameters<Store["get"]>[1],
): Promise<Uint8Array | undefined>;
/** The chunk shape for this array. */
chunk_shape: number[];
}
export class Array<
Dtype extends DataType,
Store extends Readable = Readable,
> extends Location<Store> {
readonly kind = "array";
#metadata: ArrayMetadata<Dtype>;
[CONTEXT_MARKER]: ArrayContext<Store, Dtype>;
constructor(
store: Store,
path: AbsolutePath,
metadata: ArrayMetadata<Dtype>,
) {
super(store, path);
this.#metadata = {
...metadata,
fill_value: ensure_correct_scalar(metadata),
};
this[CONTEXT_MARKER] = create_context(this, metadata);
}
get attrs(): Attributes {
return this.#metadata.attributes;
}
get shape(): number[] {
return this.#metadata.shape;
}
get chunks(): number[] {
return this[CONTEXT_MARKER].chunk_shape;
}
get dtype(): Dtype {
return this.#metadata.data_type;
}
async getChunk(
chunk_coords: number[],
options?: Parameters<Store["get"]>[1],
): Promise<Chunk<Dtype>> {
let context = this[CONTEXT_MARKER];
let maybe_bytes = await context.get_chunk_bytes(chunk_coords, options);
if (!maybe_bytes) {
let size = context.chunk_shape.reduce((a, b) => a * b, 1);
let data = new context.TypedArray(size);
// @ts-expect-error: TS can't infer that `fill_value` is union (assumes never) but this is ok
data.fill(context.fill_value);
return {
data,
shape: context.chunk_shape,
stride: context.get_strides(context.chunk_shape),
};
}
return context.codec.decode(maybe_bytes);
}
/**
* A helper method to narrow `zarr.Array` Dtype.
*
* ```typescript
* let arr: zarr.Array<DataType, FetchStore> = zarr.open(store, { kind: "array" });
*
* // Option 1: narrow by scalar type (e.g. "bool", "raw", "bigint", "number")
* if (arr.is("bigint")) {
* // zarr.Array<"int64" | "uint64", FetchStore>
* }
*
* // Option 3: exact match
* if (arr.is("float32")) {
* // zarr.Array<"float32", FetchStore, "/">
* }
* ```
*/
is<Query extends DataTypeQuery>(
query: Query,
): this is Array<NarrowDataType<Dtype, Query>, Store> {
return is_dtype(this.dtype, query);
}
}