Repository navigation
Expand file tree
/
Copy pathzmat.m
More file actions
402 lines (374 loc) · 18.2 KB
/
Copy pathzmat.m
File metadata and controls
402 lines (374 loc) · 18.2 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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
function varargout = zmat(varargin)
%
% output=zmat(input)
% or
% [output, info]=zmat(input, iscompress, method)
% [output, info]=zmat(input, iscompress, method, options ...)
% output=zmat(input, info)
%
% A portable data compression/decompression toolbox for MATLAB/GNU Octave
%
% author: Qianqian Fang <q.fang at neu.edu>
% initial version created on 04/30/2019
%
% input:
% input: a char, non-complex numeric or logical vector or array.
% Sparse matrices, and Octave diagonal, permutation, and range
% types are also accepted and stored in a compact representation.
% iscompress: (optional) if iscompress is 1, zmat compresses/encodes the input,
% if 0, it decompresses/decodes the input. Default value is 1.
%
% if iscompress is set to a negative integer, (-iscompress) specifies
% the compression level. For zlib/gzip, default level is 6 (1-9); for
% lzma/lzip, default level is 5 (1-9); for lz4hc, default level is 8 (1-16).
% the default compression level is used if iscompress is set to 1.
%
% zmat removes the trailing newline when iscompress=2 and method='base64'
% all newlines are kept when iscompress=3 and method='base64'
%
% if one defines iscompress as the info struct (2nd output of zmat), zmat
% will perform a decoding/decompression operation and recover the original
% input using the info stored in the info structure.
% method: (optional) compression method, currently, zmat supports the below methods
% 'zlib': zlib/zip based data compression (default)
% 'gzip': gzip formatted data compression
% 'lzip': lzip formatted data compression (nthread>1 compresses chunks in parallel)
% 'lzma': lzma formatted data compression
% 'xz': xz (.xz) compression via LZMA2; nthread sets parallel block threads
% 'lz4': lz4 formatted data compression
% 'lz4hc':lz4hc (LZ4 with high-compression ratio) formatted data compression
% 'zstd': zstd formatted data compression
% 'blosc2blosclz': blosc2 meta-compressor with blosclz compression
% 'blosc2lz4': blosc2 meta-compressor with lz4 compression
% 'blosc2lz4hc': blosc2 meta-compressor with lz4hc compression
% 'blosc2zlib': blosc2 meta-compressor with zlib/zip compression
% 'blosc2zstd': blosc2 meta-compressor with zstd compression
% 'base64': encode or decode use base64 format
% 'labelac': label arrays (segmentations, parcellations, masks; experimental): each
% element predicted from its neighbours along the three fastest-varying
% dimensions, coded with adaptive counts and rANS; lossless, typically half
% the size of xz on segmentations; the format of jdai and JData's
% _ArrayZipType_ "labelac". The input's own class and size give the element
% size and shape (memory order: the first dimension fastest); see 'dims'
% 'slabelac': labelac for sparse labels (experimental): the 4x4x4 blocks of one label
% coded whole, then only the other blocks' elements; about as small, and
% about 1.5 times as fast to decode; JData's _ArrayZipType_ "slabelac"
% options: a series of ('name', value) pairs, supported options include
% 'nthread': followed by an integer specifying number of threads, default 8.
% It drives lzip, lzma, xz, zstd and the blosc2 meta-compressors,
% and for zlib and gzip it deflates fixed-size blocks concurrently,
% each closed with Z_FULL_FLUSH so the result stays an ordinary
% zlib/gzip stream that any decompressor can read. Within that
% blocked form the output is a pure function of the data, level and
% block size: nthread of 1, 8 or 32 all give the same bytes. It is a
% different stream from the serial one though -- resetting the window
% at each boundary is what makes blocks independently inflatable, and
% it costs ratio, from +0.000%% on incompressible data to about +21%%
% on data whose redundancy spans the block size. Pass a negative value
% for zlib/gzip's historical single-stream output, which is smaller but
% neither threaded nor randomly accessible.
% 'offsets': followed by a 2-by-N block index previously returned in
% info.offsets; on decompression this lets zlib/gzip inflate the
% blocks concurrently. A mismatched index is ignored rather than
% trusted, falling back to a serial inflate.
% 'typesize': followed by an integer specifying the number of bytes per data element (used for shuffle;
% for labelac and slabelac, the element size of uint8 input holding wider elements' bytes)
% 'dims': for labelac and slabelac, [nx ny]: the fastest-varying dimension of the input's elements
% and the next (default: the input's first two dimensions, or one row for a vector)
% 'shuffle': 0 to disable (default for non-blosc2), 1 to enable byte-shuffle.
% For blosc2 methods the shuffle is applied inside the C layer.
% For all other methods, when [output,info]=zmat(...) is called,
% the shuffle is applied in MATLAB before compression and reversed
% after decompression; the info struct records 'shuffle' and
% 'typesize' so that zmat(compressed, info) restores the original array.
%
% output:
% output: a uint8 row vector, storing the compressed or decompressed data;
% empty when an error is encountered. When decompressing with the info
% struct, the original data type and dimensions are restored, including
% special matrix types.
% info: (optional) a struct storing additional info regarding the input data, may have
% 'type': the class of the input array
% 'size': the dimensions of the input array
% 'byte': the number of bytes per element in the input array
% 'method': a copy of the 3rd input indicating the encoding method
% 'status': the zlib/lzma/lz4 compression/decompression function return value,
% including potential error codes; see documentation of the respective
% libraries for details
% 'level': a copy of the iscompress flag; if non-zero, specifying compression
% level, see above
% 'offsets': for threaded zlib/gzip compression, a 2-by-(nblock+1) matrix of
% [compressed; uncompressed] byte offsets, one column per block plus
% a final sentinel column closing the last one. Pass it back on
% decompression to inflate the blocks in parallel. Empty for every
% other codec.
% 'matrixtype': (optional) one of 'diagonal', 'permutation', 'sparse', or
% 'range' for special matrix types. Absent for regular dense arrays.
% - 'diagonal': Octave diagonal matrix (e.g. eye(N), diag(v)); only
% the diagonal elements are stored.
% - 'permutation': Octave permutation matrix; only the permutation
% index vector is stored as uint32.
% - 'range': Octave range object (e.g. 1:1000); stored as 3 doubles
% [start, step, numel] regardless of range length.
% - 'sparse': sparse matrix (both MATLAB and Octave); row/column
% indices stored as uint32 and values in the original type.
% 'matrixclass': (optional) original element class for diagonal and sparse types
% 'matrixsize': (optional) original [rows, cols] dimensions
% 'sparsecount': (optional) number of nonzero elements for sparse type
%
% example:
%
% [ss, info]=zmat(eye(5))
% orig=zmat(ss,0)
% orig=zmat(ss,info)
% ss=char(zmat('zmat test',1,'base64'))
% orig=char(zmat(ss,0,'base64'))
%
% % sparse matrix round-trip
% A=sparse(eye(100));
% [ss, info]=zmat(A);
% A2=zmat(ss, info);
% assert(nnz(A-A2)==0);
%
% -- this function is part of the ZMAT toolbox (https://github.com/NeuroJSON/zmat)
%
if (exist('zipmat') ~= 3 && exist('zipmat') ~= 2)
error('zipmat mex file is not found. you must download the mex file or recompile');
end
if (nargin == 0)
fprintf(1, 'Usage:\n\t[output,info]=zmat(input,iscompress,method);\nPlease run "help zmat" for more details.\n');
return
end
input = varargin{1};
iscompress = 1;
zipmethod = 'zlib';
if (~(ischar(input) || islogical(input) || (isnumeric(input) && isreal(input))))
error('input must be a char, non-complex numeric or logical vector or N-D array');
end
inputinfo = whos('input');
if (~isempty(input))
typesize = inputinfo.bytes / numel(input);
else
typesize = 0;
end
%% detect and handle special matrix types (Octave diagonal, permutation, range; sparse)
specialtype = '';
isoctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;
if (issparse(input))
specialtype = 'sparse';
[sprow, spcol, spval] = find(input);
spsize = size(input);
elseif (isoctave)
tinfo = typeinfo(input);
if (any(strcmp(tinfo, {'diagonal matrix', 'complex diagonal matrix'})))
specialtype = 'diagonal';
elseif (strcmp(tinfo, 'permutation matrix'))
specialtype = 'permutation';
elseif (strcmp(tinfo, 'range'))
specialtype = 'range';
end
end
%% for special types, convert to a compact representation before compression
if (strcmp(specialtype, 'diagonal'))
% store only the diagonal vector — N elements instead of N*N
origsize = size(input);
origclass = class(input);
input = diag(input); % extract diagonal as a vector
inputinfo = whos('input');
if (~isempty(input))
typesize = inputinfo.bytes / numel(input);
end
elseif (strcmp(specialtype, 'permutation'))
% store only the permutation index vector (1-based uint32 indices)
origsize = size(input);
input = full(input); % convert to dense first for portability
[~, pidxvec] = max(input, [], 2); % extract permutation vector
input = uint32(pidxvec);
inputinfo = whos('input');
if (~isempty(input))
typesize = inputinfo.bytes / numel(input);
end
elseif (strcmp(specialtype, 'range'))
% store as [start, step, numel] — 3 doubles regardless of range length
origsize = size(input);
rstart = input(1);
if (numel(input) > 1)
rstep = input(2) - input(1);
else
rstep = 1;
end
rcount = numel(input);
input = [rstart, rstep, rcount];
inputinfo = whos('input');
if (~isempty(input))
typesize = inputinfo.bytes / numel(input);
end
elseif (strcmp(specialtype, 'sparse'))
% store [rows, cols, vals] compactly: indices as uint32, vals in original type
origsize = spsize;
origclass = class(spval);
input = uint8([typecast(uint32(sprow(:)'), 'uint8'), ...
typecast(uint32(spcol(:)'), 'uint8'), ...
typecast(spval(:)', 'uint8')]);
inputinfo = whos('input');
typesize = 1;
end
if (ischar(input))
input = uint8(input);
end
if (nargin > 1)
iscompress = varargin{2};
if (isstruct(varargin{2}))
inputinfo = varargin{2};
iscompress = 0;
zipmethod = inputinfo.method;
end
end
if (nargin > 2)
zipmethod = varargin{3};
end
opt = struct;
if (nargin > 4 && ischar(varargin{4}) && bitand(length(varargin), 1) == 1)
opt = cell2struct(varargin(5:2:end), varargin(4:2:end), 2);
end
shuffle = 0;
if (strfind(zipmethod, 'blosc2'))
shuffle = 1;
end
nthread = getoption('nthread', 8, opt);
shuffle = getoption('shuffle', shuffle, opt);
typesize = getoption('typesize', typesize, opt);
iscompress = round(iscompress);
if ((strcmp(zipmethod, 'zlib') || strcmp(zipmethod, 'gzip')) && iscompress <= -10)
iscompress = -9;
end
% On decompression, a block index from a previous compression (info.offsets,
% or an 'offsets' option) lets zlib/gzip inflate the blocks concurrently. It is
% only a speed hint: the payload is an ordinary zlib/gzip stream, and an index
% that does not match it is rejected in favour of a serial inflate.
offsets = getoption('offsets', [], opt);
if (isempty(offsets) && isstruct(opt) && isfield(opt, 'info') && isstruct(opt.info) && isfield(opt.info, 'offsets'))
offsets = opt.info.offsets;
end
%% wrapper-level byte shuffle: applies to non-blosc2 codecs when info is requested
do_wrapper_shuffle = (nargout > 1 && shuffle > 0 && iscompress ~= 0 && ...
isempty(strfind(zipmethod, 'blosc2')) && ...
~strcmp(zipmethod, 'base64') && ~strcmp(zipmethod, 'labelac') && ~strcmp(zipmethod, 'slabelac') && ...
isempty(specialtype) && typesize > 1);
if (do_wrapper_shuffle)
%% convert input to bytes, apply byte shuffle, then compress
orig_class = class(input);
orig_size = size(input);
if (~isa(input, 'uint8'))
raw_bytes = typecast(input(:)', 'uint8');
else
raw_bytes = input(:)';
end
nelems = numel(raw_bytes) / typesize;
M = reshape(raw_bytes, typesize, nelems); % typesize x nelems: col = one element
shuffled_bytes = reshape(M', 1, []); % flatten row-major: all byte-0s, then byte-1s...
[varargout{1:max(1, nargout)}] = zipmat(shuffled_bytes, iscompress, zipmethod, nthread, 0, 1, offsets);
%% overwrite info with original array metadata and record shuffle state
varargout{2}.type = orig_class;
varargout{2}.size = orig_size;
varargout{2}.byte = typesize;
varargout{2}.shuffle = shuffle;
varargout{2}.typesize = typesize;
elseif (strcmp(zipmethod, 'labelac') || strcmp(zipmethod, 'slabelac'))
% labelac, slabelac: the shape ('dims', [nx ny]) as the 8th input
[varargout{1:max(1, nargout)}] = zipmat(input, iscompress, zipmethod, nthread, shuffle, typesize, offsets, getoption('dims', [], opt));
else
[varargout{1:max(1, nargout)}] = zipmat(input, iscompress, zipmethod, nthread, shuffle, typesize, offsets);
end
%% store special matrix type info in the output info struct
if (nargout > 1 && ~isempty(specialtype))
varargout{2}.matrixtype = specialtype;
if (strcmp(specialtype, 'diagonal') || strcmp(specialtype, 'sparse'))
varargout{2}.matrixclass = origclass;
varargout{2}.matrixsize = origsize;
elseif (strcmp(specialtype, 'permutation'))
varargout{2}.matrixsize = origsize;
elseif (strcmp(specialtype, 'range'))
varargout{2}.matrixsize = origsize;
end
if (strcmp(specialtype, 'sparse'))
varargout{2}.sparsecount = length(sprow);
end
end
if (strcmp(zipmethod, 'base64') && iscompress > 1)
varargout{1} = char(varargout{1});
end
if (exist('inputinfo', 'var') && isfield(inputinfo, 'type'))
%% fix for Octave 10+ where mxGetClassName returns empty for special types
if (isempty(inputinfo.type) && isfield(inputinfo, 'class'))
inputinfo.type = inputinfo.class;
end
%% restore special matrix types
if (isfield(inputinfo, 'matrixtype'))
if (strcmp(inputinfo.matrixtype, 'diagonal'))
dvec = typecast(varargout{1}, inputinfo.matrixclass);
varargout{1} = diag(dvec);
ms = inputinfo.matrixsize;
if (size(varargout{1}, 1) ~= ms(1) || size(varargout{1}, 2) ~= ms(2))
tmp = zeros(ms, inputinfo.matrixclass);
n = min(length(dvec), min(ms));
for k = 1:n
tmp(k, k) = dvec(k);
end
varargout{1} = tmp;
end
return
elseif (strcmp(inputinfo.matrixtype, 'permutation'))
pidx = double(typecast(varargout{1}, 'uint32'));
n = inputinfo.matrixsize(1);
varargout{1} = zeros(n, n);
for k = 1:n
varargout{1}(k, pidx(k)) = 1;
end
return
elseif (strcmp(inputinfo.matrixtype, 'range'))
rparams = typecast(varargout{1}, 'double');
rstart = rparams(1);
rstep = rparams(2);
rcount = round(rparams(3));
varargout{1} = rstart:rstep:(rstart + rstep * (rcount - 1));
if (isfield(inputinfo, 'matrixsize') && ~isequal(size(varargout{1}), inputinfo.matrixsize))
varargout{1} = reshape(varargout{1}, inputinfo.matrixsize);
end
return
elseif (strcmp(inputinfo.matrixtype, 'sparse'))
rawbytes = varargout{1};
nnzcount = inputinfo.sparsecount;
idx_bytes = nnzcount * 4; % uint32 per index
ridx = typecast(rawbytes(1:idx_bytes), 'uint32');
cidx = typecast(rawbytes(idx_bytes + 1:2 * idx_bytes), 'uint32');
valbytes = rawbytes(2 * idx_bytes + 1:end);
vals = typecast(valbytes, inputinfo.matrixclass);
varargout{1} = sparse(double(ridx), double(cidx), vals, ...
inputinfo.matrixsize(1), inputinfo.matrixsize(2));
return
end
end
%% unshuffle if compression applied wrapper-level byte shuffle
if (isfield(inputinfo, 'shuffle') && inputinfo.shuffle > 0 && ...
isfield(inputinfo, 'typesize') && inputinfo.typesize > 1 && ...
isempty(strfind(inputinfo.method, 'blosc2')))
ts = inputinfo.typesize;
raw_bytes = varargout{1}(:)';
nelems = numel(raw_bytes) / ts;
M = reshape(raw_bytes, nelems, ts); % nelems x ts: col = one byte position
varargout{1} = reshape(M', 1, []); % flatten row-major: bytes of e1, then e2...
end
if (strcmp(inputinfo.type, 'logical'))
varargout{1} = logical(varargout{1});
else
varargout{1} = typecast(varargout{1}, inputinfo.type);
end
varargout{1} = reshape(varargout{1}, inputinfo.size);
end
% --------------------------------------------------------------------------------
function value = getoption(key, default, opt)
value = default;
if (isfield(opt, key))
value = opt.(key);
end