-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkf_rcd.m
105 lines (91 loc) · 2.24 KB
/
kf_rcd.m
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
function varargout = kf_rcd (varargin)
% kf_rcd. A memory- or disk-based stack for kfgs data.
%
% r = kf_rcd('init', medium, base_filename)
% Initialize the stack.
% medium is either 'mem' for storage in main memory or 'disk' for hard disk
% storage.
% base_filename is required for medium = 'disk'. It is the base filename of
% the files kf_rcd must save. Example: '/scratch/kf/test'.
[varargout{1:nargout}] = feval(varargin{:});
end
function r = init (medium, fn)
switch (lower(medium(1)))
case 'm' % mem
r.medium = 'm';
r.stack = {};
case 'd' % disk
if (nargin ~= 2)
error('rcd = kf_rcd(''init'', ''disk'', base_filename);');
end
r.medium = 'd';
r.fn = fn;
r.nbrs = [];
otherwise
error('medium = ''mem'' or ''disk''.');
end
end
function r = push (r, varargin)
switch (r.medium)
case 'm'
r.stack{end+1} = varargin;
case 'd'
r.nbrs(end+1) = length(varargin);
for (i = 1:r.nbrs(end))
fn = GetFn(r.fn, length(r.nbrs), i);
fid = fopen(fn, 'w');
[m n] = size(varargin{i});
fwrite(fid, [m n], 'int32');
fwrite(fid, varargin{i}(:), 'double');
fclose(fid);
end
end
end
function [r varargout] = pop (r)
% Return top-most and delete.
switch (r.medium)
case 'm'
varargout = r.stack{end};
r.stack(end) = [];
case 'd'
for (i = 1:r.nbrs(end))
[varargout{i} fn] = Read(r.fn, length(r.nbrs), i);
delete(fn);
end
r.nbrs(end) = [];
end
end
function [r varargout] = peak (r)
% Return top-most.
switch (r.medium)
case 'm'
varargout = r.stack{end};
case 'd'
for (i = 1:r.nbrs(end))
varargout{i} = Read(r.fn, length(r.nbrs), i);
end
end
end
function r = discard (r)
% Discard top-most without looking.
switch (r.medium)
case 'm'
r.stack(end) = [];
case 'd'
for (i = 1:r.nbrs(end))
fn = GetFn(r.fn, length(r.nbrs), i);
delete(fn);
end
r.nbrs(end) = [];
end
end
function [A fn] = Read (fn, nbr, idx)
fn = GetFn(fn, nbr, idx);
fid = fopen(fn, 'r');
sz = fread(fid, 2, 'int32');
A = fread(fid, sz', 'double');
fclose(fid);
end
function fn = GetFn (basefn, nbr, idx)
fn = sprintf('%s_%06d_%06d.dat', basefn, nbr, idx);
end