forked from hms-dbmi/vizarr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathome.ts
271 lines (239 loc) · 8.87 KB
/
ome.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
import { ZarrPixelSource } from '@hms-dbmi/viv';
import pMap from 'p-map';
import { Group as ZarrGroup, HTTPStore, openGroup, ZarrArray } from 'zarr';
import type { ImageLayerConfig, SourceData } from './state';
import {
getAttrsOnly,
guessTileSize,
join,
loadMultiscales,
parseMatrix,
range
} from './utils';
export async function loadWell(config: ImageLayerConfig, grp: ZarrGroup, wellAttrs: Ome.Well): Promise<SourceData> {
// Can filter Well fields by URL query ?acquisition=ID
const acquisitionId: number | undefined = config.acquisition ? parseInt(config.acquisition) : undefined;
let acquisitions: Ome.Acquisition[] = [];
if (!wellAttrs?.images) {
throw Error(`Well .zattrs missing images`);
}
if (!(grp.store instanceof HTTPStore)) {
throw Error('Store must be an HTTPStore to open well.');
}
const [row, col] = grp.store.url.split('/').filter(Boolean).slice(-2);
let { images } = wellAttrs;
// Do we have more than 1 Acquisition?
const acqIds = images.flatMap((img) => (img.acquisition ? [img.acquisition] : []));
if (acqIds.length > 1) {
// Need to get acquisitions metadata from parent Plate
const plateUrl = grp.store.url.replace(`${row}/${col}`, '');
const plate = await openGroup(new HTTPStore(plateUrl));
const plateAttrs = (await plate.attrs.asObject()) as { plate: Ome.Plate };
acquisitions = plateAttrs?.plate?.acquisitions ?? [];
// filter imagePaths by acquisition
if (acquisitionId && acqIds.includes(acquisitionId)) {
images = images.filter((img) => img.acquisition === acquisitionId);
}
}
const imgPaths = images.map((img) => img.path);
const cols = Math.ceil(Math.sqrt(imgPaths.length));
const rows = Math.ceil(imgPaths.length / cols);
// Use first image for rendering settings, resolutions etc.
const imgAttrs = (await grp.getItem(imgPaths[0]).then((g) => g.attrs.asObject())) as Ome.Attrs;
if (!('omero' in imgAttrs)) {
throw Error('Path for image is not valid.');
}
let resolution = imgAttrs.multiscales[0].datasets[0].path;
// Create loader for every Image.
const promises = imgPaths.map((p) => grp.getItem(join(p, resolution)));
const data = (await Promise.all(promises)) as ZarrArray[];
const axis_labels = getOmeAxisLabels(imgAttrs.multiscales);
const meta = parseOmeroMeta(imgAttrs.omero, axis_labels);
const tileSize = guessTileSize(data[0]);
const loaders = range(rows).flatMap((row) => {
return range(cols).map((col) => {
const offset = col + row * cols;
return { name: String(offset), row, col, loader: new ZarrPixelSource(data[offset], axis_labels, tileSize) };
});
});
const sourceData: SourceData = {
loaders,
...meta,
axis_labels,
loader: [loaders[0].loader],
model_matrix: parseMatrix(config.model_matrix),
defaults: {
selection: meta.defaultSelection,
colormap: config.colormap ?? '',
opacity: config.opacity ?? 1,
},
name: `Well ${row}${col}`,
};
if (acquisitions.length > 0) {
// To show acquisition chooser in UI
sourceData.acquisitions = acquisitions;
sourceData.acquisitionId = acquisitionId || -1;
}
sourceData.rows = rows;
sourceData.columns = cols;
sourceData.onClick = (info: any) => {
let gridCoord = info.gridCoord;
if (!gridCoord) {
return;
}
const { row, column } = gridCoord;
let imgSource = undefined;
if (grp.store instanceof HTTPStore && !isNaN(row) && !isNaN(column)) {
const field = row * cols + column;
imgSource = join(grp.store.url, imgPaths[field]);
}
if (config.onClick) {
delete info.layer;
info.imageSource = imgSource;
config.onClick(info);
} else if (imgSource) {
window.open(window.location.origin + window.location.pathname + '?source=' + imgSource);
}
};
return sourceData;
}
export async function loadPlate(config: ImageLayerConfig, grp: ZarrGroup, plateAttrs: Ome.Plate): Promise<SourceData> {
if (!('columns' in plateAttrs) || !('rows' in plateAttrs)) {
throw Error(`Plate .zattrs missing columns or rows`);
}
const rows = plateAttrs.rows.map((row) => row.name);
const columns = plateAttrs.columns.map((row) => row.name);
// Fields are by index and we assume at least 1 per Well
const wellPaths = plateAttrs.wells.map((well) => well.path);
// Use first image as proxy for others.
const wellAttrs = await getAttrsOnly<{ well: Ome.Well }>(grp, wellPaths[0]);
if (!('well' in wellAttrs)) {
throw Error('Path for image is not valid, not a well.');
}
const imgPath = wellAttrs.well.images[0].path;
const imgAttrs = (await grp.getItem(join(wellPaths[0], imgPath)).then((g) => g.attrs.asObject())) as Ome.Attrs;
if (!('omero' in imgAttrs)) {
throw Error('Path for image is not valid.');
}
// Lowest resolution is the 'path' of the last 'dataset' from the first multiscales
const { datasets } = imgAttrs.multiscales[0];
const resolution = datasets[datasets.length - 1].path;
async function getImgPath(wellPath:string) {
const wellAttrs = await getAttrsOnly<{ well: Ome.Well }>(grp, wellPath);
return join(wellPath, wellAttrs.well.images[0].path);
}
const wellImagePaths = await Promise.all(wellPaths.map(getImgPath));
// Create loader for every Well. Some loaders may be undefined if Wells are missing.
const mapper = ([key, path]: string[]) => grp.getItem(path).then((arr) => [key, arr]) as Promise<[string, ZarrArray]>;
const promises = await pMap(
wellImagePaths.map((p) => [p, join(p, resolution)]),
mapper,
{ concurrency: 10 }
);
const data = await Promise.all(promises);
const axis_labels = getOmeAxisLabels(imgAttrs.multiscales);
const meta = parseOmeroMeta(imgAttrs.omero, axis_labels);
const tileSize = guessTileSize(data[0][1]);
const loaders = data.map((d) => {
const [row, col] = d[0].split('/');
return {
name: `${row}${col}`,
row: rows.indexOf(row),
col: columns.indexOf(col),
loader: new ZarrPixelSource(d[1], axis_labels, tileSize),
};
});
// Load Image to use for channel names, rendering settings, sizeZ, sizeT etc.
const sourceData: SourceData = {
loaders,
...meta,
axis_labels,
loader: [loaders[0].loader],
model_matrix: parseMatrix(config.model_matrix),
defaults: {
selection: meta.defaultSelection,
colormap: config.colormap ?? '',
opacity: config.opacity ?? 1,
},
name: plateAttrs.name || 'Plate',
rows: rows.length,
columns: columns.length,
};
// Us onClick from image config or Open Well in new window
sourceData.onClick = (info: any) => {
let gridCoord = info.gridCoord;
if (!gridCoord) {
return;
}
const { row, column } = gridCoord;
let imgSource = undefined;
// TODO: use a regex for the path??
if (grp.store instanceof HTTPStore && !isNaN(row) && !isNaN(column)) {
imgSource = join(grp.store.url, rows[row], columns[column]);
}
if (config.onClick) {
delete info.layer;
info.imageSource = imgSource;
config.onClick(info);
} else if (imgSource) {
window.open(window.location.origin + window.location.pathname + '?source=' + imgSource);
}
};
return sourceData;
}
export async function loadOmeroMultiscales(
config: ImageLayerConfig,
grp: ZarrGroup,
attrs: { multiscales: Ome.Multiscale[]; omero: Ome.Omero }
): Promise<SourceData> {
const { name, opacity = 1, colormap = '' } = config;
const data = await loadMultiscales(grp, attrs.multiscales);
const axis_labels = getOmeAxisLabels(attrs.multiscales);
const meta = parseOmeroMeta(attrs.omero, axis_labels);
const tileSize = guessTileSize(data[0]);
const loader = data.map((arr) => new ZarrPixelSource(arr, axis_labels, tileSize));
return {
loader: loader,
axis_labels,
name: meta.name ?? name,
model_matrix: parseMatrix(config.model_matrix),
defaults: {
selection: meta.defaultSelection,
colormap,
opacity,
},
...meta,
};
}
function parseOmeroMeta({ rdefs, channels, name }: Ome.Omero, axis_labels: string[]) {
const t = rdefs.defaultT ?? 0;
const z = rdefs.defaultZ ?? 0;
const colors: string[] = [];
const contrast_limits: number[][] = [];
const visibilities: boolean[] = [];
const names: string[] = [];
channels.forEach((c) => {
colors.push(c.color);
contrast_limits.push([c.window.start, c.window.end]);
visibilities.push(c.active);
names.push(c.label);
});
const defaultSelection = axis_labels.map((label) => {
if (label == 't') return t;
if (label == 'z') return z;
return 0;
});
return {
name,
names,
colors,
contrast_limits,
visibilities,
channel_axis: axis_labels.includes('c') ? axis_labels.indexOf('c') : null,
defaultSelection,
};
}
function getOmeAxisLabels(multiscales: Ome.Multiscale[]): [...string[], 'y', 'x'] {
const default_axes = ['t', 'c', 'z', 'y', 'x']; // v0.1 & v0.2
return (multiscales[0].axes || default_axes) as [...string[], 'y', 'x'];
}