Repository navigation
Expand file tree
/
Copy pathmap.cpp
More file actions
412 lines (345 loc) · 13.3 KB
/
Copy pathmap.cpp
File metadata and controls
412 lines (345 loc) · 13.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
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
403
404
405
406
407
408
409
410
411
412
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
// [[Rcpp::depends(BH)]]
#include "core.h"
#include "serialize.h"
#include "conversion.h"
#include "utils.h"
#include "load.h"
#include "save.h"
#include "threadSettings.h"
#include "TinyParallel.h"
using namespace Rcpp;
struct FARRSequentialSubsetter : public TinyParallel::Worker {
const std::vector<std::string>& input_filebases;
std::vector<int64_t> slice_sizes;
std::vector<SEXP> cumparts;
std::vector<SEXPTYPE> arr_types;
SEXP argbuffers;
// current_pos * buffer_nelems is the pointer position in the array
int64_t current_pos;
std::vector<int> buffer_nelems;
FARRSequentialSubsetter(
const std::vector<std::string>& input_filebases,
std::vector<int64_t> slice_sizes,
std::vector<SEXP> cumparts,
std::vector<SEXPTYPE> arr_types,
SEXP argbuffers,
int64_t current_pos,
std::vector<int> buffer_nelems
) : input_filebases(input_filebases), slice_sizes(slice_sizes),
cumparts(cumparts), arr_types(arr_types), argbuffers(argbuffers),
current_pos(current_pos), buffer_nelems(buffer_nelems) {}
void operator()(std::size_t begin, std::size_t end) {
for(std::size_t ii = begin; ii < end; ii++) {
FARR_subset_sequential(
input_filebases[ii],
slice_sizes[ii],
cumparts[ii],
arr_types[ii],
VECTOR_ELT(argbuffers, ii),
current_pos * buffer_nelems[ii], buffer_nelems[ii]
);
}
}
};
/**
# DIPSAUS DEBUG START
# devtools::load_all()
# e1 <- as_filearray(1:240, dimension = c(2,3,4,10), type = "integer", partition_size = 3L)
# e2 <- as_filearray(rnorm(240), dimension = c(2,3,4,10), type = "double", partition_size = 3L)
#
# x <- e1+e2
# print(x[][240])
**/
// [[Rcpp::export]]
SEXP FARR_buffer_map(
std::vector<std::string>& input_filebases,
const std::string& output_filebase,
const Function& map,
std::vector<int>& buffer_nelems,
int result_nelems = 0
){
// Prepare outputs
std::string out_fbase = correct_filebase(output_filebase);
List out_meta = FARR_meta(out_fbase);
SEXP out_cumpart = realToInt64_inplace(out_meta["cumsum_part_sizes"]);
SEXPTYPE out_array_type = out_meta["sexp_type"];
SEXPTYPE out_file_type = file_buffer_sxptype(out_array_type);
SEXP out_dim = out_meta["dimension"];
realToInt64_inplace(out_dim);
R_xlen_t out_ndims = Rf_length(out_dim);
int64_t* out_dimptr = INTEGER64(out_dim);
int64_t out_unit_partlen = 1;
for(R_xlen_t jj = 0; jj <out_ndims - 1; jj++, out_dimptr++){
out_unit_partlen *= *out_dimptr;
}
// prepare inputs
int narrays = input_filebases.size();
if(buffer_nelems.size() - narrays < 0) {
Rcpp::stop("C++: `FARR_buffer_map`: vector buffer_nelems is too short. The length must be consistent with number of input arrays.");
}
std::vector<List> metas(narrays);
std::vector<SEXPTYPE> arr_types(narrays);
std::vector<SEXPTYPE> file_buffer_types(narrays);
std::vector<SEXPTYPE> memory_buffer_types(narrays);
std::vector<SEXP> cumparts(narrays);
std::vector<int64_t> slice_sizes(narrays);
std::vector<int64_t> input_lens(narrays);
// dimensions of the first input array
SEXP in_dim = R_NilValue;
R_xlen_t in_ndims;
int64_t* in_dimptr;
for(int ii = 0; ii < narrays; ii++){
std::string fbase = correct_filebase(input_filebases[ii]);
input_filebases[ii] = fbase;
List meta = FARR_meta(fbase);
metas[ii] = meta;
arr_types[ii] = meta["sexp_type"];
file_buffer_types[ii] = file_buffer_sxptype(arr_types[ii]);
memory_buffer_types[ii] = array_memory_sxptype(arr_types[ii]);
cumparts[ii] = realToInt64_inplace(meta["cumsum_part_sizes"]);
in_dim = meta["dimension"];
if( in_dim == R_NilValue ){
stop("Cannot obtain dimensions from the inputs");
}
realToInt64_inplace(in_dim);
in_ndims = Rf_length(in_dim);
in_dimptr = INTEGER64(in_dim);
// slice length
slice_sizes[ii] = 1;
for(R_xlen_t jj = 0; jj <in_ndims - 1; jj++, in_dimptr++){
slice_sizes[ii] *= *in_dimptr;
}
in_dimptr = INTEGER64(in_dim) + (in_ndims - 1);
// length of input array
input_lens[ii] = slice_sizes[ii] * (*in_dimptr);
}
// allocate buffers; `argbuffers` protects each buffer once stored, so
// the buffers are not PROTECTed one by one (keeps the protection stack
// depth constant)
SEXP argbuffers = PROTECT(Rf_allocVector(VECSXP, narrays));
for(int ii = 0; ii < narrays; ii++){
SET_VECTOR_ELT(argbuffers, ii, Rf_allocVector(memory_buffer_types[ii], buffer_nelems[ii]));
}
int64_t current_pos = 0;
int64_t current_pos_save = 0;
SEXP tmp = R_NilValue;
if( result_nelems <= 0 ){
result_nelems = buffer_nelems[0];
}
R_xlen_t expected_res_nelem = result_nelems;
int ncores = getThreads();
if( ncores > narrays ){
ncores = narrays;
}
// SEXP convert_as2(SEXP x, SEXP y, SEXPTYPE type)
SEXP tmp_val = PROTECT(Rf_allocVector(out_file_type, result_nelems));
/**
* Repeat meself
*/
FARRSequentialSubsetter seqsubsetter(
input_filebases, slice_sizes, cumparts,
arr_types, argbuffers, 0, buffer_nelems
);
try{
for( ; current_pos < input_lens[0]; current_pos += buffer_nelems[0] ){
seqsubsetter.current_pos = current_pos / buffer_nelems[0];
TinyParallel::parallelFor(0, narrays, seqsubsetter);
tmp = PROTECT(map(argbuffers));
R_xlen_t tmplen = Rf_xlength(tmp);
if( result_nelems <= 0 ){
expected_res_nelem = tmplen;
} else {
expected_res_nelem = result_nelems;
if(tmplen - expected_res_nelem != 0){
// Rcout << tmplen << " vs. " << result_nelems << "\n";
UNPROTECT(1);
stop(
"Function `map` return length is inconsistent with `result_nelems` (expected: " +
std::to_string(expected_res_nelem) + ", actual: " +
std::to_string(tmplen) + ")"
);
}
}
convert_as2(tmp, tmp_val, out_array_type);
UNPROTECT(1); // tmp
FARR_subset_assign_sequential_bare(
out_fbase, out_unit_partlen,
out_cumpart, out_array_type,
tmp_val, current_pos_save
);
current_pos_save += expected_res_nelem;
}
} catch (const Rcpp::LongjumpException& e) {
// An R error or interrupt in `map` (including a partition lock
// time-out): rethrow so Rcpp's generated wrapper resumes the jump
// with the original condition. Use `throw;`, never
// `std::rethrow_exception`: a package built with libc++ can run in
// an R that loaded libstdc++, and `exception_ptr` would mix the two
// C++ runtimes
throw;
} catch (const Rcpp::internal::InterruptedException& e) {
// An interrupt with older Rcpp (without unwind protection): rethrow
// so the wrapper interrupts R, instead of `catch(...)` below
throw;
} catch (const std::exception& e) {
// A C++ error (e.g. `stop()` above, a failed partition write):
// rethrow so the wrapper turns it into an R error. Do not call
// `forward_exception_to_r` here: it raises the R error from inside
// this catch block, which skips the destructors in this function
throw;
} catch (...) {
throw std::runtime_error("filearray C++: Caught an unknown exception in `FARR_buffer_map`.");
}
// No UNPROTECT in the handlers: each one ends in an R error, and R
// restores the protection stack when the error jumps
UNPROTECT(2); // argbuffers, tmp_val
return(R_NilValue);
}
// [[Rcpp::export]]
SEXP FARR_buffer_map2(
std::vector<std::string>& input_filebases,
const Function& map,
std::vector<int>& buffer_nelems
){
// prepare inputs
int narrays = input_filebases.size();
if(buffer_nelems.size() - narrays < 0) {
Rcpp::stop("C++: `FARR_buffer_map2`: vector buffer_nelems is too short. The length must be consistent with number of input arrays.");
}
std::vector<List> metas(narrays);
std::vector<SEXPTYPE> arr_types(narrays);
std::vector<SEXPTYPE> file_buffer_types(narrays);
std::vector<SEXPTYPE> memory_buffer_types(narrays);
std::vector<SEXP> cumparts(narrays);
std::vector<int64_t> slice_sizes(narrays);
std::vector<int64_t> input_lens(narrays);
// dimensions of the first input array
SEXP in_dim = R_NilValue;
R_xlen_t in_ndims;
int64_t* in_dimptr;
for(int ii = 0; ii < narrays; ii++){
std::string fbase = correct_filebase(input_filebases[ii]);
input_filebases[ii] = fbase;
List meta = FARR_meta(fbase);
metas[ii] = meta;
arr_types[ii] = meta["sexp_type"];
file_buffer_types[ii] = file_buffer_sxptype(arr_types[ii]);
memory_buffer_types[ii] = array_memory_sxptype(arr_types[ii]);
cumparts[ii] = realToInt64_inplace(meta["cumsum_part_sizes"]);
in_dim = meta["dimension"];
if( in_dim == R_NilValue ){
stop("Cannot obtain dimensions from the inputs");
}
realToInt64_inplace(in_dim);
in_ndims = Rf_length(in_dim);
in_dimptr = INTEGER64(in_dim);
// slice length
slice_sizes[ii] = 1;
for(R_xlen_t jj = 0; jj <in_ndims - 1; jj++, in_dimptr++){
slice_sizes[ii] *= *in_dimptr;
}
in_dimptr = INTEGER64(in_dim) + (in_ndims - 1);
// length of input array
input_lens[ii] = slice_sizes[ii] * (*in_dimptr);
}
// allocate buffers; `argbuffers` protects each buffer once stored, so
// the buffers are not PROTECTed one by one (keeps the protection stack
// depth constant)
SEXP argbuffers = PROTECT(Rf_allocVector(VECSXP, narrays));
for(int ii = 0; ii < narrays; ii++){
SET_VECTOR_ELT(argbuffers, ii, Rf_allocVector(memory_buffer_types[ii], buffer_nelems[ii]));
}
int64_t current_pos = 0;
int ncores = getThreads();
if( ncores > narrays ){
ncores = narrays;
}
R_xlen_t niters = input_lens[0] / buffer_nelems[0];
if( niters * buffer_nelems[0] < input_lens[0] ){
niters++;
}
SEXP ret = PROTECT(Rf_allocVector(VECSXP, niters));
R_xlen_t iter = 0;
FARRSequentialSubsetter seqsubsetter(
input_filebases, slice_sizes, cumparts,
arr_types, argbuffers, 0, buffer_nelems
);
// current_pos < input_lens[0];
for( iter = 0, current_pos = 0 ;
iter < niters;
current_pos += buffer_nelems[0], iter++ ){
seqsubsetter.current_pos = iter;
TinyParallel::parallelFor(0, narrays, seqsubsetter);
try{
SET_VECTOR_ELT(ret, iter, Shield<SEXP>(map(argbuffers)));
} catch (const Rcpp::LongjumpException& e) {
// An R error or interrupt in `map`: rethrow so the wrapper
// resumes the jump with the original condition (`throw;`, see
// `FARR_buffer_map`)
throw;
} catch (const Rcpp::internal::InterruptedException& e) {
throw;
} catch (const std::exception& e) {
// rethrow; no `forward_exception_to_r` (see `FARR_buffer_map`)
throw;
} catch (...) {
throw std::runtime_error("filearray C++: Caught an unknown exception in `FARR_buffer_map2`.");
}
}
// No UNPROTECT in the handlers (see `FARR_buffer_map`)
UNPROTECT(2); // argbuffers, ret
return(ret);
}
/*** R
devtools::load_all()
e1 <- as_filearray(1:240, dimension = c(2,3,4,10), type = "integer", partition_size = 3L)
e2 <- as_filearray(rnorm(240), dimension = c(2,3,4,10), type = "double", partition_size = 3L)
x <- e1+e2
invisible(x[])
tmp <- integer(240)
current_pos <- 0L
FARR_subset_sequential(
x$.filebase,
24L,
bit64::as.integer64(c(3,6, 9, 10)),
13L,
tmp,
current_pos, 24L
);
# # devtools::load_all()
# require(filearray)
# dim <- 3:5
# set.seed(1);
# fbases <- sapply(1:4, function(i){
# file <- tempfile(); unlink(file, recursive = TRUE)
# x <- filearray_create(file, dim, type = 'double')
# x[] <- seq_len(prod(dim))
# x$.filebase
# })
# set.seed(2); file <- tempfile(); unlink(file, recursive = TRUE)
# y <- filearray_create(file, 4:5, type = 'complex')
# y$initialize_partition()
#
# FARR_buffer_map(
# fbases,
# y$.filebase,
# function(x){
# print(c(x[[1]], sum(x[[1]])))
# sum(x[[1]])
# },
# 3L,
# 1L
# )
# res <- FARR_buffer_map2(
# fbases,
# function(x){
# print(c(x[[1]], sum(x[[1]])))
# sum(x[[1]])
# },
# 3L,
# 1L
# )
# # y[] - simplify2array(res)
*/