| 1 | toInteger <- function(x, condition) |
| 2 | { |
| 3 | if (!is.integer(x)) |
| 4 | tryCatch( |
| 5 | {x = as.integer(x)[1]}, |
| 6 | error = function(e) paste("cannot convert argument",substitute(x),"to integer") |
| 7 | ) |
| 8 | if (!condition(x)) |
| 9 | stop(paste("argument",substitute(x),"does not verify condition",body(condition))) |
| 10 | x |
| 11 | } |
| 12 | |
| 13 | curvesToCoeffs = function(series, wf) |
| 14 | { |
| 15 | L = length(series[1,]) |
| 16 | D = ceiling( log2(L) ) |
| 17 | nb_sample_points = 2^D |
| 18 | apply(series, 1, function(x) { |
| 19 | interpolated_curve = spline(1:L, x, n=nb_sample_points)$y |
| 20 | W = wavelets::dwt(interpolated_curve, filter=wf, D)@W |
| 21 | rev( sapply( W, function(v) ( sqrt( sum(v^2) ) ) ) ) |
| 22 | }) |
| 23 | } |
| 24 | |
| 25 | #data: matrix of double or connection |
| 26 | serialize = function(data, file, type, nb_per_chunk) |
| 27 | { |
| 28 | bin_data = file(file, "ab") |
| 29 | #write data length on first call |
| 30 | nbytes = ifelse(type=="double",8,4) |
| 31 | first_write = FALSE |
| 32 | if (file.info(file)$size == 0) |
| 33 | { |
| 34 | #number of items always on 8 bytes |
| 35 | writeBin(0L, bin_data, size=8) #,endian="little") |
| 36 | first_write = TRUE |
| 37 | } |
| 38 | if (is.matrix(data)) |
| 39 | { |
| 40 | writeBin(t(data), bin_data, size=nbytes) |
| 41 | data_length = ncol(data) |
| 42 | } |
| 43 | else #if (is(data, "connection")) |
| 44 | { |
| 45 | if (first_write) |
| 46 | { |
| 47 | data_line = scan(data, double(), sep=",", nlines=1) |
| 48 | writeBin(data_line, bin_data, size=nbytes) |
| 49 | data_length = length(data_line) |
| 50 | } |
| 51 | repeat |
| 52 | { |
| 53 | data_chunk = scan(data, double(), sep=",", nlines=nb_per_chunk) |
| 54 | if (length(data_chunk)==0) |
| 55 | break |
| 56 | writeBin(data_chunk, bin_data, size=nbytes) |
| 57 | } |
| 58 | } |
| 59 | if (first_write) |
| 60 | { |
| 61 | #ecrire file_size-1 / (nbytes*nbWritten) en 0 dans bin_data ! ignored == file_size |
| 62 | ignored = seek(bin_data, 0) |
| 63 | writeBin(data_length, bin_data, size=8) |
| 64 | } |
| 65 | close(bin_data) |
| 66 | } |
| 67 | |
| 68 | #TODO: read in binary file, always same structure |
| 69 | getDataFromFile(indices, file, type) |
| 70 | { |
| 71 | bin_data = file(file, "rb") |
| 72 | nbytes = ifelse(type=="double",8,4) |
| 73 | data_length = readBin(bin_data,"double",1,nbytes) #,endian="little") |
| 74 | t(sapply(indices, function(i) readBin(bin_data,"double",n=data_length,size=nbytes))) |
| 75 | } |