drop enercast submodule; drop Rcpp requirement; fix doc, complete code, fix fix fix
[epclust.git] / epclust / R / main.R
index ce650ff..00d2a88 100644 (file)
@@ -59,6 +59,7 @@
 #' @param contrib_type Type of contribution: "relative", "logit" or "absolute" (any prefix)
 #' @param WER "end" to apply stage 2 after stage 1 has fully iterated, or "mix" to apply
 #'   stage 2 at the end of each task
+#' @param smooth_lvl Smoothing level: odd integer, 1 == no smoothing. 3 seems good
 #' @param nvoice Number of voices within each octave for CWT computations
 #' @param random TRUE (default) for random chunks repartition
 #' @param ntasks Number of tasks (parallel iterations to obtain K1 [if WER=="end"]
 #' # WER distances computations are too long for CRAN (for now)
 #'
 #' # Random series around cos(x,2x,3x)/sin(x,2x,3x)
-#' x = seq(0,500,0.05)
-#' L = length(x) #10001
-#' ref_series = matrix( c(cos(x),cos(2*x),cos(3*x),sin(x),sin(2*x),sin(3*x)), ncol=6 )
+#' x <- seq(0,500,0.05)
+#' L <- length(x) #10001
+#' ref_series <- matrix( c(cos(x),cos(2*x),cos(3*x),sin(x),sin(2*x),sin(3*x)), ncol=6 )
 #' library(wmtsa)
-#' series = do.call( cbind, lapply( 1:6, function(i)
+#' series <- do.call( cbind, lapply( 1:6, function(i)
 #'   do.call(cbind, wmtsa::wavBootstrap(ref_series[,i], n.realization=400)) ) )
 #' #dim(series) #c(2400,10001)
-#' res_ascii = claws(series, K1=60, K2=6, 200, verbose=TRUE)
+#' res_ascii <- claws(series, K1=60, K2=6, 200, verbose=TRUE)
 #'
 #' # Same example, from CSV file
-#' csv_file = "/tmp/epclust_series.csv"
+#' csv_file <- "/tmp/epclust_series.csv"
 #' write.table(series, csv_file, sep=",", row.names=FALSE, col.names=FALSE)
-#' res_csv = claws(csv_file, K1=60, K2=6, 200)
+#' res_csv <- claws(csv_file, K1=60, K2=6, 200)
 #'
 #' # Same example, from binary file
 #' bin_file <- "/tmp/epclust_series.bin"
 #' # Prepare data.frame in DB-format
 #' n <- nrow(series)
 #' time_values <- data.frame(
-#'   id = rep(1:n,each=L),
-#'   time = rep( as.POSIXct(1800*(0:n),"GMT",origin="2001-01-01"), L ),
-#'   value = as.double(t(series)) )
+#'   id <- rep(1:n,each=L),
+#'   time <- rep( as.POSIXct(1800*(0:n),"GMT",origin="2001-01-01"), L ),
+#'   value <- as.double(t(series)) )
 #' dbWriteTable(series_db, "times_values", times_values)
 #' # Fill associative array, map index to identifier
 #' indexToID_inDB <- as.character(
 #'   else
 #'     NULL
 #' }
-#' res_db = claws(getSeries, K1=60, K2=6, 200))
+#' res_db <- claws(getSeries, K1=60, K2=6, 200))
 #' dbDisconnect(series_db)
 #'
 #' # All results should be the same:
 claws <- function(series, K1, K2, nb_series_per_chunk, nb_items_clust=7*K1,
        algoClust1=function(data,K) cluster::pam(t(data),K,diss=FALSE,pamonce=1)$id.med,
        algoClust2=function(dists,K) cluster::pam(dists,K,diss=TRUE,pamonce=1)$id.med,
-       wav_filt="d8", contrib_type="absolute", WER="end", nvoice=4, random=TRUE,
-       ntasks=1, ncores_tasks=1, ncores_clust=4, sep=",", nbytes=4,
+       wav_filt="d8", contrib_type="absolute", WER="end", smooth_lvl=3, nvoice=4,
+       random=TRUE, ntasks=1, ncores_tasks=1, ncores_clust=3, sep=",", nbytes=4,
        endian=.Platform$endian, verbose=FALSE, parll=TRUE)
 {
        # Check/transform arguments
@@ -169,10 +170,10 @@ claws <- function(series, K1, K2, nb_series_per_chunk, nb_items_clust=7*K1,
        nb_series_per_chunk <- .toInteger(nb_series_per_chunk, function(x) x>=1)
        nb_items_clust <- .toInteger(nb_items_clust, function(x) x>K1)
        random <- .toLogical(random)
-       tryCatch( {ignored <- wavelets::wt.filter(wav_filt)},
-               error = function(e) stop("Invalid wavelet filter; see ?wavelets::wt.filter") )
-       ctypes = c("relative","absolute","logit")
-       contrib_type = ctypes[ pmatch(contrib_type,ctypes) ]
+       tryCatch({ignored <- wavelets::wt.filter(wav_filt)},
+               error=function(e) stop("Invalid wavelet filter; see ?wavelets::wt.filter") )
+       ctypes <- c("relative","absolute","logit")
+       contrib_type <- ctypes[ pmatch(contrib_type,ctypes) ]
        if (is.na(contrib_type))
                stop("'contrib_type' in {'relative','absolute','logit'}")
        if (WER!="end" && WER!="mix")
@@ -194,48 +195,48 @@ claws <- function(series, K1, K2, nb_series_per_chunk, nb_items_clust=7*K1,
        {
                if (verbose)
                        cat("...Serialize time-series (or retrieve past binary file)\n")
-               series_file = ".series.epclust.bin"
+               series_file <- ".series.epclust.bin"
                if (!file.exists(series_file))
                        binarize(series, series_file, nb_series_per_chunk, sep, nbytes, endian)
-               getSeries = function(inds) getDataInFile(inds, series_file, nbytes, endian)
+               getSeries <- function(inds) getDataInFile(inds, series_file, nbytes, endian)
        }
        else
-               getSeries = series
+               getSeries <- series
 
        # Serialize all computed wavelets contributions into a file
-       contribs_file = ".contribs.epclust.bin"
-       index = 1
-       nb_curves = 0
+       contribs_file <- ".contribs.epclust.bin"
+       index <- 1
+       nb_curves <- 0
        if (verbose)
                cat("...Compute contributions and serialize them (or retrieve past binary file)\n")
        if (!file.exists(contribs_file))
        {
-               nb_curves = binarizeTransform(getSeries,
+               nb_curves <- binarizeTransform(getSeries,
                        function(curves) curvesToContribs(curves, wav_filt, contrib_type),
                        contribs_file, nb_series_per_chunk, nbytes, endian)
        }
        else
        {
                # TODO: duplicate from getDataInFile() in de_serialize.R
-               contribs_size = file.info(contribs_file)$size #number of bytes in the file
-               contrib_length = readBin(contribs_file, "integer", n=1, size=8, endian=endian)
-               nb_curves = (contribs_size-8) / (nbytes*contrib_length)
+               contribs_size <- file.info(contribs_file)$size #number of bytes in the file
+               contrib_length <- readBin(contribs_file, "integer", n=1, size=8, endian=endian)
+               nb_curves <- (contribs_size-8) / (nbytes*contrib_length)
        }
-       getContribs = function(indices) getDataInFile(indices, contribs_file, nbytes, endian)
+       getContribs <- function(indices) getDataInFile(indices, contribs_file, nbytes, endian)
 
        # A few sanity checks: do not continue if too few data available.
        if (nb_curves < K2)
                stop("Not enough data: less series than final number of clusters")
-       nb_series_per_task = round(nb_curves / ntasks)
+       nb_series_per_task <- round(nb_curves / ntasks)
        if (nb_series_per_task < K2)
                stop("Too many tasks: less series in one task than final number of clusters")
 
        # Generate a random permutation of 1:N (if random==TRUE);
        # otherwise just use arrival (storage) order.
-       indices_all = if (random) sample(nb_curves) else seq_len(nb_curves)
+       indices_all <- if (random) sample(nb_curves) else seq_len(nb_curves)
        # Split (all) indices into ntasks groups of ~same size
-       indices_tasks = lapply(seq_len(ntasks), function(i) {
-               upper_bound = ifelse( i<ntasks, min(nb_series_per_task*i,nb_curves), nb_curves )
+       indices_tasks <- lapply(seq_len(ntasks), function(i) {
+               upper_bound <- ifelse( i<ntasks, min(nb_series_per_task*i,nb_curves), nb_curves )
                indices_all[((i-1)*nb_series_per_task+1):upper_bound]
        })
 
@@ -243,43 +244,43 @@ claws <- function(series, K1, K2, nb_series_per_chunk, nb_items_clust=7*K1,
        {
                # Initialize parallel runs: outfile="" allow to output verbose traces in the console
                # under Linux. All necessary variables are passed to the workers.
-               cl = parallel::makeCluster(ncores_tasks, outfile="")
-               varlist = c("ncores_clust","verbose","parll", #task 1 & 2
+               cl <- parallel::makeCluster(ncores_tasks, outfile="")
+               varlist <- c("ncores_clust","verbose","parll", #task 1 & 2
                        "K1","getContribs","algoClust1","nb_items_clust") #task 1
                if (WER=="mix")
                {
                        # Add variables for task 2
-                       varlist = c(varlist, "K2","getSeries","algoClust2","nb_series_per_chunk",
-                               "nvoice","nbytes","endian")
+                       varlist <- c(varlist, "K2","getSeries","algoClust2","nb_series_per_chunk",
+                               "smooth_lvl","nvoice","nbytes","endian")
                }
-               parallel::clusterExport(cl, varlist, envir = environment())
+               parallel::clusterExport(cl, varlist, envir <- environment())
        }
 
        # This function achieves one complete clustering task, divided in stage 1 + stage 2.
        # stage 1: n indices  --> clusteringTask1(...) --> K1 medoids (indices)
        # stage 2: K1 indices --> K1xK1 WER distances --> clusteringTask2(...) --> K2 medoids,
-       # where n = N / ntasks, N being the total number of curves.
-       runTwoStepClustering = function(inds)
+       # where n == N / ntasks, N being the total number of curves.
+       runTwoStepClustering <- function(inds)
        {
                # When running in parallel, the environment is blank: we need to load the required
                # packages, and pass useful variables.
                if (parll && ntasks>1)
                        require("epclust", quietly=TRUE)
-               indices_medoids = clusteringTask1(inds, getContribs, K1, algoClust1,
+               indices_medoids <- clusteringTask1(inds, getContribs, K1, algoClust1,
                        nb_items_clust, ncores_clust, verbose, parll)
                if (WER=="mix")
                {
-                       indices_medoids = clusteringTask2(indices_medoids, getSeries, K2, algoClust2,
-                               nb_series_per_chunk, nvoice, nbytes, endian, ncores_clust, verbose, parll)
+                       indices_medoids <- clusteringTask2(indices_medoids, getSeries, K2, algoClust2,
+                               nb_series_per_chunk,smooth_lvl,nvoice,nbytes,endian,ncores_clust,verbose,parll)
                }
                indices_medoids
        }
 
        if (verbose)
        {
-               message = paste("...Run ",ntasks," x stage 1", sep="")
+               message <- paste("...Run ",ntasks," x stage 1", sep="")
                if (WER=="mix")
-                       message = paste(message," + stage 2", sep="")
+                       message <- paste(message," + stage 2", sep="")
                cat(paste(message,"\n", sep=""))
        }
 
@@ -304,15 +305,15 @@ claws <- function(series, K1, K2, nb_series_per_chunk, nb_items_clust=7*K1,
        # Run last clustering tasks to obtain only K2 medoids indices
        if (verbose)
                cat("...Run final // stage 1 + stage 2\n")
-       indices_medoids = clusteringTask1(indices_medoids_all, getContribs, K1, algoClust1,
+       indices_medoids <- clusteringTask1(indices_medoids_all, getContribs, K1, algoClust1,
                nb_items_clust, ncores_tasks*ncores_clust, verbose, parll)
-       indices_medoids = clusteringTask2(indices_medoids, getContribs, K2, algoClust2,
-               nb_series_per_chunk, nvoice, nbytes, endian, ncores_last_stage, verbose, parll)
+       indices_medoids <- clusteringTask2(indices_medoids, getContribs, K2, algoClust2,
+               nb_series_per_chunk,smooth_lvl,nvoice,nbytes,endian,ncores_last_stage,verbose,parll)
 
        # Compute synchrones, that is to say the cumulated power consumptions for each of the K2
        # final groups.
-       medoids = getSeries(indices_medoids)
-       synchrones = computeSynchrones(medoids, getSeries, nb_curves, nb_series_per_chunk,
+       medoids <- getSeries(indices_medoids)
+       synchrones <- computeSynchrones(medoids, getSeries, nb_curves, nb_series_per_chunk,
                ncores_last_stage, verbose, parll)
 
        # NOTE: no need to use big.matrix here, since there are only K2 << K1 << N remaining curves