Repository navigation
Expand file tree
/
Copy pathslabelacencode.m
More file actions
241 lines (230 loc) · 8.3 KB
/
Copy pathslabelacencode.m
File metadata and controls
241 lines (230 loc) · 8.3 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
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
function output = slabelacencode(input, es, nx, ny)
%
% output = slabelacencode(labels)
% or
% output = slabelacencode(bytes, es, nx, ny)
%
% Compress a label array with slabelac (experimental): labelac for sparse labels, where most of
% the array is regions of one label. The array's 4x4x4 blocks of one label are coded first, as a
% coarse label array of their own (with labelac's model); only the elements of the other blocks
% are then coded, as labelac codes them (in wavefront planes, with a rANS lane per 2048 positions
% rather than 8192). About as small as labelac, and about 1.5 times as fast to decode in compiled
% code, about 3 times in MATLAB. The format is jdai's (https://github.com/NeuroJSON/jdai,
% src/labelac.cpp: labelac's stream version 2), byte for byte. ZMat (with slabelac) does the work
% when it is installed; else this file's vectorized code gives the same bytes.
%
% input:
% labels: an integer, logical or char array, coded in its JData (row-major) order
% bytes: the elements' little-endian bytes in row-major order (uint8), with
% es: the element size in bytes (1, 2, 4 or 8)
% nx, ny: the fastest and second-fastest dimensions (as _ArraySize_(end), _ArraySize_(end-1))
%
% output:
% output: the slabelac stream (uint8 row)
%
% examples:
% seg = zeros(64, 64, 64, 'uint8');
% seg(10:40, 20:50, 5:60) = 3;
% z = slabelacencode(seg);
% isequal(slabelacdecode(z), reshape(permute(seg, [3 2 1]), 1, []))
%
% license:
% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://neurojson.org/jsonlab)
%
if (nargin == 1)
% a label array: its row-major bytes, element size and two last dimensions
a = input;
if (islogical(a) || ischar(a))
a = uint8(a);
end
if (~isinteger(a) && ~isfloat(a))
error('slabelac: a label array must be numeric');
end
dims = size(a);
nx = dims(end);
ny = dims(end - 1);
a = permute(a, ndims(a):-1:1);
input = typecast(a(:).', 'uint8');
es = numel(typecast(cast(0, class(a)), 'uint8'));
end
% ZMat's compiled coder, when it has slabelac: the same bytes, much faster
persistent nozmat
if (isempty(nozmat) && exist('zmat', 'file'))
try
output = zmat(reshape(uint8(input), 1, []), 1, 'slabelac', 'typesize', es, 'dims', [nx ny]);
if (~isempty(output) || isempty(input))
return
end
catch
end
nozmat = true;
end
BITS = 2; % the blocks' edge: 2^BITS
B = 2^BITS;
if (~any(es == [1 2 4 8]))
error('slabelac: elements must be 1, 2, 4 or 8 bytes');
end
bytes = reshape(uint8(input), 1, []);
if (mod(numel(bytes), es))
error('slabelac: the data is not a whole number of elements');
end
cls = {'uint8', 'uint16', '', 'uint32', '', '', '', 'uint64'};
a = typecast(bytes, cls{es});
count = numel(a);
nx = max(double(nx), 1);
ny = max(double(ny), 1);
if (count && mod(count, nx * ny))
nx = count; % a shape that does not fit: one row
ny = 1;
end
[values, ~, sym] = unique(a(:));
K = numel(values);
if (K > 65536)
error('slabelac: more than 65536 distinct values (not a label array)');
end
output = [uint8(2), varint_(es), varint_(nx), varint_(ny), varint_(count), varint_(K), typecast(reshape(values, 1, []), 'uint8')];
if (K <= 1 || count == 0)
return
end
sym = double(sym(:)) - 1;
nz = count / (nx * ny);
% the elements' coordinates and blocks; a block's symbol: its elements' one symbol, or K
i = (0:count - 1)';
x = mod(i, nx);
y = mod(floor(i / nx), ny);
z = floor(i / (nx * ny));
nb = [floor((nx - 1) / B) + 1, floor((ny - 1) / B) + 1, floor((nz - 1) / B) + 1];
nblocks = prod(nb);
bi = floor(x / B) + nb(1) * (floor(y / B) + nb(2) * floor(z / B));
lo = accumarray(bi + 1, sym, [nblocks 1], @min);
hi = accumarray(bi + 1, sym, [nblocks 1], @max);
block = lo;
block(lo ~= hi) = K;
% the block pass: version 1 over the nb(1) x nb(2) x nb(3) grid of block symbols, K + 1 symbols
q = (0:nblocks - 1)';
qx = mod(q, nb(1));
qy = mod(floor(q / nb(1)), nb(2));
qz = floor(q / (nb(1) * nb(2)));
[~, order] = sort(qx + qy + qz); % (stable: increasing index in each plane)
bounds = [0; cumsum(accumarray(qx + qy + qz + 1, 1))];
key = context_(block, qx, qy, qz, nb(1), nb(2), K + 1);
[Fb, Cb] = pass_(key, block, order, bounds, K + 1);
clear q qx qy qz key order bounds;
% the element pass: the mixed blocks' elements in version 1's order (wavefront planes x + y + z,
% increasing index in each), the single-label blocks' elements left out
mixed = find(block(bi + 1) == K); % (ascending i)
t = x(mixed) + y(mixed) + z(mixed);
[~, o] = sort(t); % (stable)
order = mixed(o);
bounds = [0; cumsum(accumarray(t + 1, 1, [nx + ny + nz - 2, 1]))];
key = context_(sym, x, y, z, nx, ny, K);
[Fe, Ce] = pass_(key, sym, order, bounds, K);
clear key sym x y z t i bi mixed o order bounds;
Fq = [Fb; Fe];
Cq = [Cb; Ce];
P = numel(Fq);
% interleaved rANS, from the last position to the first: position j in lane mod(j, N)
M = 65536;
N = max(1, min(256, floor(P / 2048))); % (a lane per 2048 positions: labelac takes 8192)
state = 65536 * ones(N, 1);
words = zeros(P, 1);
wpos = P;
for r = ceil(P / N) - 1:-1:0
n = min(N, P - r * N);
f = Fq(r * N + (1:n));
xs = state(1:n);
emit = find(xs >= f * 65536);
w = mod(xs(emit), 65536);
words(wpos - numel(w) + 1:wpos) = w;
wpos = wpos - numel(w);
xs(emit) = floor(xs(emit) / 65536);
state(1:n) = floor(xs ./ f) * M + mod(xs, f) + Cq(r * N + (1:n));
end
output = [output, varint_(BITS), varint_(N), typecast(uint32(state(:)'), 'uint8'), typecast(uint16(words(wpos + 1:end)'), 'uint8')];
%% -------------------------------------------------------------------------
function key = context_(s, x, y, z, nx, ny, K)
% every element's context key (L * K + U) * K + F: the symbols of its left, up and front neighbours
n = numel(s);
L = zeros(n, 1);
U = L;
F = L;
k = find(x > 0);
L(k) = s(k - 1);
k = find(y > 0);
U(k) = s(k - nx);
k = find(z > 0);
F(k) = s(k - nx * ny);
key = (L * K + U) * K + F;
%% -------------------------------------------------------------------------
function [Fq, Cq] = pass_(key, sym, order, bounds, K)
% the frequency and start of every position (order(bounds(g) + 1:bounds(g + 1)): group g's
% elements), each group with the counts from the groups before it, which it then updates
M = 65536;
INC = 128;
VOTE = 128;
LIMIT = 65535;
Fq = zeros(numel(order), 1);
Cq = Fq;
mkeys = zeros(0, 1); % known context keys, ascending
mrows = zeros(0, 1); % their rows in counts
counts = zeros(1024, K);
nrow = 0;
for p = 1:numel(bounds) - 1
pos = bounds(p) + 1:bounds(p + 1);
if (isempty(pos))
continue
end
j = order(pos);
s = sym(j);
[uk, ~, inv] = unique(key(j));
[tf, loc] = ismember(uk, mkeys);
rows = zeros(numel(uk), 1);
rows(tf) = mrows(loc(tf));
new = uk(~tf);
if (~isempty(new))
newrows = nrow + (1:numel(new))';
if (newrows(end) > size(counts, 1))
counts(max(2 * size(counts, 1), newrows(end)), K) = 0;
end
counts(newrows, :) = 1;
for nb = [floor(new / (K * K)), mod(floor(new / K), K), mod(new, K)]
ix = newrows + nb * size(counts, 1);
counts(ix) = counts(ix) + VOTE;
end
rows(~tf) = newrows;
nrow = newrows(end);
[mkeys, o] = sort([mkeys; new]);
mrows = [mrows; newrows];
mrows = mrows(o);
end
cu = counts(rows, :);
f = 1 + floor(cu * (M - K) ./ repmat(sum(cu, 2), 1, K));
[~, im] = max(cu, [], 2);
ix = (1:numel(rows))' + (im - 1) * numel(rows);
f(ix) = f(ix) + M - sum(f, 2);
c = cumsum(f, 2) - f;
ix = inv(:) + s(:) * numel(rows);
Fq(pos) = f(ix);
Cq(pos) = c(ix);
counts(rows, :) = counts(rows, :) + accumarray([inv(:), s(:) + 1], INC, [numel(rows), K]);
touched = rows;
while (~isempty(touched))
big = touched(sum(counts(touched, :), 2) > LIMIT);
if (isempty(big))
break
end
counts(big, :) = floor((counts(big, :) + 1) / 2);
touched = big;
end
end
%% -------------------------------------------------------------------------
function b = varint_(v)
b = zeros(1, 0, 'uint8');
v = double(v);
while (v >= 128)
b(end + 1) = uint8(mod(v, 128) + 128);
v = floor(v / 128);
end
b(end + 1) = uint8(v);