+ computeSynchronesChunk = function(indices)
+ {
+ if (verbose)
+ cat(paste("--- Compute synchrones for ",length(indices)," lines\n", sep=""))
+ ref_series = getRefSeries(indices)
+ #get medoids indices for this chunk of series
+ for (i in seq_len(nrow(ref_series)))
+ {
+ j = which.min( rowSums( sweep(medoids, 2, ref_series[i,], '-')^2 ) )
+ if (parll)
+ synchronicity::lock(m)
+ synchrones[j,] = synchrones[j,] + ref_series[i,]
+ counts[j,1] = counts[j,1] + 1
+ if (parll)
+ synchronicity::unlock(m)
+ }
+ }
+
+ K = nrow(medoids)
+ # Use bigmemory (shared==TRUE by default) + synchronicity to fill synchrones in //
+ synchrones = bigmemory::big.matrix(nrow=K,ncol=ncol(medoids),type="double",init=0.)
+ counts = bigmemory::big.matrix(nrow=K,ncol=1,type="double",init=0)
+ # Fork (// run) only on Linux & MacOS; on Windows: run sequentially
+ parll = (requireNamespace("synchronicity",quietly=TRUE)
+ && parll && Sys.info()['sysname'] != "Windows")
+ if (parll)
+ m <- synchronicity::boost.mutex()
+
+ indices_workers = .spreadIndices(seq_len(nb_ref_curves), nb_series_per_chunk)
+ ignored <-
+ if (parll)
+ {
+ parallel::mclapply(indices_workers, computeSynchronesChunk,
+ mc.cores=ncores_clust, mc.allow.recursive=FALSE)
+ }
+ else
+ lapply(indices_workers, computeSynchronesChunk)
+
+ mat_syncs = matrix(nrow=K, ncol=ncol(medoids))
+ vec_count = rep(NA, K)
+ #TODO: can we avoid this loop?
+ for (i in seq_len(K))
+ {
+ mat_syncs[i,] = synchrones[i,]
+ vec_count[i] = counts[i,1]
+ }
+ #NOTE: odds for some clusters to be empty? (when series already come from stage 2)
+ # ...maybe; but let's hope resulting K1' be still quite bigger than K2
+ mat_syncs = sweep(mat_syncs, 1, vec_count, '/')
+ mat_syncs[ sapply(seq_len(K), function(i) all(!is.nan(mat_syncs[i,]))) , ]