First commit
[epclust.git] / pkg / R / computeWerDists.R
1 #' computeWerDists
2 #'
3 #' Compute the WER distances between the series at specified indices, which are
4 #' obtaind by \code{getSeries(indices)}
5 #'
6 #' @param indices Indices of the series to consider
7 #' @param getSeries Function to retrieve series (argument: 'inds', integer vector),
8 #' as columns of a matrix
9 #' @param ncores Number of cores for parallel runs
10 #' @inheritParams claws
11 #'
12 #' @return A distances matrix of size K x K where K == length(indices)
13 #'
14 #' @export
15 computeWerDists <- function(indices, getSeries, nb_series_per_chunk, smooth_lvl=3,
16 nvoice=4, nbytes=4, endian=.Platform$endian, ncores=3, verbose=FALSE)
17 {
18 n <- length(indices)
19 L <- length(getSeries(1)) #TODO: not very neat way to get L
20 noctave <- ceiling(log2(L)) #min power of 2 to cover serie range
21 # Since a CWT contains noctave*nvoice complex series, we deduce the number of CWT to
22 # retrieve/put in one chunk.
23 nb_cwt_per_chunk <- max(1, floor(nb_series_per_chunk / (nvoice*noctave*2)))
24
25 # Initialize result as a square big.matrix of size 'number of medoids'
26 Xwer_dist <- bigmemory::big.matrix(nrow=n, ncol=n, type="double")
27
28 shift <- 1 #roughly equivalent to s0 in biwavelets & cie. TODO: as arg?
29
30 cwt_file <- tempfile(pattern="epclust_cwt.bin_")
31 # Compute the getSeries(indices) CWT, and store the results in the binary file
32 computeSaveCWT <- function(inds)
33 {
34 if (verbose)
35 cat(" Compute save CWT on ",length(inds)," indices\n", sep="")
36
37 # Obtain CWT as big vectors of real part + imaginary part (concatenate)
38 ts_cwt <- sapply(inds, function(i) {
39 ts <- scale(ts(getSeries(i)), center=TRUE, scale=FALSE)
40 ts_cwt <- Rwave::cwt(ts, noctave+ceiling(shift/nvoice), nvoice,
41 w0=2*pi, twoD=TRUE, plot=FALSE)
42 ts_cwt <- ts_cwt[,(1+shift):(noctave*nvoice+shift)]
43 c( as.double(Re(ts_cwt)),as.double(Im(ts_cwt)) )
44 })
45
46 # Serialization
47 binarize(ts_cwt, cwt_file, nb_cwt_per_chunk, ",", nbytes, endian)
48 }
49
50 # Function to retrieve a synchrone CWT from (binary) file
51 getCWT <- function(index, L)
52 {
53 flat_cwt <- getDataInFile(index, cwt_file, nbytes, endian)
54 cwt_length <- length(flat_cwt) / 2
55 re_part <- as.matrix(flat_cwt[1:cwt_length], nrow=L)
56 im_part <- as.matrix(flat_cwt[(cwt_length+1):(2*cwt_length)], nrow=L)
57 re_part + 1i * im_part
58 }
59
60 # Compute distances between columns i and j for j>i
61 computeDistances <- function(i)
62 {
63 if (parll)
64 {
65 # parallel workers start with an empty environment
66 require("epclust", quietly=TRUE)
67 Xwer_dist <- bigmemory::attach.big.matrix(Xwer_dist_desc)
68 }
69
70 if (verbose)
71 cat(paste(" Distances from ",i," to ",i+1,"...",n,"\n", sep=""))
72
73 # Get CWT of column i, and run computations for columns j>i
74 cwt_i <- getCWT(i, L)
75 WX <- filterMA(Mod(cwt_i * Conj(cwt_i)), smooth_lvl)
76
77 for (j in (i+1):n)
78 {
79 cwt_j <- getCWT(j, L)
80
81 # Compute the ratio of integrals formula 5.6 for WER^2
82 # in https://arxiv.org/abs/1101.4744v2 paragraph 5.3
83 num <- filterMA(Mod(cwt_i * Conj(cwt_j)), smooth_lvl)
84 WY <- filterMA(Mod(cwt_j * Conj(cwt_j)), smooth_lvl)
85 wer2 <- sum(colSums(num)^2) / sum(colSums(WX) * colSums(WY))
86
87 Xwer_dist[i,j] <- sqrt(L * ncol(cwt_i) * (1 - wer2))
88 Xwer_dist[j,i] <- Xwer_dist[i,j]
89 }
90 Xwer_dist[i,i] <- 0.
91 }
92
93 if (verbose)
94 cat(paste("--- Precompute and serialize synchrones CWT\n", sep=""))
95
96 # Split indices by packets of length at most nb_cwt_per_chunk
97 indices_cwt <- .splitIndices(indices, nb_cwt_per_chunk)
98 # NOTE: next loop could potentially be run in //. Indices would be permuted (by
99 # serialization order), and synchronicity would be required because of concurrent
100 # writes. Probably not worth the effort - but possible.
101 for (inds in indices_cwt)
102 computeSaveCWT(inds)
103
104 parll <- (ncores > 1)
105 if (parll)
106 {
107 # outfile=="" to see stderr/stdout on terminal
108 cl <-
109 if (verbose)
110 parallel::makeCluster(ncores, outfile="")
111 else
112 parallel::makeCluster(ncores)
113 Xwer_dist_desc <- bigmemory::describe(Xwer_dist)
114 parallel::clusterExport(cl, envir=environment(),
115 varlist=c("parll","n","L","Xwer_dist_desc","getCWT","verbose"))
116 }
117
118 if (verbose)
119 cat(paste("--- Compute WER distances\n", sep=""))
120
121 ignored <-
122 if (parll)
123 parallel::clusterApplyLB(cl, seq_len(n-1), computeDistances)
124 else
125 lapply(seq_len(n-1), computeDistances)
126 Xwer_dist[n,n] <- 0.
127
128 if (parll)
129 parallel::stopCluster(cl)
130
131 unlink(cwt_file) #remove binary file
132
133 Xwer_dist[,] #~small matrix K1 x K1
134 }