/
matrixOps.R
713 lines (592 loc) · 22.3 KB
/
matrixOps.R
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# Matrix operations ----
#' @title Distance to binary matrix
#'
#' @description Distance matrix to binary matrix based on threshold value
#'
#' @param distmat Distance matrix
#' @param emRad The radius or threshold value
#' @param convMat Should the matrix be converted from a `distmat` object of class [Matrix::Matrix()] to [base::matrix()] (or vice versa)
#'
#' @return A (sparse) matrix with only 0s and 1s
#'
#' @export
#'
#' @family Distance matrix operations (recurrence plot)
#' @family Distance matrix operations (recurrence network)
#'
mat_di2bi <- function(distmat, emRad = NA, convMat = FALSE){
matPack <- FALSE
# if already Matrix do not convert to matrix
if(any(grepl("Matrix",class(distmat)))){
matPack <- TRUE
convMat <- TRUE
}
distmat <- rp_checkfix(distmat, checkAUTO = TRUE, fixAUTO = TRUE)
#attributes(distmat)
if(any(is.na(distmat))){
NAij <- Matrix::which(is.na(distmat), arr.ind=TRUE)
} else {
NAij <- NA
}
# RP <- matrix(0,dim(distmat)[1],dim(distmat)[2])
# RP[as.matrix(distmat <= emRad)] <- 1
if(is.na(emRad)){emRad <- est_radius(distmat)$Radius}
if(emRad==0){emRad <- .Machine$double.eps}
# Always use sparse representation for conversion to save memory load
ij <- Matrix::which(distmat <= emRad, arr.ind=TRUE)
if(NROW(ij)>0){
xij <- data.frame(y = sapply(seq_along(ij[,1]),function(r){distmat[ij[[r,1]],ij[[r,2]]]}), ij)
suppressMessages(RP <- Matrix::sparseMatrix(x=rep(1,length(xij$y)),i=xij$row,j=xij$col, dims = dim(distmat)))
# Simple check
if(!all(stats::na.exclude(as.vector(RP))%in%c(0,1))){warning("Matrix did not convert to a binary (0,1) matrix!!")}
} else {
RP <- matrix(0,dim(distmat)[1],dim(distmat)[2])
}
if(convMat&matPack){RP <- Matrix::as.matrix(RP)}
suppressMessages(RP <- rp_copy_attributes(source = distmat, target = RP))
attributes(RP)$emRad <- emRad
attributes(RP)$NAij <- NAij
return(RP)
}
#' @title Distance to weighted matrix
#'
#' @description Distance matrix to weighted matrix based on threshold value
#'
#' @param distmat Distance matrix
#' @param emRad The radius or threshold value
#' @param theiler Use a theiler window around the line of identity / synchronisation to remove high auto-correlation at short time-lags (default = `0`)
#' @param convMat convMat Should the matrix be converted from a `distmat` object of class [Matrix::Matrix()] to [base::matrix()] (or vice versa)
#'
#' @return A matrix with 0s and values < threshold distance value
#'
#' @export
#'
#' @family Distance matrix operations (recurrence plot)
#' @family Distance matrix operations (recurrence network)
#'
mat_di2we <- function(distmat, emRad, theiler = 0, convMat = FALSE){
matPack <- FALSE
if(any(grepl("Matrix",class(distmat)))){
matPack <- TRUE
convMat <- TRUE
}
# RP <- NetComp::matrix_threshold(distmat,threshold = emRad, minval = 1, maxval = 0)
if(emRad==0) emRad <- .Machine$double.eps
# RP <- distmat #matrix(0,dim(distmat)[1],dim(distmat)[2])
# RP[distmat <= emRad] <- 0
if(any(is.na(distmat))){
NAij <- Matrix::which(is.na(distmat), arr.ind=TRUE)
} else {
NAij <- NA
}
ij <- Matrix::which(distmat <= emRad, arr.ind=TRUE)
if(NROW(ij)>0){
# Always use sparse representation for conversion to save memory load
#xij <- data.frame(y = sapply(which(distmat > emRad, arr.ind=TRUE)[,1],function(r){distmat[ij[[r,1]],ij[[r,2]]]}), which(distmat > emRad, arr.ind=TRUE))
xij <- data.frame(y = sapply(seq_along(ij[,1]),function(r){distmat[ij[[r,1]],ij[[r,2]]]}), ij)
suppressWarnings(RP <- Matrix::sparseMatrix(x=xij$y,i=xij$row,j=xij$col, dims = dim(distmat)))
# if(!all(as.vector(RP)==0|as.vector(RP)==1)){warning("Matrix did not convert to a binary (0,1) matrix!!")}
} else {
RP <- matrix(0,dim(distmat)[1],dim(distmat)[2])
}
if(convMat&matPack){RP <- Matrix::as.matrix(RP)}
RP <- rp_copy_attributes(source = distmat, target = RP)
attributes(RP)$emRad <- emRad
attributes(RP)$NAij <- NAij
return(RP)
}
#' @title Distance to chromatic matrix
#'
#' @description
#' Distance matrix to chromatic matrix based on unordered categorical series
#'
#' @param distmat Distance matrix
#' @param y One of the dimensions (as a data frame or matrix) of the RP which must contain unique unordered categorical values
#' @param emRad The radius or threshold value
#' @param theiler Use a theiler window around the line of identity / synchronisation to remove high auto-correlation at short time-lags (default = `0`)
#' @param convMat convMat Should the matrix be converted from a `distmat` object of class [Matrix::Matrix()] to [base::matrix()] (or vice versa)
#'
#' @return A matrix with 0s and the unordered categorical values that are recurring
#'
#' @export
#'
#' @family Distance matrix operations (recurrence plot)
#' @family Distance matrix operations (recurrence network)
#'
mat_di2ch <- function(distmat, y, emRad, theiler = 0, convMat = FALSE){
matPack <- FALSE
if(any(grepl("Matrix",class(distmat)))){
matPack <- TRUE
convMat <- TRUE
}
if(any(is.na(distmat))){
NAij <- Matrix::which(is.na(distmat), arr.ind=TRUE)
} else {
NAij <- NA
}
if(emRad==0) emRad <- .Machine$double.eps
ij <- Matrix::which(distmat <= emRad, arr.ind=TRUE)
if(NROW(ij)>0){
# Always use sparse representation for conversion to save memory load
#xij <- data.frame(y = sapply(which(distmat > emRad, arr.ind=TRUE)[,1],function(r){distmat[ij[[r,1]],ij[[r,2]]]}), which(distmat > emRad, arr.ind=TRUE))
xij <- data.frame(y = sapply(seq_along(ij[,1]),function(r){y[ij[r,1]]}), ij)
suppressWarnings(RP <- Matrix::sparseMatrix(x=xij$y,i=xij$row,j=xij$col, dims = dim(distmat)))
# if(!all(as.vector(RP)==0|as.vector(RP)==1)){warning("Matrix did not convert to a binary (0,1) matrix!!")}
} else {
RP <- matrix(0,dim(distmat)[1],dim(distmat)[2])
}
if(convMat&matPack){RP <- Matrix::as.matrix(RP)}
RP <- rp_copy_attributes(source = distmat, target = RP)
attributes(RP)$emRad <- emRad
attributes(RP)$NAij <- NAij
return(RP)
}
#' @title Weighted to Binary matrix
#'
#' @inheritParams mat_di2bi
#'
#' @return A binary matrix
#'
#' @export
#'
mat_we2bi <- function(distmat, emRad, theiler = 0, convMat = FALSE){
matPack <- FALSE
if(any(grepl("Matrix",class(distmat)))){
matPack <- TRUE
convMat <- TRUE
}
# RP <- NetComp::matrix_threshold(distmat,threshold = emRad, minval = 1, maxval = 0)
if(emRad==0) emRad <- .Machine$double.eps
# RP <- distmat #matrix(0,dim(distmat)[1],dim(distmat)[2])
# RP[distmat <= emRad] <- 0
if(any(is.na(distmat))){
NAij <- Matrix::which(is.na(distmat), arr.ind=TRUE)
} else {
NAij <- NA
}
ij <- Matrix::which(distmat > 0, arr.ind=TRUE)
if(NROW(ij)>0){
# Always use sparse representation for conversion to save memory load
#xij <- data.frame(y = sapply(which(distmat > emRad, arr.ind=TRUE)[,1],function(r){distmat[ij[[r,1]],ij[[r,2]]]}), which(distmat > emRad, arr.ind=TRUE))
xij <- data.frame(y = sapply(seq_along(ij[,1]),function(r){distmat[ij[[r,1]],ij[[r,2]]]}), ij)
suppressWarnings(RP <- Matrix::sparseMatrix(x=1,i=xij$row,j=xij$col, dims = dim(distmat)))
# if(!all(as.vector(RP)==0|as.vector(RP)==1)){warning("Matrix did not convert to a binary (0,1) matrix!!")}
} else {
RP <- matrix(0,dim(distmat)[1],dim(distmat)[2])
}
if(convMat&matPack){RP <- Matrix::as.matrix(RP)}
RP <- rp_copy_attributes(source = distmat, target = RP)
attributes(RP)$emRad <- emRad
attributes(RP)$NAij <- NAij
return(RP)
}
#' Matrix to indexed data frame
#'
#' Mimics the default behaviour of `reshape2::melt()`
#'
#' @param mat A matrix
#'
#' @return A data.frame with two index columns named `"Var1"` and `"Var2"`
#'
#' @export
#'
#' @examples
#' mat_mat2ind(as.matrix(1:100,ncol=10))
#'
mat_mat2ind <- function(mat){
if(all(!is.matrix(mat),!attr(class(mat),"package")%in%"Matrix")){stop("Input has to be a matrix.")}
ind <- which(!is.na(mat), arr.ind = TRUE)
out <- cbind.data.frame(ind, mat[!is.na(mat)])
colnames(out) <- c("Var1","Var2","value")
return(out)
}
#' Get indices of matrix diagonals, rows, or columns
#'
#' @param Xlength X dim
#' @param Ylength Y dim
#' @param index index of diagonal, row or column
#' @param diagonal diagonal
#' @param horizontal horizontal
#'
#' @return list
#'
#' @export
#'
mat_ind <- function(Xlength, Ylength, index, diagonal = FALSE){
if(diagonal){
if(index>=0){
Xx <- seq(1,(Xlength-index))
Yy <- seq((index+1),Ylength)
} else {
index <- abs(index)
# Yy <- seq(1,(Xlength-index))
# Xx <- seq((index+1),Ylength)
Yy <- seq(1,(Xlength-index))
Xx <- seq((index+1),Ylength)
}
return(list(r = Xx, c = Yy))
} else {
# if(symmetrical){
Yy <- seq(1,Ylength)
Xx <- index
# } else {
# Yy <- seq(1,Ylength)
# Xx <- index
# }
# if(horizontal){
# return(list(r = Yy, c = Xx))
# } else {
return(list(r = Xx, c = Yy))
# }
}
}
#' Calculate Hamming distance
#'
#' @param X A matrix (of coordinates)
#' @param Y A matrix (of coordinates)
#' @param embedded Do X and/or Y represent surrogate dimensions of an embedded time series?
#'
#' @return A hamming-distance matrix of X, or X and Y. Useful for ordered and unordered categorical data.
#' @export
#'
#' @family Distance matrix operations (recurrence plot)
#' @author Fred Hasselman
#'
mat_hamming <- function(X, Y=NULL, embedded=TRUE) {
if ( missing(Y) ) {
if(embedded){
# X and Y represent delay-embeddings of a timeseries
if(which.max(dim(X))==1){X <- t(X)}
}
uniqs <- unique(as.vector(X))
U <- X == uniqs[1]
H <- t(U) %*% U
for ( uniq in uniqs[-1] ) {
U <- X == uniq
H <- H + t(U) %*% U
}
} else {
if(embedded){
# X and Y represent delay-embeddings of a timeseries
if(which.max(dim(X))==1){X <- t(X)}
if(which.max(dim(Y))==1){Y <- t(Y)}
}
uniqs <- union(X, Y)
H <- t(X == uniqs[1]) %*% (Y == uniqs[1])
for ( uniq in uniqs[-1] ) {
H <- H + t(X == uniq) %*% (Y == uniq)
}
}
NROW(X) - H
}
#' Replace matrix diagonals
#'
#' Sets a band of matrix diagonals to any given value
#'
#' @param mat A Matrix
#' @param lower Lower diagonal to be included in the band (should be \eqn{\le 0})
#' @param upper Upper diagonal to be included in the band (should be \eqn{\ge 0})
#' @param value A single value to replace all values in the selected band (default = `NA`)
#' @param silent Operate in silence, only (some) warnings will be shown (default = `TRUE`)
#'
#' @return A matrix in which the values in the selected diagonals have been replaced
#'
#' @export
#'
#' @family Distance matrix operations (recurrence plot)
#'
#' @author Fred Hasselman
#'
#'
#' @examples
#' # Create a 10 by 10 matrix
#' library(Matrix)
#' m <- Matrix(rnorm(10),10,10)
#'
#' bandReplace(m,-1,1,0) # Replace diagonal and adjacent bands with 0 (Theiler window of 1)
bandReplace <- function(mat, lower, upper, value = NA, silent=TRUE){
# if(lower>0){lower=-1*lower
# warning("lower > 0 ...\n using: -1*lower")
# }
# if(upper<0){upper=abs(upper)
# warning("upper > 0 ...\n using: abs(upper)")
# }
# if(all(lower==0,upper==0)){
# #diag(mat) <- value
# if(!silent){message(paste0("lower and upper are both 0 (no band, just diagonal)\n using: diag(mat) <- ",round(value,4),"..."))}
# }
tmp <- mat
delta <- col(mat)-row(mat)
indc <- delta >= lower & delta <= upper
suppressMessages(mat[indc] <- value)
mat <- methods::as(mat, "dgCMatrix")
mat <- rp_copy_attributes(source = tmp, target = mat, source_remove = c("names", "row.names", "class","dim", "dimnames","x","i","p"))
rm(tmp)
return(mat)
}
#' Corridor analysis
#'
#' Create a corridor around the main diagonal. For long time series it may not make sense to evaluate recurrences on the longest time scales.
#'
#' @param mat A Matrix
#' @param lower Lower diagonal to be included in the corridor (should be \eqn{\le 0})
#' @param upper Upper diagonal to be included in the corridor (should be \eqn{\ge 0})
#' @param value A single value to replace all values outside the corridor (default = `NA`)
#' @param silent Operate in silence, only (some) warnings will be shown (default = `TRUE`)
#'
#' @return A matrix in which the values outside the corridor have been replaced
#'
#' @export
#'
#' @family Distance matrix operations (recurrence plot)
#'
#' @author Fred Hasselman
#'
#'
#' @examples
#' # Create a 10 by 10 matrix
#' library(Matrix)
#' m <- Matrix(rnorm(10),10,10)
#'
#' createCorridor(m,-7,7,0) # Set diagonals 10 9 and 8 to 0.
createCorridor <- function(mat, lower, upper, value = NA, silent=TRUE){
# if(lower>0){lower=-1*lower
# warning("lower > 0 ...\n using: -1*lower")
# }
# if(upper<0){upper=abs(upper)
# warning("upper > 0 ...\n using: abs(upper)")
# }
# if(all(lower==0,upper==0)){
# #diag(mat) <- value
# if(!silent){message(paste0("lower and upper are both 0 (no band, just diagonal)\n using: diag(mat) <- ",round(value,4),"..."))}
# }
tmp <- mat
delta <- col(mat)-row(mat)
indc <- delta < lower & delta > upper
suppressMessages(mat[indc] <- value)
mat <- methods::as(mat, "dgCMatrix")
mat <- rp_copy_attributes(source = tmp, target = mat, source_remove = c("names", "row.names", "class","dim", "dimnames","x","i","p"))
rm(tmp)
return(mat)
}
#' Set theiler window on a distance matrix or recurrence matrix.
#'
#' @inheritParams rp
#' @inheritParams rp_measures
#'
#' @return The matrix with the diagonals indicated in the `theiler` argument set to either `max(RM)+1` (if `RM` is a distance matrix) or `0` (if `RM` is a recurrence matrix).
#'
#' @export
#'
setTheiler <- function(RM, theiler = NA, silent = FALSE, chromatic = FALSE){
checkPkg("Matrix")
# Check auto-recurrence
RM <- rp_checkfix(RM, checkAUTO = TRUE, fixAUTO = TRUE)
skip <- FALSE
# Theiler
if(!is.na(attributes(RM)$theiler%00%NA)){
if(is.numeric(attributes(RM)$theiler)){
if(!silent){message(paste0("Value found in attribute 'theiler'... assuming a theiler window of size: ",attributes(RM)$theiler," was already removed."))}
skip <- TRUE
} else {
if(!silent){message(paste0("Value found in attribute 'theiler' is not numeric (",attributes(RM)$theiler,"), setting: 'theiler <- NA'"))}
theiler <- NA
}
} else {
if(!is.numeric(theiler)){
if(!is.na(theiler)){
if(!silent){message(paste0("Value passed to 'theiler' is not numeric (",attributes(RM)$theiler,"), setting: 'theiler <- NA'"))}
theiler <- NA
}
}
}
if(is.na(theiler)){
if(attributes(RM)$AUTO){
theiler <- 1
} else {
theiler <- 0
}
}
if(length(theiler)==1){
if(theiler < 0){theiler <- 0}
if(length(Matrix::diag(RM))<length(-theiler:theiler)){
if(!silent){message("Ignoring theiler window, it is larger than the matrix...")}
skip <- TRUE
}
if(theiler == 0){skip <- TRUE}
}
if(length(theiler==2)){
if(length(Matrix::diag(RM))<length(min(theiler):max(theiler))){
if(!silent){message("Ignoring theiler window, it is larger than the matrix...")}
skip <- TRUE
}
}
if(length(theiler>2)){
if(any(length(Matrix::diag(RM))<abs(theiler))){
if(!silent){message("Ignoring theiler window, it contains diagonals that are larger than the matrix...")}
skip <- TRUE
}
}
if(!skip){
if(all(as.vector(RM)==0|as.vector(RM)==1)|chromatic){
value <- 0
} else {
value <- max(Matrix::as.matrix(RM), na.rm = TRUE)+1
}
#LOS <- diag(RM)
if(length(theiler)==1){
if(theiler > 1){
theiler <- (theiler-1)
RM <- bandReplace(mat = RM, lower = -theiler, upper = theiler, value = value)
} else {
if(theiler != 0){
RM <- bandReplace(mat = RM, lower = 0, upper = 0, value = value)
}
}
}
if(length(theiler)==2){
RM <- bandReplace(mat = RM, lower = min(theiler), upper = max(theiler), value = value)
}
if(length(theiler)>2){
theiler <- sort(theiler)
for(d in seq_along(theiler)){
RM <- bandReplace(mat = RM, lower = theiler[d], upper = theiler[d], value = value)
}
}
attr(RM,"theiler") <- theiler
} # skip
return(RM)
}
#' Course grain a matrix for plotting
#'
#'
#' @param RM A (recurrence) matrix
#' @param target_height How many rows? (default = `NROW(RM)/2`)
#' @param target_width How many columns? (default = `NCOL(RM)/2`)
#' @param summary_func How to summarise the values in subset `X` of `RM`. If set to `NA`, the function will try to pick a summary function based on the cell values: If `RM` is a distance matrix, `mean(X, na.rm = TRUE)` will be used; If it is a binary matrix `ifelse(mean(X, na.rm = TRUE)>recurrence_threshold,1,0)`, a categorical matrix (`categorical = TRUE`, or, matrix attribute `chromatic = TRUE`) will pick the most frequent category in the subset `attributes(ftable(X))$col.vars$x[[which.max(ftable(X))]]`. (default = `NA`)
#' @param recurrence_threshold For a binary matrix the mean of the cells to be summarised will vary between `0` and `1`, which essentially represents the recurrence rate for that subset of the matrix. If `NA` the threshold will be set to a value that in most cases should return a plot with a similar `RR` as the original plot. (default = `NA`)
#' @param categorical If set to `TRUE`, will force `summary_func` to select the most frequent value. If `NA` the matrix attribute `chromatic` will be used. If `chromatic` is not present, all values in the matrix have to be whole numbers as determined by `plyr::is.discrete()`. (default = `NA`)
#' @param output_type The output format for `plyr::vapply()`. (default = `0.0`)
#' @param n_core Number of cores for parallel processing. Set to `NA` to automatically choose cores. (default = `1`)
#' @param silent Silt-ish mode (default = `FALSE`)
#'
#' @note This code was inspired by code published in a blog post by Guillaume Devailly on 29-04-2020 (https://gdevailly.netlify.app/post/plotting-big-matrices-in-r/)
#'
#' @return A coursegrained matrix of size `target_width` by `target_height`.
#'
#' @export
#'
#' @examples
#'
#' # Continuous
#' RMc1 <- rp(cumsum(rnorm(200)))
#' rp_plot(RMc1)
#' RMc2 <- mat_coursegrain(RMc1)
#' rp_plot(RMc2)
#'
#' # Binary
#' RMb1 <- rp(cumsum(rnorm(200)), emRad = NA)
#' rp_plot(RMb1, plotMeasures = TRUE)
#' # Reported RQA measures in rp_plot will be based on the full matrix
#' rp_plot(RMb1, maxSize = 100^2, plotMeasures = TRUE)
#' # Plotting the coursegrained matrix itself will yield different values
#' RMb2 <- mat_coursegrain(RMb1)
#' rp_plot(RMb2, plotMeasures = TRUE)
#'
#' # Categorical
#' RMl1 <- rp(y1 = round(runif(100, min = 1, max = 3)), chromatic = TRUE)
#' rp_plot(RMl1)
#' RMl2 <- mat_coursegrain(RMl1, categorical = TRUE)
#' rp_plot(RMl2)
#'
mat_coursegrain <- function(RM,
target_height = round(NROW(RM)/2),
target_width = round(NCOL(RM)/2),
summary_func = NA,
recurrence_threshold = NA,
categorical = NA,
output_type = 0.0, #vapply style
n_core = 1, # parallel processing
silent = FALSE){
# square?
if(NROW(RM)==NCOL(RM)){
if(target_height!=target_width){
stop("Original matrix is square, but target dimensions are not!")
}
}
if(target_height > NROW(RM) | target_width > NCOL(RM)){
stop("Input matrix must be bigger than target width and height.")
}
if(is.na(recurrence_threshold)){
if(all(stats::na.exclude(as.vector(RM))%in%c(0,1))){
RR <- rp_measures(RM)
recurrence_threshold <- mean(c(RR$RR,RR$SING_rate,RR$DET,RR$LAM_hv), na.rm = TRUE)
rm(RR)
#((NROW(RM)*NCOL(RM))/(target_height*target_width))
}
} else {
if(recurrence_threshold%)(%c(0,1)){
recurrence_threshold <- mean(RM, na.rm = TRUE)
}
}
if(is.na(categorical)){
if(attributes(RM)$chromatic|all(plyr::is.discrete(RM))){
categorical <- TRUE
} else {
categorical <- FALSE
}
}
if(is.na(n_core)){
n_core <- parallel::detectCores()-1
}
if(n_core>1){
available_core <- parallel::detectCores()
if(!n_core%[]%c(2,available_core)){
n_core <- (available_core-1)
}
}
if(is.na(summary_func)){
if(all(stats::na.exclude(as.vector(RM))%in%c(0,1))){
summary_func <- function(x){ifelse(mean(x, na.rm = TRUE)>recurrence_threshold,1,0)}
if(!silent){message("Binary matrix... using summary function 'ifelse(mean(x, na.rm = TRUE)>recurrence_threshold,1,0)' for coursegraining.")}
} else {
if(categorical){
summary_func <- function(x){as.numeric(attributes(stats::ftable(x))$col.vars$x[[which.max(stats::ftable(x))]])}
if(!silent){message("Categorical matrix... using summary function 'attributes(ftable(x))$col.vars[[which.max(ftable(x))]]' for coursegraining.")}
} else {
if(!all(plyr::is.discrete(RM))){
summary_func <- function(x){mean(x, na.rm = TRUE)}
if(!silent){message("Continuous matrix... using summary function 'mean(x, na.rm = TRUE)' for coursegraining.")}
}
}
}
}
tmpMat <- as.matrix(RM)
seq_height <- round(seq(1, NROW(RM), length.out = target_height + 1))
seq_width <- round(seq(1, NCOL(RM), length.out = target_width + 1))
# subMat <- list()
# m <- 0
# for(i in seq_len(target_height)){
# for(j in seq_len(target_width)){
# m <- m + 1
# subMat[[m]] <- list(x = seq(seq_height[i], seq_height[i + 1]),
# y = seq(seq_width[j], seq_width[j + 1]))
# }
# }
#
# tmpMat <- matrix(plyr::laply(subMat, function(f) summary_func(as.numeric(RM[f$x,f$y]))),nrow = target_height, ncol = target_width)
# rp_plot(tmpMat, courseGrain = FALSE)
# complicated way to write a double for loop
tmpMat <- do.call(rbind, parallel::mclapply(seq_len(target_height), function(i) { # i is row
vapply(seq_len(target_width), function(j) { # j is column
summary_func(as.numeric(RM[seq(seq_height[i], seq_height[i + 1]), seq(seq_width[j] , seq_width[j + 1])]))
}, output_type)
}, mc.cores = n_core))
# tmpMat <- purrr::map(seq_len(target_height), ~ purrr::map(seq_len(target_width), ~ summary_func(as.numeric(RM[seq(seq_height[.x], seq_height[.x + 1]), seq(seq_width[.y] , seq_width[.y + 1])])), .y=.x))
#
tmpMat <- Matrix::as.matrix(tmpMat)
tmpMat <- rp_copy_attributes(source = RM, target = tmpMat)
tmpMat <- rp_checkfix(tmpMat, checkS4 = TRUE, fixS4 = TRUE, checkAUTO = TRUE, fixAUTO = TRUE)
rm(RM)
return(tmpMat)
}