-
Notifications
You must be signed in to change notification settings - Fork 18
/
io.ts
240 lines (217 loc) · 7.34 KB
/
io.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
import { DTYPE_VALUES, ImageLayer, MultiscaleImageLayer, ZarrPixelSource } from '@hms-dbmi/viv';
import { Group as ZarrGroup, HTTPStore, openGroup, ZarrArray } from 'zarr';
import GridLayer from './gridLayer';
import { loadOmeroMultiscales, loadPlate, loadWell } from './ome';
import type {
ImageLayerConfig,
LayerState,
MultichannelConfig,
SingleChannelConfig,
SourceData,
LayerCtr,
} from './state';
import {
COLORS,
CYMRGB,
getAxisLabels,
guessTileSize,
hexToRGB,
loadMultiscales,
MAGENTA_GREEN,
MAX_CHANNELS,
open,
parseMatrix,
range,
RGB,
} from './utils';
function loadSingleChannel(config: SingleChannelConfig, data: ZarrPixelSource<string[]>[], max: number): SourceData {
const { color, contrast_limits, visibility, name, colormap = '', opacity = 1 } = config;
return {
loader: data,
name,
channel_axis: null,
colors: [color ?? COLORS.white],
names: ['channel_0'],
contrast_limits: [contrast_limits ?? [0, max]],
visibilities: [visibility ?? true],
model_matrix: parseMatrix(config.model_matrix),
defaults: {
selection: Array(data[0].shape.length).fill(0),
colormap,
opacity,
},
axis_labels: data[0].labels,
};
}
function loadMultiChannel(config: MultichannelConfig, data: ZarrPixelSource<string[]>[], max: number): SourceData {
const { names, channel_axis, name, model_matrix, opacity = 1, colormap = '' } = config;
let { contrast_limits, visibilities, colors } = config;
const n = data[0].shape[channel_axis as number];
for (const channelProp of [contrast_limits, visibilities, names, colors]) {
if (channelProp && channelProp.length !== n) {
const propertyName = Object.keys({ channelProp })[0];
throw Error(`channel_axis is length ${n} and provided channel_axis property ${propertyName} is different size.`);
}
}
if (!visibilities) {
if (n <= MAX_CHANNELS) {
// Default to all on if visibilities not specified and less than 6 channels.
visibilities = Array(n).fill(true);
} else {
// If more than MAX_CHANNELS, only make first set on by default.
visibilities = [...Array(MAX_CHANNELS).fill(true), ...Array(n - MAX_CHANNELS).fill(false)];
}
}
if (!colors) {
if (n == 1) {
colors = [COLORS.white];
} else if (n == 2) {
colors = MAGENTA_GREEN;
} else if (n === 3) {
colors = RGB;
} else if (n <= MAX_CHANNELS) {
colors = CYMRGB.slice(0, n);
} else {
// Default color for non-visible is white
colors = Array(n).fill(COLORS.white);
// Get visible indices
const visibleIndices = visibilities.flatMap((bool, i) => (bool ? i : []));
// Set visible indices to CYMRGB colors. visibleIndices.length === MAX_CHANNELS from above.
for (const [i, visibleIndex] of visibleIndices.entries()) {
colors[visibleIndex] = CYMRGB[i];
}
}
}
return {
loader: data,
name,
channel_axis: Number(channel_axis as number),
colors,
names: names ?? range(n).map((i) => `channel_${i}`),
contrast_limits: contrast_limits ?? Array(n).fill([0, max]),
visibilities,
model_matrix: parseMatrix(config.model_matrix),
defaults: {
selection: Array(data[0].shape.length).fill(0),
colormap,
opacity,
},
axis_labels: data[0].labels,
};
}
export async function createSourceData(config: ImageLayerConfig): Promise<SourceData> {
const node = await open(config.source);
let data: ZarrArray[];
if (node instanceof ZarrGroup) {
const attrs = (await node.attrs.asObject()) as Ome.Attrs;
if ('plate' in attrs) {
return loadPlate(config, node, attrs.plate);
}
if ('well' in attrs) {
return loadWell(config, node, attrs.well);
}
if ('omero' in attrs) {
return loadOmeroMultiscales(config, node, attrs);
}
if (Object.keys(attrs).length === 0 && node.store instanceof HTTPStore) {
// No rootAttrs in this group.
// if url is to a plate/acquisition/ check parent dir for 'plate' zattrs
const parentUrl = node.store.url.slice(0, node.store.url.lastIndexOf('/'));
const parent = await openGroup(new HTTPStore(parentUrl));
const parentAttrs = (await parent.attrs.asObject()) as Ome.Attrs;
if ('plate' in parentAttrs) {
return loadPlate(config, parent, parentAttrs.plate);
}
}
if (!('multiscales' in attrs)) {
throw Error('Group is missing multiscales specification.');
}
data = await loadMultiscales(node, attrs.multiscales);
if (!config.axis_labels) {
// Update config axis_labels if present in multiscales
config.axis_labels = attrs.multiscales[0].axes;
}
} else {
data = [node];
}
const labels = getAxisLabels(data[0], config.axis_labels);
const tileSize = guessTileSize(data[0]);
const loader = data.map((d) => new ZarrPixelSource(d, labels, tileSize));
const [base] = loader;
// If contrast_limits not provided or are missing from omero metadata.
const max = base.dtype === 'Float32' ? 1 : DTYPE_VALUES[base.dtype].max;
// Now that we have data, try to figure out how to render initially.
// If explicit channel axis is provided, try to load as multichannel.
if ('channel_axis' in config || labels.includes('c')) {
config = config as MultichannelConfig;
config.channel_axis = config.channel_axis ?? labels.indexOf('c');
return loadMultiChannel(config, loader, max);
}
const nDims = base.shape.length;
if (nDims === 2 || !('channel_axis' in config)) {
return loadSingleChannel(config as SingleChannelConfig, loader, max);
}
throw Error('Failed to load image.');
}
export function initLayerStateFromSource(sourceData: SourceData): LayerState {
const {
loader,
channel_axis,
colors,
visibilities,
contrast_limits,
model_matrix,
defaults,
// Grid
loaders,
rows,
columns,
onClick,
} = sourceData;
const { selection, opacity, colormap } = defaults;
const Layer = getLayer(sourceData);
const loaderSelection: number[][] = [];
const colorValues: number[][] = [];
const contrastLimits: number[][] = [];
const channelIsOn: boolean[] = [];
const visibleIndices = visibilities.flatMap((bool, i) => (bool ? i : []));
for (const index of visibleIndices) {
if (Number.isInteger(channel_axis)) {
const channelSelection = [...selection];
channelSelection[channel_axis as number] = index;
loaderSelection.push(channelSelection);
} else {
loaderSelection.push(selection);
}
colorValues.push(hexToRGB(colors[index]));
contrastLimits.push(contrast_limits[index]);
channelIsOn.push(true);
}
// set initial slider values to contrast_limits
const sliderValues = [...contrastLimits];
if (!(loader[0].dtype in DTYPE_VALUES)) {
throw Error(`Dtype not supported, must be ${JSON.stringify(Object.keys(DTYPE_VALUES))}`);
}
return {
Layer,
layerProps: {
loader: loader.length === 1 ? loader[0] : loader,
loaders,
rows,
columns,
loaderSelection,
colorValues,
sliderValues,
contrastLimits,
channelIsOn,
opacity,
colormap,
modelMatrix: model_matrix,
onClick,
},
on: true,
};
}
function getLayer(sourceData: SourceData): LayerCtr<typeof ImageLayer | typeof MultiscaleImageLayer | GridLayer> {
return sourceData.loaders ? GridLayer : sourceData.loader.length > 1 ? MultiscaleImageLayer : ImageLayer;
}