cute_little_R_functions.R 711 KB
Newer Older
Gael  MILLOT's avatar
Gael MILLOT committed
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
list.diag[[i0]] <- numeric(length = nrow(mat) - i0)
}
sector <- c("topleft", "topright", "bottomright", "bottomleft")
diag.scan <-c( # same order as sector. Recover each diag from center to corner
"mat[as.matrix(as.data.frame(list(1:(nrow(mat) - i1), (ncol(mat) -i1):1)))]", # topleft part
"mat[as.matrix(as.data.frame(list(1:(nrow(mat) - i1), (1:ncol(mat))[-(1:i1)])))]", # topright part
"mat[as.matrix(as.data.frame(list((1 + i1):nrow(mat), ncol(mat):(1 + i1))))]", # bottomright part
"mat[as.matrix(as.data.frame(list((1 + i1):nrow(mat), 1:(ncol(mat) -i1))))]" # bottomleft part
)
# empty part detection
tempo.list.diag <- list.diag
empty.sector <- NULL
full.sector <- NULL
warning <- NULL
for(i0 in 1:length(sector)){
tempo.list.diag <- list.diag
for(i1 in 1:(nrow(mat) - 1)){
tempo.list.diag[[i1]] <- eval(parse(text = diag.scan[i0]))
if(ifelse(is.na(empty.cell.string), ! all(is.na(tempo.list.diag[[i1]])), ! (all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = TRUE) & ! (is.na(all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = FALSE)))))){ # I had to add this ! (is.na(all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = FALSE))) because all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = FALSE) gives NA and not FALSE if one NA in tempo.list.diag[[i1]] -> not good for if()
full.sector <- c(full.sector, sector[i0])
break
}
}
if(i1 == nrow(mat) - 1){
if(all(unlist(lapply(tempo.list.diag, FUN = function(x){if(is.na(empty.cell.string)){is.na(x)}else{x == empty.cell.string}})), na.rm = TRUE)){
empty.sector <- c(empty.sector, sector[i0])
Gael  MILLOT's avatar
Gael MILLOT committed
2027
tempo.warning <- paste0("FROM FUNCTION ", function.name, ": EMPTY SECTOR DETECTED ON THE ", toupper(sector[i0]), " CORNER, FULL OF ", empty.cell.string)
Gael  MILLOT's avatar
Gael MILLOT committed
2028
2029
2030
2031
2032
2033
2034
warning <- paste0(ifelse(is.null(warning), tempo.warning, paste0(warning, "\n\n", tempo.warning)))
}else{
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE ", toupper(sector[i0]), " SECTOR, DETECTED AS EMPTY, IS NOT? DIFFERENT VALUES IN THIS SECTOR:\n", paste(names(table(unlist(tempo.list.diag), useNA = "ifany")), collapse = " "), "\n\n================\n\n")
stop(tempo.cat)
}
}
}
Gael  MILLOT's avatar
Gael MILLOT committed
2035
# end empty part detection
Gael  MILLOT's avatar
Gael MILLOT committed
2036
if(length(empty.sector) == 0){
Gael  MILLOT's avatar
Gael MILLOT committed
2037
2038
2039
2040
tempo.warning <- paste0("FROM FUNCTION ", function.name, ": ACCORDING TO empty.cell.string ARGUMENT (", empty.cell.string, "), mat ARGUMENT MATRIX HAS ZERO EMPTY HALF PART")
warning <- paste0(ifelse(is.null(warning), tempo.warning, paste0(warning, "\n\n", tempo.warning)))
}else{
if(length(empty.sector) > 1){
Gael  MILLOT's avatar
Gael MILLOT committed
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": ACCORDING TO empty.cell.string ARGUMENT (", empty.cell.string, "), mat ARGUMENT MATRIX HAS MORE THAN ONE EMPTY HALF PART (ACCORDING TO THE GRAND DIAGONAL): ", paste(empty.sector, collapse = " "), "\n\n================\n\n")
stop(tempo.cat)
}else if(any(full.sector %in% empty.sector, na.rm = TRUE)){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE FUNCTION HAS DETECTED EMPTY AND NON EMPTY HALF PART IN THE SAME SECTOR: ", paste(full.sector[full.sector %in% empty.sector], collapse = " "), "\n\n================\n\n")
stop(tempo.cat)
}else if(length(empty.sector) + length(full.sector)!= 4){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE FUNCTION HAS DETECTED MORE OR LESS SECTORS THAN 4:\nEMPTY SECTORS:", paste(empty.sector, collapse = " "), "\nFULL SECTORS:", paste(full.sector, collapse = " "), "\n\n================\n\n")
stop(tempo.cat)
}
# matrix filling
for(i1 in 1:(nrow(mat) - 1)){
if(empty.sector == "topleft"){
eval(parse(text = paste0(diag.scan[1], " <- ", diag.scan[3])))
}else if(empty.sector == "topright"){
eval(parse(text = paste0(diag.scan[2], " <- ", diag.scan[4])))
}else if(empty.sector == "bottomright"){
eval(parse(text = paste0(diag.scan[3], " <- ", diag.scan[1])))
}else if(empty.sector == "bottomleft"){
eval(parse(text = paste0(diag.scan[4], " <- ", diag.scan[2])))
}
}
# end matrix filling
Gael  MILLOT's avatar
Gael MILLOT committed
2063
}
Gael  MILLOT's avatar
Gael MILLOT committed
2064
2065
2066
2067
2068
2069
2070
2071
if(warning.print == TRUE){
return(list(mat = mat, warnings = warning))
}else{
return(mat)
}
}


2072
######## fun_permut() #### progressively breaks a vector order
Gael  MILLOT's avatar
Gael MILLOT committed
2073
2074


2075
fun_permut <- function(data1, data2 = NULL, n = NULL, seed = 555, count.print = 10, text.print = "", cor.method = "spearman", cor.limit = 0.2, path.lib = NULL){
Gael  MILLOT's avatar
Gael MILLOT committed
2076
2077
2078
2079
2080
2081
2082
2083
2084
# AIM
# reorder the elements of the data1 vector by flipping 2 randomly selected consecutive positions either:
# 1) n times (when n is precised) or
# 2) until the correlation between data1 and data2 decreases down to the cor.limit (0.2 by default). See cor.limit below to deal with negative correlations
# Example of consecutive position flipping: ABCD -> BACD -> BADC, etc.
# ARGUMENTS
# data1: a vector of at least 2 elements. Must be numeric if data2 is specified
# data2: a numeric vector of same length as data1
# n: number of times "flipping 2 randomly selected consecutive positions". Ignored if data2 is specified
2085
2086
# seed: integer number used by set.seed(). Write NULL if random result is required, an integer otherwise. BEWARE: if not NULL, fun_permut() will systematically return the same result when the other parameters keep the same settings
# count.print: interger value. Print a working progress message every count.print during loops. BEWARE: can increase substentially the time to complete the process using a small value, like 10 for instance. Use Inf is no loop message desired
Gael  MILLOT's avatar
Gael MILLOT committed
2087
2088
# text.print: optional message to add to the working progress message every count.print loop
# cor.method: correlation method. Either "pearson", "kendall" or "spearman". Ignored if data2 is not specified
2089
# cor.limit: a correlation limit (between 0 and 1). Ignored if data2 is not specified. Compute the correlation between data1 and data2, permute the data1 values, and stop the permutation process when the correlation between data1 and data2 decreases down below the cor limit value (0.2 by default). If cor(data1, data2) is negative, then -cor.limit is used and the process stops until the correlation between data1 and data2 increases up over cor.limit (-0.2 by default). BEWARE: write a positive cor.limit even if cor(data1, data2) is known to be negative. The function will automatically uses -cor.limit. If the initial correlation is already below cor.limit (positive correlation) or over -cor.limit (negative correlation), then the data1 value positions are completely randomized (correlation between data1 and data2 is expected to be 0)
Gael  MILLOT's avatar
Gael MILLOT committed
2090
2091
2092
2093
# path.lib: absolute path of the required packages, if not in the default folders
# REQUIRED PACKAGES
# lubridate
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
Gael  MILLOT's avatar
Gael MILLOT committed
2094
2095
# fun_check()
# fun_pack()
Gael  MILLOT's avatar
Gael MILLOT committed
2096
2097
2098
2099
# RETURN
# a list containing:
# $data: the modified vector
# $warnings: potential warning messages (in case of negative correlation when data2 is specified)
2100
2101
# $cor: a spearman correlation between the initial positions (1:length(data1) and the final positions if data2 is not specified and the final correlation between data1 and data2 otherwise, according to cor.method
# $count: the number of loops used
Gael  MILLOT's avatar
Gael MILLOT committed
2102
# EXAMPLES
2103
2104
2105
2106
2107
2108
2109
# fun_permut(data1 = LETTERS[1:5], data2 = NULL, n = 20, seed = 1, count.print = 10, text.print = "", cor.method = "spearman", cor.limit = 0.2)
# fun_permut(data1 = 101:110, data2 = 21:30, n = 20, seed = 1, count.print = 10, text.print = "", cor.method = "spearman", cor.limit = 0.2)
# a way to use the cor.limit argument just considering data1
# obs1 <- 101:110 ; fun_permut(data1 = obs1, data2 = obs1, seed = 1, count.print = 10, cor.method = "spearman", cor.limit = 0.2)
# fun_permut(data1 = 1:1e3, data2 = 1e3:1, n = 20, seed = 1, count.print = 1e6, text.print = "", cor.method = "spearman", cor.limit = 0.7)
# fun_permut(data1 = 1:1e2, data2 = 1e2:1, seed = 1, count.print = 1e3, cor.limit = 0.5)

Gael  MILLOT's avatar
Gael MILLOT committed
2110
2111
2112
2113
# DEBUGGING
# data1 = LETTERS[1:5] ; data2 = NULL ; n = 10 ; seed = NULL ; count.print = 10 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.2 ; path.lib = NULL
# data1 = LETTERS[1:5] ; data2 = NULL ; n = 10 ; seed = 22 ; count.print = 10 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.2 ; path.lib = NULL
# data1 = 101:110 ; data2 = 21:30 ; n = 10 ; seed = 22 ; count.print = 10 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.2 ; path.lib = NULL
2114
# data1 = 1:1e3 ; data2 = 1e3:1 ; n = 20 ; seed = 22 ; count.print = 1e6 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.7 ; path.lib = NULL
Gael  MILLOT's avatar
Gael MILLOT committed
2115
2116
2117
2118
# function name
function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
# end function name
# required function checking
Gael  MILLOT's avatar
Gael MILLOT committed
2119
2120
if(length(find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2121
2122
stop(tempo.cat)
}
Gael  MILLOT's avatar
Gael MILLOT committed
2123
2124
if(length(find("fun_pack", mode = "function")) == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_pack() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2125
2126
2127
2128
2129
2130
2131
stop(tempo.cat)
}
# end required function checking
# argument checking
arg.check <- NULL # for function debbuging
checked.arg.names <- NULL # for function debbuging
ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
2132
2133
2134
2135
2136
tempo <- fun_check(data = data1, class = "vector", fun.name = function.name) ; eval(ee)
if(tempo$problem == FALSE & length(data1) < 2){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": data1 ARGUMENT MUST BE A VECTOR OF MINIMUM LENGTH 2. HERE IT IS: ", length(data1),"\n\n================\n\n")
stop(tempo.cat)
}
Gael  MILLOT's avatar
Gael MILLOT committed
2137
if( ! is.null(data2)){
Gael  MILLOT's avatar
Gael MILLOT committed
2138
tempo <- fun_check(data = data1, class = "vector", mode = "numeric", fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2139
2140
if(tempo$problem == TRUE){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": data1 MUST BE A NUMERIC VECTOR IF data2 ARGUMENT IS SPECIFIED\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2141
cat(tempo.cat)
Gael  MILLOT's avatar
Gael MILLOT committed
2142
arg.check <- c(arg.check, TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2143
}
Gael  MILLOT's avatar
Gael MILLOT committed
2144
tempo <- fun_check(data = data2, class = "vector", mode = "numeric", fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2145
2146
if(length(data1) != length(data2)){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": data1 AND data2 MUST BE VECTOR OF SAME LENGTH. HERE IT IS ", length(data1)," AND ", length(data2), "\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2147
cat(tempo.cat)
Gael  MILLOT's avatar
Gael MILLOT committed
2148
arg.check <- c(arg.check, TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2149
}
2150
2151
2152
2153
2154
2155
2156
}else if(is.null(n)){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": n ARGUMENT CANNOT BE NULL IF data2 ARGUMENT IS NULL\n\n================\n\n")
cat(tempo.cat)
arg.check <- c(arg.check, TRUE)
}
if( ! is.null(n)){
tempo <- fun_check(data = n, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2157
2158
}
if( ! is.null(seed)){
2159
tempo <- fun_check(data = seed, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2160
}
2161
tempo <- fun_check(data = count.print, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2162
2163
2164
tempo <- fun_check(data = text.print, class = "character", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = cor.method, options = c("pearson", "kendall", "spearman"), length =1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = cor.limit, class = "vector", mode = "numeric", prop = TRUE, length = 1, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2165
if( ! is.null(path.lib)){
Gael  MILLOT's avatar
Gael MILLOT committed
2166
tempo <- fun_check(data = path.lib, class = "character", fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2167
2168
2169
2170
2171
2172
if(tempo$problem == FALSE & ! all(dir.exists(path.lib))){
cat(paste0("\n\n============\n\nERROR IN ", function.name, ": \nDIRECTORY PATH INDICATED IN THE path.lib PARAMETER DOES NOT EXISTS: ", path.lib, "\n\n============\n\n"))
arg.check <- c(arg.check, TRUE)
}
}
if(any(arg.check) == TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
2173
stop() # nothing else because print = TRUE by default in fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2174
}
Gael  MILLOT's avatar
Gael MILLOT committed
2175
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2176
2177
# end argument checking
# package checking
Gael  MILLOT's avatar
Gael MILLOT committed
2178
fun_pack(req.package = "lubridate", path.lib = path.lib)
Gael  MILLOT's avatar
Gael MILLOT committed
2179
# end package checking
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
# local function
fun_loop <- function(round, count, tempo.pos, pos.seq.max, pos, data1, data2, cor.method, cor.ini, cor.limit, tempo.cor, tempo.time, tempo.lapse, final.loop, final.exp, BREAK){
loop1 <- trunc(count/(abs(cor.ini) - abs(tempo.cor)) * (abs(tempo.cor) - cor.limit)) # count/(abs(cor.ini) - abs(tempo.cor)) is the number of count per unit of corr. Tis is multiplied by the remaining distance to run ceiling to be over the number of approximate loops in order to reach the cor.limit value
if(is.na(loop1) | ! is.finite(loop1)){
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 1\n\n============\n\n"))
stop(tempo.cat)
}
if(loop1 > 1e9){
loop2 <- trunc(loop1 / 1e9) #
loop1 <- 1e9
}else{
loop2 <- 1
}
cat(paste0("\n\nFOR LOOP STEP | ROUND: ", round, " | LOOP1: ", format(loop1, big.mark=","), " | LOOP2: ", format(loop2, big.mark=","), " | TEMPO CORRELATION: ", tempo.cor, "\n"))
if(loop2 == 1 & loop1 < 100000){
BREAK <- TRUE
}else{
tempo.date.loop <- Sys.time()
tempo.time.loop <- as.numeric(tempo.date.loop)
total.loop <- loop1 * loop2
count3 <- 0
for(i3 in 1:loop2){
for(i4 in 1:loop1){
count[1] <- count + 1
count3[1] <- count3 + 1
pos[1] <- sample.int(n = pos.seq.max, size = 1, replace = FALSE) # selection of 1 position
tempo.pos[(pos + 1):pos] <- tempo.pos[pos:(pos + 1)]
if(count3 == tempo.count.print){
tempo.count.print[1] <- tempo.count.print + count.print
tempo.time[1] <- as.numeric(Sys.time())
tempo.lapse[1] <- round(lubridate::seconds_to_period(tempo.time - tempo.time.loop))
final.loop[1] <- (tempo.time - tempo.time.loop) / ((i3 - 1) * loop1 + i4) * total.loop # intra nb.compar loop lapse: time lapse / cycles done * cycles remaining
final.exp[1] <- as.POSIXct(final.loop, origin = tempo.date.loop)
cat(paste0("\nFOR LOOP | ROUND ", round, ifelse(text.print == "", "", paste0(" | ", text.print)), " | LOOP 1: ", format(i4, big.mark=","), " / ", format(loop1, big.mark=","), ifelse(loop2 == 1, "", paste0(" | LOOP 2: ", format(i3, big.mark=","), " / ", format(loop2, big.mark=","), " | TOTAL LOOP 1+2 ", format((i3 - 1) * loop1 + i4, big.mark=","), " / ", total.loop)), " | ", format(count, big.mark=","), " PERMUTATION IN data1 | TIME SPENT: ", tempo.lapse, " | EXPECTED END: ", final.exp))
}
}
}
}
return(list(tempo.pos = tempo.pos, count = count, BREAK = BREAK)) # BEWARE: respect the order 1) tempo.pos, 2) count, 3) BREAK
}
#end local function
Gael  MILLOT's avatar
Gael MILLOT committed
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
# main code
if( ! is.null(seed)){
# code that does not affect set.seed() in the global environment
# as soon as set.seed() or a random function, like runif() or sample(), is used, R creates the .Random.seed in the global environment, that will control the subsequent random operations (vector of number used by the random number generator). The .Random.seed object is systematically stored in the global environment, wherever the environment of set.seed() or runif() execution
# thanks to this code, when the function end, .Random.seed recovers the last vector of .Random.seed, whatever random execution performed by the function. Thus, if a set.seed() was performed in the global environment, the reproducibility of successive random operation in this environment will not be impaired
# Example:
## open a new R session. Then
## myfunction <- function (){if(exists(".Random.seed", envir = .GlobalEnv)){old <- .Random.seed ; on.exit(assign(".Random.seed", old, env = .GlobalEnv))} ; set.seed(2) ; runif(1)}
## set.seed(1) ; rnorm(1) ; rnorm(1) ; rnorm(1)
## rerun the same in a new session but without the previous line
## set.seed(1) ; rnorm(1) ; myfunction() ; rnorm(1) ; rnorm(1)
if(exists(".Random.seed", envir = .GlobalEnv)){ # .Random.seed does not exists, it means that no random operation has been performed yet in any R environment
tempo.random.seed <- .Random.seed
on.exit(assign(".Random.seed", tempo.random.seed, env = .GlobalEnv))
}else{
on.exit(set.seed(NULL)) # inactivate set.seed()
}
# end code that does not affect set.seed() in the global environment
set.seed(seed)
}
2241
ini.date <- Sys.time() # time of process begin, converted into seconds
Gael  MILLOT's avatar
Gael MILLOT committed
2242
2243
2244
ini.time <- as.numeric(ini.date) # time of process begin, converted into seconds
ini.pos <- 1:length(data1) # positions of data1 before permutation loops
tempo.pos <- ini.pos # positions of data1 that will be modified during loops
2245
2246
pos.seq <- ini.pos[-length(data1)] # selection of 1 position in initial position, without the last because always up permutation (pos -> pos+1 & pos+1 -> pos)
pos.seq.max <- length(pos.seq) # max position (used by sample.int() function)
Gael  MILLOT's avatar
Gael MILLOT committed
2247
2248
warnings <- NULL
# variable allocation before the loops to save time
2249
2250
2251
2252
tempo.time <- as.numeric(Sys.time())
tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time))
final.loop <- tempo.time
final.exp <- Sys.time()
Gael  MILLOT's avatar
Gael MILLOT committed
2253
2254
pos <- 0 # position randomly selected
tempo.count.print <- count.print # for the printing message
2255
2256
2257
2258
2259
2260
count <- 0
count2 <- 0
count4 <- 0
round <- 0
BREAK <- FALSE
tempo.res <- vector("list", 3)
Gael  MILLOT's avatar
Gael MILLOT committed
2261
2262
2263
2264
2265
2266
2267
2268
# end variable allocation before the loops to save time
if(is.null(data2)){
if(tempo.count.print > n){
tempo.count.print <- n
}
# pos.check <- NULL
for(i2 in 1:n){
count[1] <- count + 1
2269
pos[1] <- sample.int(n = pos.seq.max, size = 1, replace = FALSE) # random sample of a position to permute, sample.int samples in 1:pos.seq.max. Or sample(x = pos.seq, size = 1, replace = FALSE) but slower
Gael  MILLOT's avatar
Gael MILLOT committed
2270
2271
2272
tempo.pos[(pos + 1):pos] <- tempo.pos[pos:(pos + 1)]
if(count == tempo.count.print){
tempo.count.print[1] <- tempo.count.print + count.print
2273
2274
2275
tempo.time[1] <- as.numeric(Sys.time())
tempo.lapse[1] <- round(lubridate::seconds_to_period(tempo.time - ini.time))
cat(paste0("\nFOR LOOP ", i2, " / ", n, ifelse(text.print == "", "", paste0(" | ", text.print)), " | TIME SPENT: ", tempo.lapse))
Gael  MILLOT's avatar
Gael MILLOT committed
2276
2277
2278
}
# pos.check <- c(pos.check, pos)
}
2279
cat("\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2280
}else{
2281
2282
2283
cor.ini <- cor(x = data1, y = data2, use = "pairwise.complete.obs", method = cor.method)
tempo.cor <- cor.ini # correlation that will be modified during loops
neg.cor <- FALSE
Gael  MILLOT's avatar
Gael MILLOT committed
2284
if(tempo.cor < 0){
2285
tempo.warnings <- paste0("INITIAL ", toupper(cor.method), " CORRELATION BETWEEN data1 AND data2 HAS BEEN DETECTED AS NEGATIVE: ", tempo.cor, ". THE cor.limit PARAMETER WILL BE SWITCHED TO THE NEGATIVE EQUIVALENT: ", -cor.limit)
Gael  MILLOT's avatar
Gael MILLOT committed
2286
warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings) # in fact, abs(tempo.cor) is systematicallu used
2287
2288
neg.cor <- TRUE
tempo.cor <- abs(tempo.cor)
Gael  MILLOT's avatar
Gael MILLOT committed
2289
}
2290
if(tempo.cor < cor.limit){ # randomize directly all the position to be close to correlation zero
Gael  MILLOT's avatar
Gael MILLOT committed
2291
2292
2293
2294
for(i1 in 1:5){ # done 5 times to be sure of the complete randomness
tempo.pos <- sample(x = tempo.pos, size = length(tempo.pos), replace = FALSE)
}
}else{
2295
2296
2297
2298
2299
2300
2301
count[1] <- count + 1 # 1 and not 0 because already 1 performed just below
count2[1] <- 1 # 1 and not 0 because already 1 performed just below
pos[1] <- sample.int(n = pos.seq.max, size = 1, replace = FALSE) # selection of 1 position
tempo.pos[(pos + 1):pos] <- tempo.pos[pos:(pos + 1)]
tempo.cor[1] <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
cat("\nFIRST WHILE LOOP STEP\n")
while(tempo.cor == abs(cor.ini)){
Gael  MILLOT's avatar
Gael MILLOT committed
2302
count[1] <- count + 1
2303
2304
count2[1] <- count2 + 1
pos[1] <- sample.int(n = pos.seq.max, size = 1, replace = FALSE) # selection of 1 position
Gael  MILLOT's avatar
Gael MILLOT committed
2305
tempo.pos[(pos + 1):pos] <- tempo.pos[pos:(pos + 1)]
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
tempo.cor[1] <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
if(count2 == tempo.count.print){
tempo.count.print[1] <- tempo.count.print + count.print
tempo.time[1] <- as.numeric(Sys.time())
tempo.lapse[1] <- round(lubridate::seconds_to_period(tempo.time - ini.time))
cat(paste0("\nFIRST WHILE LOOP ", format(count2, big.mark=","), " / ? ", ifelse(text.print == "", "", paste0(" | ", text.print)), " | ", format(count, big.mark=","), " PERMUTATION IN data1 | CORRELATION LIMIT: ", cor.limit, " | TEMPO CORRELATION: ", round(tempo.cor, 3), " | TIME SPENT: ", tempo.lapse))
}
}
cat("\nFIRST WHILE LOOP END")
tempo.cor[1] <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
if(tempo.cor < cor.limit){
tempo.warnings <- paste0("THE FOR LOOP STEPS HAVE BEEN TOO FAR AND THE SECOND WHILE LOOP STEP HAS NOT BEEN USED")
warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings) # in fact, abs(tempo.cor) is systematicallu used
}
tempo.date.loop <- Sys.time()
tempo.time.loop <- as.numeric(tempo.date.loop)
tempo.cor.loop <- tempo.cor
while(tempo.cor > cor.limit & BREAK == FALSE){
round[1] <- round + 1
tempo.res[] <- fun_loop(round = round, count = count, tempo.pos = tempo.pos, pos.seq.max = pos.seq.max, pos = pos, data1 = data1, data2 = data2, cor.method = cor.method, cor.ini = cor.ini, cor.limit = cor.limit, tempo.cor = tempo.cor, tempo.time = tempo.time, tempo.lapse = tempo.lapse, final.loop = final.loop, final.exp = final.exp, BREAK = BREAK)
tempo.pos[] <- tempo.res[[1]]
count[1] <- tempo.res[[2]]
BREAK[1] <- tempo.res[[3]]
tempo.cor[1] <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
}
cat(paste0("\n\nFOR LOOP END | TEMPO CORRELATION: ", tempo.cor, "\n"))
tempo.cor[1] <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
tempo.date.loop <- Sys.time()
tempo.time.loop <- as.numeric(tempo.date.loop)
tempo.cor.loop <- tempo.cor
count4[1] <- 0
cat("\nSECOND WHILE LOOP STEP\n")
while(tempo.cor > cor.limit){
count[1] <- count + 1
count4[1] <- count4 + 1
pos[1] <- sample.int(n = pos.seq.max, size = 1, replace = FALSE) # selection of 1 position
tempo.pos[(pos + 1):pos] <- tempo.pos[pos:(pos + 1)]
tempo.cor[1] <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
if(count4 == tempo.count.print){
Gael  MILLOT's avatar
Gael MILLOT committed
2345
tempo.count.print[1] <- tempo.count.print + count.print
2346
2347
2348
2349
2350
tempo.time[1] <- as.numeric(Sys.time())
tempo.lapse[1] <- round(lubridate::seconds_to_period(tempo.time - ini.time))
final.loop[1] <- (tempo.time - tempo.time.loop) / (tempo.cor.loop - tempo.cor) * (tempo.cor - cor.limit) # tempo.cor.loop - tempo.cor always positive and tempo.cor decreases progressively starting from tempo.cor.loop
final.exp[1] <- as.POSIXct(final.loop, origin = tempo.date.loop)
cat(paste0("\nSECOND WHILE LOOP ", ifelse(text.print == "", "", paste0(" | ", text.print)), format(count4, big.mark=","), " / ? | ", format(count, big.mark=","), " PERMUTATION IN data1 | CORRELATION LIMIT: ", cor.limit, " | TEMPO CORRELATION: ", round(tempo.cor, 3), " | TIME SPENT: ", tempo.lapse, " | EXPECTED END: ", final.exp))
Gael  MILLOT's avatar
Gael MILLOT committed
2351
2352
}
}
2353
cat("\nSECOND WHILE LOOP END\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2354
2355
}
}
2356
output <- list(data = data1[tempo.pos], warnings = warnings, cor = ifelse(is.null(data2), cor(ini.pos, tempo.pos, method = "spearman"), ifelse(neg.cor == TRUE, -tempo.cor, tempo.cor)), count = count)
Gael  MILLOT's avatar
Gael MILLOT committed
2357
2358
2359
2360
2361
return(output)
}


################ Graphics management
Gael  MILLOT's avatar
Gael MILLOT committed
2362
2363
2364


# this order can be used:
Gael  MILLOT's avatar
Gael MILLOT committed
2365
2366
# fun_width()
# fun_open()
Gael  MILLOT's avatar
Gael MILLOT committed
2367
# fun_prior_plot() # not for ggplot2
Gael  MILLOT's avatar
Gael MILLOT committed
2368
# plot() or any other plotting
Gael  MILLOT's avatar
Gael MILLOT committed
2369
# fun_post_plot() if fun_prior_plot() has been used # not for ggplot2
Gael  MILLOT's avatar
Gael MILLOT committed
2370
# fun_close()
Gael  MILLOT's avatar
Gael MILLOT committed
2371
2372


Gael  MILLOT's avatar
Gael MILLOT committed
2373
######## fun_width() #### window width depending on classes to plot
Gael  MILLOT's avatar
Gael MILLOT committed
2374
2375
2376


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2377
fun_width <- function(class.nb, inches.per.class.nb = 1, ini.window.width = 7, inch.left.space, inch.right.space, boundarie.space = 0.5){
Gael  MILLOT's avatar
Gael MILLOT committed
2378
2379
2380
2381
# AIM
# rescale the width of a window to open depending on the number of classes to plot
# can be used for height, considering that it is as if it was a width
# this order can be used:
Gael  MILLOT's avatar
Gael MILLOT committed
2382
2383
# fun_width()
# fun_open()
Gael  MILLOT's avatar
Gael MILLOT committed
2384
2385
2386
# fun_prior_plot() # not for ggplot2
# plot() or any other plotting
# fun_post_plot() if fun_prior_plot() has been used # not for ggplot2
Gael  MILLOT's avatar
Gael MILLOT committed
2387
# fun_close()
Gael  MILLOT's avatar
Gael MILLOT committed
2388
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
Gael  MILLOT's avatar
Gael MILLOT committed
2389
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
# ARGUMENTS
# class.nb: number of class to plot
# inches.per.class.nb: number of inches per unit of class.nb. 2 means 2 inches for each boxplot for instance
# ini.window.width:initial window width in inches
# inch.left.space: left horizontal margin of the figure region (in inches)
# inch.right.space: right horizontal margin of the figure region (in inches)
# boundarie.space: space between the right and left limits of the plotting region and the plot (0.5 means half a class width)
# RETURN
# the new window width in inches
# EXAMPLES
Gael  MILLOT's avatar
Gael MILLOT committed
2400
# fun_width(class.nb = 10, inches.per.class.nb = 0.2, ini.window.width = 7, inch.left.space = 1, inch.right.space = 1, boundarie.space = 0.5)
Gael  MILLOT's avatar
Gael MILLOT committed
2401
2402
2403
2404
2405
2406
# DEBUGGING
# class.nb = 10 ; inches.per.class.nb = 0.2 ; ini.window.width = 7 ; inch.left.space = 1 ; inch.right.space = 1 ; boundarie.space = 0.5 # for function debugging
# function name
function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
# end function name
# required function checking
Gael  MILLOT's avatar
Gael MILLOT committed
2407
2408
if(length(find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2409
2410
2411
2412
2413
2414
2415
stop(tempo.cat)
}
# end required function checking
# argument checking
arg.check <- NULL # for function debbuging
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
Gael  MILLOT's avatar
Gael MILLOT committed
2416
2417
2418
2419
2420
2421
tempo <- fun_check(data = class.nb, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = inches.per.class.nb, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = ini.window.width, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = inch.left.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = inch.right.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = boundarie.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2422
if(any(arg.check) == TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
2423
stop() # nothing else because print = TRUE by default in fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2424
}
Gael  MILLOT's avatar
Gael MILLOT committed
2425
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2426
2427
2428
2429
2430
2431
# end argument checking
# main code
range.max <- class.nb + boundarie.space # the max range of the future plot
range.min <- boundarie.space # the min range of the future plot
window.width <- inch.left.space + inch.right.space + inches.per.class.nb * (range.max - range.min)
return(window.width)
Gael  MILLOT's avatar
Gael MILLOT committed
2432
2433
2434
}


Gael  MILLOT's avatar
Gael MILLOT committed
2435
######## fun_open() #### open a GUI or pdf graphic window
Gael  MILLOT's avatar
Gael MILLOT committed
2436
2437
2438


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2439
fun_open <- function(pdf.disp = TRUE, path.fun = "working.dir", pdf.name.file = "graph", width.fun = 7, height.fun = 7, paper = "special", no.pdf.overwrite = TRUE, return.output = FALSE){
Gael  MILLOT's avatar
Gael MILLOT committed
2440
2441
2442
2443
# AIM
# open a pdf or screen (GUI) graphic window
# BEWARE: on Linux, use pdf.disp = TRUE, if (GUI) graphic window is not always available, meaning that X is not installed (clusters for instance). Use X11() in R to test if available
# this order can be used:
Gael  MILLOT's avatar
Gael MILLOT committed
2444
2445
# fun_width()
# fun_open()
Gael  MILLOT's avatar
Gael MILLOT committed
2446
2447
2448
# fun_prior_plot() # not for ggplot2
# plot() or any other plotting
# fun_post_plot() if fun_prior_plot() has been used # not for ggplot2
Gael  MILLOT's avatar
Gael MILLOT committed
2449
# fun_close()
Gael  MILLOT's avatar
Gael MILLOT committed
2450
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
Gael  MILLOT's avatar
Gael MILLOT committed
2451
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
# ARGUMENTS:
# pdf.disp: use pdf or not
# path.fun: where the pdf is saved. Write "working.dir" if working directory is required (default)
# pdf.name.file: name of the pdf file containing the graphs (the .pdf extension is added by the function)
# width.fun: width of the windows (in inches)
# height.fun: height of the windows (in inches)
# paper: paper argument of the pdf function (paper format). Only used for pdf(). Either "a4", "letter", "legal", "us", "executive", "a4r", "USr" or "special". If "special", means that width.fun and height.fun specify the paper size
# no.pdf.overwrite: existing pdf can be overwritten ? Only used if pdf.disp = TRUE
# return.output: return output ? If TRUE but function not assigned, the output list is displayed
# RETURN
# a list containing:
# $pdf.loc: path of the pdf created
# $ini.par: initial par() parameters (to reset in a new graph)
# $zone.ini: initial window spliting (to reset in a new graph)
# EXAMPLES
Gael  MILLOT's avatar
Gael MILLOT committed
2467
# fun_open(pdf.disp = FALSE, path.fun = "C:/Users/Gael/Desktop", pdf.name.file = "graph", width.fun = 7, height.fun = 7, paper = "special", no.pdf.overwrite = TRUE, return.output = TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2468
2469
2470
2471
2472
2473
2474
# DEBUGGING
# pdf.disp = TRUE ; path.fun = "C:/Users/Gael/Desktop" ; pdf.name.file = "graphs" ; width.fun = 7 ; height.fun = 7 ; paper = "special" ; no.pdf.overwrite = TRUE ; return.output = TRUE # for function debugging
# pdf.disp = TRUE ; path.fun = "/pasteur/homes/gmillot/" ; pdf.name.file = "graphs" ; width.fun = 7 ; height.fun = 7 ; paper = "special" ; no.pdf.overwrite = TRUE ; return.output = TRUE # for function debugging
# function name
function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
# end function name
# required function checking
Gael  MILLOT's avatar
Gael MILLOT committed
2475
2476
if(length(find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2477
2478
2479
2480
2481
2482
2483
stop(tempo.cat)
}
# end required function checking
# argument checking
arg.check <- NULL # for function debbuging
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
Gael  MILLOT's avatar
Gael MILLOT committed
2484
2485
2486
2487
2488
2489
2490
2491
2492
tempo <- fun_check(data = pdf.disp, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = path.fun, class = "character", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = pdf.name.file, class = "character", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = width.fun, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = height.fun, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = path.fun, class = "character", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = paper, options = c("a4", "letter", "legal", "us", "executive", "a4r", "USr", "special", "A4", "LETTER", "LEGAL", "US"), length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data =no.pdf.overwrite, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = return.output, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2493
if(any(arg.check) == TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
2494
stop() # nothing else because print = TRUE by default in fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2495
}
Gael  MILLOT's avatar
Gael MILLOT committed
2496
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
# end argument checking
# main code
if(path.fun == "working.dir"){
path.fun <- getwd()
}else{
if(grepl(x = path.fun, pattern = ".+/$")){
path.fun <- substr(path.fun, 1, nchar(path.fun) - 1) # remove the last /
}
if(dir.exists(path.fun) == FALSE){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": path.fun ARGUMENT DOES NOT CORRESPOND TO EXISTING DIRECTORY\n\n================\n\n")
stop(tempo.cat)
}
}
if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
open.fail <- NULL
windows()
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
invisible(dev.off()) # close the new window
}else if(Sys.info()["sysname"] == "Linux"){
if(pdf.disp == TRUE){
if(file.exists(paste0(path.fun, "/recover_ini_par.pdf"))){
Gael  MILLOT's avatar
Gael MILLOT committed
2518
tempo.cat <- paste0("\n\n================\n\nPROBLEM IN fun_open(): THIS FUNCTION CANNOT BE USED ON LINUX IF A recover_ini_par.pdf FILE ALREADY EXISTS HERE: ", paste(path.fun, collapse = " "), "\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
stop(tempo.cat)
}else{
pdf(width = width.fun, height = height.fun, file=paste0(path.fun, "/recover_ini_par.pdf"), paper = paper)
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
invisible(dev.off()) # close the pdf windows
file.remove(paste0(path.fun, "/recover_ini_par.pdf")) # remove the pdf file
}
}else{
# test if X11 can be opened
if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THIS FUNCTION CANNOT BE USED ON LINUX IF A Rplots.pdf FILE ALREADY EXISTS HERE: ", getwd(), "\n\n================\n\n")
stop(tempo.cat)
}else{
open.fail <- suppressWarnings(try(X11(), silent = TRUE))[] # try to open a X11 window. If open.fail == NULL, no problem, meaning that the X11 window is opened. If open.fail != NULL, a pdf can be opened here paste0(getwd(), "/Rplots.pdf")
if(is.null(open.fail)){
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
invisible(dev.off()) # close the new window
}else if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
file.remove(paste0(getwd(), "/Rplots.pdf")) # remove the pdf file
Gael  MILLOT's avatar
Gael MILLOT committed
2538
tempo.cat <- ("\n\n================\n\nPROBLEM IN fun_open(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE SET pdf.disp ARGUMENT TO TRUE AND RERUN\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
stop(tempo.cat)
}
}
}
}else{
open.fail <- NULL
quartz()
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
invisible(dev.off()) # close the new window
}
zone.ini <- matrix(1, ncol=1) # to recover the initial parameters for next figure region when device region split into several figure regions
if(pdf.disp == TRUE){
pdf.loc <- paste0(path.fun, "/", pdf.name.file, ".pdf")
if(file.exists(pdf.loc) == TRUE & no.pdf.overwrite == TRUE){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": pdf.loc FILE ALREADY EXISTS AND CANNOT BE OVERWRITTEN DUE TO no.pdf.overwrite ARGUMENT SET TO TRUE: ", pdf.loc, "\n\n================\n\n")
stop(tempo.cat)
}else{
pdf(width = width.fun, height = height.fun, file=pdf.loc, paper = paper)
}
}else if(pdf.disp == FALSE){
pdf.loc <- NULL
if(Sys.info()["sysname"] == "Windows"){ # .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
windows(width = width.fun, height = height.fun, rescale="fixed")
}else if(Sys.info()["sysname"] == "Linux"){
if( ! is.null(open.fail)){
Gael  MILLOT's avatar
Gael MILLOT committed
2564
stop("\n\n================\n\nPROBLEM IN fun_open(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE SET pdf.disp ARGUMENT TO TRUE AND RERUN\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
}else{
X11(width = width.fun, height = height.fun)
}
}else{
quartz(width = width.fun, height = height.fun)
}
}
if(return.output == TRUE){
output <- list(pdf.loc = pdf.loc, ini.par = ini.par, zone.ini = zone.ini)
return(output)
}
}


2579
######## fun_prior_plot() #### set graph param before plotting (erase axes for instance)
Gael  MILLOT's avatar
Gael MILLOT committed
2580
2581
2582


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2583
2584
2585
2586
2587
2588
fun_prior_plot <- function(param.reinitial = FALSE, xlog.scale = FALSE, ylog.scale = FALSE, remove.label = TRUE, remove.x.axis = TRUE, remove.y.axis = TRUE, std.x.range = TRUE, std.y.range = TRUE, down.space = 1, left.space = 1, up.space = 1, right.space = 1, orient = 1, dist.legend = 3.5, tick.length = 0.5, box.type = "n", amplif.label = 1, amplif.axis = 1, display.extend = FALSE, return.par = FALSE){
# AIM
# very convenient to erase the axes for post plot axis redrawing using fun_post_plot()
# reinitialize and set the graphic parameters before plotting
# CANNOT be used if no graphic device already opened
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
Gael  MILLOT's avatar
Gael MILLOT committed
2589
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
# ARGUMENTS
# param.reinitial: reinitialize graphic parameters before applying the new ones, as defined by the other arguments? Either TRUE or FALSE
# xlog.scale: Log scale for the x-axis? Either TRUE or FALSE. If TRUE, erases the x-axis, except legend, for further drawing by fun_post_plot()(xlog argument of par())
# ylog.scale: Log scale for the y-axis? Either TRUE or FALSE. If TRUE, erases the y-axis, except legend, for further drawing by fun_post_plot()(ylog argument of par())
# remove.label: remove labels (axis legend) of the two axes? Either TRUE or FALSE (ann argument of par())
# remove.x.axis: remove x-axis except legend? Either TRUE or FALSE (control the xaxt argument of par()). Automately set to TRUE if xlog.scale == TRUE
# remove.y.axis: remove y-axis except legend? Either TRUE or FALSE (control the yaxt argument of par()). Automately set to TRUE if ylog.scale == TRUE
# std.x.range: standard range on the x-axis? TRUE (no range extend) or FALSE (4% range extend). Controls xaxs argument of par() (TRUE is xaxs = "i", FALSE is xaxs = "r")
# std.y.range: standard range on the y-axis? TRUE (no range extend) or FALSE (4% range extend). Controls yaxs argument of par() (TRUE is yaxs = "i", FALSE is yaxs = "r")
# down.space: lower vertical margin (in inches, mai argument of par())
# left.space: left horizontal margin (in inches, mai argument of par())
# up.space: upper vertical margin between plot region and grapical window (in inches, mai argument of par())
# right.space: right horizontal margin (in inches, mai argument of par())
# orient: scale number orientation (las argument of par()). 0, always parallel to the axis; 1, always horizontal; 2, always perpendicular to the axis; 3, always vertical
# dist.legend: numeric value that moves axis legends away in inches (first number of mgp argument of par() but in inches thus / 0.2)
# tick.length: length of the ticks (1 means complete the distance between the plot region and the axis numbers, 0.5 means half the length, etc. 0 means no tick
# box.type: bty argument of par(). Either "o", "l", "7", "c", "u", "]", the resulting box resembles the corresponding upper case letter. A value of "n" suppresses the box
# amplif.label: increase or decrease the size of the text in legends
# amplif.axis: increase or decrease the size of the scale numbers in axis
# display.extend: extend display beyond plotting region? Either TRUE or FALSE (xpd argument of par() without NA)
# return.par: return graphic parameter modification?
# RETURN
# return graphic parameter modification
# EXAMPLES
# fun_prior_plot(param.reinitial = FALSE, xlog.scale = FALSE, ylog.scale = FALSE, remove.label = TRUE, remove.x.axis = TRUE, remove.y.axis = TRUE, std.x.range = TRUE, std.y.range = TRUE, down.space = 1, left.space = 1, up.space = 1, right.space = 1, orient = 1, dist.legend = 4.5, tick.length = 0.5, box.type = "n", amplif.label = 1, amplif.axis = 1, display.extend = FALSE, return.par = FALSE)
# DEBUGGING
# param.reinitial = FALSE ; xlog.scale = FALSE ; ylog.scale = FALSE ; remove.label = TRUE ; remove.x.axis = TRUE ; remove.y.axis = TRUE ; std.x.range = TRUE ; std.y.range = TRUE ; down.space = 1 ; left.space = 1 ; up.space = 1 ; right.space = 1 ; orient = 1 ; dist.legend = 4.5 ; tick.length = 0.5 ; box.type = "n" ; amplif.label = 1 ; amplif.axis = 1 ; display.extend = FALSE ; return.par = FALSE # for function debugging
# function name
function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
# end function name
# required function checking
Gael  MILLOT's avatar
Gael MILLOT committed
2621
2622
if(length(find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2623
2624
2625
2626
2627
2628
2629
stop(tempo.cat)
}
# end required function checking
# argument checking
arg.check <- NULL # for function debbuging
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
Gael  MILLOT's avatar
Gael MILLOT committed
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
tempo <- fun_check(data = param.reinitial, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = xlog.scale, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = ylog.scale, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = remove.label, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = remove.x.axis, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = remove.y.axis, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = std.x.range, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = std.y.range, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = down.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = left.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = up.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = right.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = orient, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = dist.legend, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = tick.length, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = box.type, options = c("o", "l", "7", "c", "u", "]", "n"), length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = amplif.label, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = amplif.axis, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = display.extend, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = return.par, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2650
if(any(arg.check) == TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
2651
stop() # nothing else because print = TRUE by default in fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2652
}
Gael  MILLOT's avatar
Gael MILLOT committed
2653
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
# end argument checking
# main code
if(is.null(dev.list())){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THIS FUNCTION CANNOT BE USED IF NO GRAPHIC DEVICE ALREADY OPENED (dev.list() IS CURRENTLY NULL)\n\n================\n\n")
stop(tempo.cat)
}
if(param.reinitial == TRUE){
if( ! all(names(dev.cur()) == "null device")){
active.wind.nb <- dev.cur()
}else{
active.wind.nb <- 0
}
if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
windows()
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
invisible(dev.off()) # close the new window
}else if(Sys.info()["sysname"] == "Linux"){
if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THIS FUNCTION CANNOT BE USED ON LINUX WITH param.reinitial SET TO TRUE IF A Rplots.pdf FILE ALREADY EXISTS HERE: ", getwd(), "\n\n================\n\n")
stop(tempo.cat)
}else{
open.fail <- suppressWarnings(try(X11(), silent = TRUE))[] # try to open a X11 window. If open.fail == NULL, no problem, meaning that the X11 window is opened. If open.fail != NULL, a pdf can be opened here paste0(getwd(), "/Rplots.pdf")
if(is.null(open.fail)){
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
invisible(dev.off()) # close the new window
}else if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
invisible(dev.off()) # close the new window
file.remove(paste0(getwd(), "/Rplots.pdf")) # remove the pdf file
}else{
tempo.cat <- ("\n\n================\n\nPROBLEM IN fun_prior_plot(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE USE PDF GRAPHIC INTERFACES AND RERUN\n\n================\n\n")
stop(tempo.cat)
}
}
}else{ # macOS
quartz()
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened)
invisible(dev.off()) # close the new window
}
if( ! all(names(dev.cur()) == "null device")){
dev.set(active.wind.nb) # go back to the active windows if exists
par(ini.par) # apply the initial par to current window
}
}
if(remove.x.axis == TRUE){
par(xaxt = "n") # suppress the y-axis label
}else{
par(xaxt = "s")
}
if(remove.y.axis == TRUE){
par(yaxt = "n") # suppress the y-axis label
}else{
par(yaxt = "s")
}
if(std.x.range == TRUE){
par(xaxs = "i")
}else{
par(xaxs = "r")
}
if(std.y.range == TRUE){
par(yaxs = "i")
}else{
par(yaxs = "r")
}
par(mai = c(down.space, left.space, up.space, right.space), ann = ! remove.label, las = orient, mgp = c(dist.legend/0.2, 1, 0), xpd = display.extend, bty= box.type, cex.lab = amplif.label, cex.axis = amplif.axis)
par(tcl = -par()$mgp[2] * tick.length) # tcl gives the length of the ticks as proportion of line text, knowing that mgp is in text lines. So the main ticks are a 0.5 of the distance of the axis numbers by default. The sign provides the side of the tick (negative for outside of the plot region)
if(xlog.scale == TRUE){
par(xaxt = "n", xlog = TRUE) # suppress the x-axis label
}else{
par(xlog = FALSE)
}
if(ylog.scale == TRUE){
par(yaxt = "n", ylog = TRUE) # suppress the y-axis label
}else{
par(ylog = FALSE)
}
if(return.par == TRUE){
tempo.par <- par()
return(tempo.par)
}
}


Gael  MILLOT's avatar
Gael MILLOT committed
2737
2738
2739
2740
######## fun_scale() #### select nice label numbers when setting number of ticks on an axis


 
Gael  MILLOT's avatar
Gael MILLOT committed
2741
2742
2743


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2744
fun_scale <- function(n, lim, kind = "approx", log = "no", path.lib = NULL){
Gael  MILLOT's avatar
Gael MILLOT committed
2745
# AIM
Gael  MILLOT's avatar
Gael MILLOT committed
2746
# attempt to select nice scale numbers when setting n ticks on a lim axis range
Gael  MILLOT's avatar
Gael MILLOT committed
2747
# ARGUMENTS
Gael  MILLOT's avatar
Gael MILLOT committed
2748
2749
2750
2751
2752
2753
2754
2755
2756
# n: desired number of ticks on the axis (integer more than 0)
# lim: vector of 2 numbers indicating the limit range of the axis. Order of the 2 values matters (for inverted axis)
# kind: either "approx" (approximative), "strict" (strict) or "strict.cl" (strict clean). If "approx", use the scales::trans_breaks() function to provide an easy to read scale of approximately n ticks spanning the range of the lim argument. If "strict", cut the range of the lim argument into n + 1 equidistant part and return the n numbers at each boundary. This often generates numbers uneasy to read. If "strict.cl", provide an easy to read scale of exactly n ticks, but sometimes not completely spanning the range of the lim argument. Automatically set to "approx" if the log argument is other than no
# log: either "no" (values of the lim argument are not log), "log2" (values of the lim argument are log2 transformed) or "log10" (values of the lim argument are log10 transformed). If other than "no" (log scale), the kind argument is automatically set to "approx"
# path.lib: absolute path of the required packages, if not in the default folders
# REQUIRED PACKAGES
# if kind = "approx":
# ggplot2
# scales
Gael  MILLOT's avatar
Gael MILLOT committed
2757
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
Gael  MILLOT's avatar
Gael MILLOT committed
2758
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2759
# fun_round()
Gael  MILLOT's avatar
Gael MILLOT committed
2760
2761
2762
# RETURN
# a vector of numbers
# EXAMPLES
Gael  MILLOT's avatar
Gael MILLOT committed
2763
# ymin = 2; ymax = 3.101; n = 10; scale <- fun_scale(n = n, lim = c(ymin, ymax), kind = "approx", log = "no") ; scale ; par(yaxt = "n", yaxs = "i", las = 1) ; plot(ymin:ymax, ymin:ymax, xlim = range(scale, ymin, ymax)[order(c(ymin, ymax))], ylim = range(scale, ymin, ymax)[order(c(ymin, ymax))], xlab = "DEFAULT SCALE", ylab = "NEW SCALE") ; par(yaxt = "s") ; axis(side = 2, at = scale)
Gael  MILLOT's avatar
Gael MILLOT committed
2764
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
2765
2766
# n = 9 ; lim = c(2, 3.101) ; kind = "approx" ; log = "no" ; path.lib = NULL # for function debugging
# n = 10 ; lim = c(25, -15) ; kind = "approx" ; log = "no" ; path.lib = NULL # for function debugging
Gael  MILLOT's avatar
Gael MILLOT committed
2767
2768
2769
# function name
function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
# end function name
Gael  MILLOT's avatar
Gael MILLOT committed
2770
# end initial argument checking
Gael  MILLOT's avatar
Gael MILLOT committed
2771
# required function checking
Gael  MILLOT's avatar
Gael MILLOT committed
2772
2773
if(length(find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2774
2775
2776
2777
2778
2779
2780
stop(tempo.cat)
}
# end required function checking
# argument checking
arg.check <- NULL # for function debbuging
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
Gael  MILLOT's avatar
Gael MILLOT committed
2781
tempo <- fun_check(data = n, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2782
2783
2784
2785
2786
if(tempo$problem == FALSE & n == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": n ARGUMENT MUST BE A NON NULL AND POSITIVE INTEGER\n\n================\n\n")
cat(tempo.cat)
arg.check <- c(arg.check, TRUE) # 
}
Gael  MILLOT's avatar
Gael MILLOT committed
2787
tempo <- fun_check(data = lim, class = "vector", mode = "numeric", length = 2, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2788
2789
2790
2791
2792
if(tempo$problem == FALSE & diff(lim) == 0){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": lim ARGUMENT HAS A NULL RANGE (2 IDENTICAL VALUES)\n\n================\n\n")
cat(tempo.cat)
arg.check <- c(arg.check, TRUE)
}else if(tempo$problem == FALSE & any(lim %in% c(Inf, -Inf))){
Gael  MILLOT's avatar
Gael MILLOT committed
2793
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": lim ARGUMENT CANNOT CONTAIN -Inf OR Inf VALUES\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
2794
cat(tempo.cat)
Gael  MILLOT's avatar
Gael MILLOT committed
2795
2796
arg.check <- c(arg.check, TRUE)
}
Gael  MILLOT's avatar
Gael MILLOT committed
2797
2798
tempo <- fun_check(data = kind, options = c("approx", "strict", "strict.cl"), length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = log, options = c("no", "log2", "log10"), length = 1, fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2799
2800
2801
if(tempo$problem == FALSE & log != "no" & any(lim < 0)){
tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": FINAL lim RANGE SPAN NULL OR NEGATIVE VALUES:", paste(lim, collapse = " "), "\nWHICH IS IMCOMPATIBLE WITH log PARAMETER SET TO log10 OR log2\n\n================\n\n")
cat(tempo.cat)
Gael  MILLOT's avatar
Gael MILLOT committed
2802
arg.check <- c(arg.check, TRUE) # 
Gael  MILLOT's avatar
Gael MILLOT committed
2803
}
Gael  MILLOT's avatar
Gael MILLOT committed
2804
if( ! is.null(path.lib)){
Gael  MILLOT's avatar
Gael MILLOT committed
2805
tempo <- fun_check(data = path.lib, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
2806
2807
2808
2809
2810
if(tempo$problem == FALSE & ! all(dir.exists(path.lib))){
cat(paste0("\n\n============\n\nERROR IN ", function.name, ": \nDIRECTORY PATH INDICATED IN THE path.lib PARAMETER DOES NOT EXISTS: ", path.lib, "\n\n============\n\n"))
arg.check <- c(arg.check, TRUE)
}
}
Gael  MILLOT's avatar
Gael MILLOT committed
2811
if(any(arg.check) == TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
2812
stop() # nothing else because print = TRUE by default in fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2813
}
Gael  MILLOT's avatar
Gael MILLOT committed
2814
2815
# end argument checking with fun_check()
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2816
2817
# end argument checking
# main code
Gael  MILLOT's avatar
Gael MILLOT committed
2818
2819
2820
2821
2822
2823
2824
lim.order <- order(lim) # to deal with inverted axis
lim <- sort(lim)
if(log != "no"){
kind <- "approx"
}
if(kind == "approx"){
# package checking
Gael  MILLOT's avatar
Gael MILLOT committed
2825
2826
fun_pack(req.package = c("ggplot2"), path.lib = path.lib)
fun_pack(req.package = c("scales"), path.lib = path.lib)
Gael  MILLOT's avatar
Gael MILLOT committed
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
# end package checking
output <- ggplot2::ggplot_build(ggplot2::ggplot() + ggplot2::scale_y_continuous(
breaks = scales::trans_breaks(
trans = if(log == "no"){"identity"}else if(log == "log10"){"log10"}else if(log == "log2"){"log2"}, 
inv = if(log == "no"){"identity"}else if(log == "log10"){function(x){10^x}}else if(log == "log2"){function(x){2^x}}, 
n = n
), 
limits = lim
))$layout$panel_params[[1]]$y.major_source # pretty() alone is not appropriate: tempo.pret <-  pretty(seq(lim[1] ,lim[2], length.out = n)) ; tempo.pret[tempo.pret > = lim[1] & tempo.pret < = lim[2]]
}else if(kind == "strict"){
output <- fun_round(seq(lim[1] ,lim[2], length.out = n), 2)
}else if(kind == "strict.cl"){
Gael  MILLOT's avatar
Gael MILLOT committed
2839
2840
2841
tempo.range <- diff(sort(lim))
tempo.max <- max(lim)
tempo.min <- min(lim)
Gael  MILLOT's avatar
Gael MILLOT committed
2842
mid <- tempo.min + (tempo.range/2) # middle of axis
Gael  MILLOT's avatar
Gael MILLOT committed
2843
tempo.inter <- tempo.range / (n + 1) # current interval between two ticks, between 0 and Inf
Gael  MILLOT's avatar
Gael MILLOT committed
2844
2845
2846
2847
if(tempo.inter == 0){
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": THE INTERVAL BETWEEN TWO TICKS OF THE SCALE IS NULL. MODIFY THE lim OR n ARGUMENT\n\n============\n\n"))
stop(tempo.cat)
}
Gael  MILLOT's avatar
Gael MILLOT committed
2848
2849
2850
log10.abs.lim <- 200
log10.range <- (-log10.abs.lim):log10.abs.lim
log10.vec <- 10^log10.range
Gael  MILLOT's avatar
Gael MILLOT committed
2851
round.vec <- c(5, 4, 3, 2.5, 2, 1.25, 1)
Gael  MILLOT's avatar
Gael MILLOT committed
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
dec.table <- outer(log10.vec, round.vec) # table containing the scale units (row: power of ten from -201 to +199, column: the 5, 2.5, 2, 1.25, 1 notches

 

# recover the number of leading zeros in tempo.inter
ini.scipen <- options()$scipen
options(scipen = -1000) # force scientific format
if(any(grepl(pattern = "\\+", x = tempo.inter))){ # tempo.inter > 1
power10.exp <- as.integer(substring(text = tempo.inter, first = (regexpr(pattern = "\\+", text = tempo.inter) + 1))) # recover the power of 10. Example recover 08 from 1e+08
mantisse <- as.numeric(substr(x = tempo.inter, start = 1, stop = (regexpr(pattern = "\\+", text = tempo.inter) - 2))) # recover the mantisse. Example recover 1.22 from 1.22e+08
}else if(any(grepl(pattern = "\\-", x = tempo.inter))){ # tempo.inter < 1
Gael  MILLOT's avatar
Gael MILLOT committed
2863
power10.exp <- as.integer(substring(text = tempo.inter, first = (regexpr(pattern = "\\-", text = tempo.inter)))) # recover the power of 10. Example recover 08 from 1e+08
Gael  MILLOT's avatar
Gael MILLOT committed
2864
2865
mantisse <- as.numeric(substr(x = tempo.inter, start = 1, stop = (regexpr(pattern = "\\-", text = tempo.inter) - 2))) # recover the mantisse. Example recover 1.22 from 1.22e+08
}else{
Gael  MILLOT's avatar
Gael MILLOT committed
2866
2867
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 1\n\n============\n\n"))
stop(tempo.cat)
Gael  MILLOT's avatar
Gael MILLOT committed
2868
2869
}
tempo.scale <- dec.table[log10.range == power10.exp, ]
Gael  MILLOT's avatar
Gael MILLOT committed
2870
2871
# new interval 
inter.select <- NULL
Gael  MILLOT's avatar
Gael MILLOT committed
2872
for(i1 in 1:length(tempo.scale)){
Gael  MILLOT's avatar
Gael MILLOT committed
2873
2874
2875
2876
tempo.first.tick <- trunc((tempo.min + tempo.scale[i1]) / tempo.scale[i1]) * (tempo.scale[i1]) # this would be use to have a number not multiple of tempo.scale[i1]: ceiling(tempo.min) + tempo.scale[i1] * 10^power10.exp
tempo.last.tick <- tempo.first.tick + tempo.scale[i1] * (n - 1)
if((tempo.first.tick >= tempo.min) & (tempo.last.tick <= tempo.max)){
inter.select <- tempo.scale[i1]
Gael  MILLOT's avatar
Gael MILLOT committed
2877
2878
2879
break()
}
}
Gael  MILLOT's avatar
Gael MILLOT committed
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
if(is.null(inter.select)){
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 2\n\n============\n\n"))
stop(tempo.cat)
}
options(scipen = ini.scipen) # restore the initial scientific penalty
# end new interval 
# centering the new scale 
tempo.mid <- trunc((mid + (-1:1) * inter.select) / inter.select) * inter.select # tempo middle tick closest to the middle axis
mid.tick <- tempo.mid[which.min(abs(tempo.mid - mid))]
if(n == 1){
output <- mid.tick
}else if(n == 2){
tempo.min.dist <- mid.tick - inter.select - tempo.min
tempo.max.dist <- tempo.max - mid.tick + inter.select
if(tempo.min.dist <= tempo.max.dist){ # distance between lowest tick and bottom axis <= distance between highest tick and top axis. If yes, extra tick but at the top, otherwise at the bottom
output <- c(mid.tick, mid.tick + inter.select)
}else{
output <- c(mid.tick - inter.select, mid.tick)
}
}else if((n / 2 - trunc(n / 2)) > 0.1){ # > 0.1 to avoid floating point. Because result can only be 0 or 0.5. Thus, > 0.1 means odd number
output <- c(mid.tick - (trunc(n / 2):1) * inter.select, mid.tick, mid.tick + (1:trunc(n / 2)) * inter.select)
}else if((n / 2 - trunc(n / 2)) < 0.1){ # < 0.1 to avoid floating point. Because result can only be 0 or 0.5. Thus, < 0.1 means even number
tempo.min.dist <- mid.tick - trunc(n / 2) * inter.select - tempo.min
tempo.max.dist <- tempo.max - mid.tick + trunc(n / 2) * inter.select
if(tempo.min.dist <= tempo.max.dist){ # distance between lowest tick and bottom axis <= distance between highest tick and top axis. If yes, extra tick but at the bottom, otherwise at the top
output <- c(mid.tick - ((trunc(n / 2) - 1):1) * inter.select, mid.tick, mid.tick + (1:trunc(n / 2)) * inter.select)
}else{
output <- c(mid.tick - (trunc(n / 2):1) * inter.select, mid.tick, mid.tick + (1:(trunc(n / 2) - 1)) * inter.select)
}
}else{
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 3\n\n============\n\n"))
stop(tempo.cat)
}
# end centering the new scale 
# last check
if(min(output) < tempo.min){
output <- c(output[-1], max(output) + inter.select) # remove the lowest tick and add a tick at the top
}else if( max(output) > tempo.max){
output <- c(min(output) - inter.select, output[-length(output)])
}
if(min(output) < tempo.min | max(output) > tempo.max){
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 4\n\n============\n\n"))
stop(tempo.cat)
}
if(any(is.na(output))){
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 5 (NA GENERATION)\n\n============\n\n"))
stop(tempo.cat)
Gael  MILLOT's avatar
Gael MILLOT committed
2927
}
Gael  MILLOT's avatar
Gael MILLOT committed
2928
# end last check
Gael  MILLOT's avatar
Gael MILLOT committed
2929
2930
2931
2932
2933
2934
2935
}else{
tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 6\n\n============\n\n"))
stop(tempo.cat)
}
if(diff(lim.order) < 0){
output <- rev(output)
}
Gael  MILLOT's avatar
Gael MILLOT committed
2936
2937
2938
2939
return(output)
}


2940
2941
2942
2943
######## fun_post_plot() #### set graph param after plotting (axes redesign for instance)


 
Gael  MILLOT's avatar
Gael MILLOT committed
2944
2945
2946


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2947
2948
2949
2950
2951
2952
fun_post_plot <- function(x.side = 0, x.log.scale = FALSE, x.categ = NULL, x.categ.pos = NULL, x.lab = "", x.axis.magnific = 1.5, x.label.magnific = 1.5, x.dist.legend = 0.5, x.nb.inter.tick = 1, y.side = 0, y.log.scale = FALSE, y.categ = NULL, y.categ.pos = NULL, y.lab = "", y.axis.magnific = 1.5, y.label.magnific = 1.5, y.dist.legend = 0.5, y.nb.inter.tick = 1, text.angle = 90, tick.length = 0.5, sec.tick.length = 0.3, bg.color = NULL, grid.lwd = NULL, grid.col = "white", corner.text = "", magnific.corner.text = 1, just.label.add = FALSE, par.reset = FALSE, custom.par = NULL){
# AIM
# redesign axis. If x.side = 0, y.side = 0, the function just adds text at topright of the graph and reset par() for next graphics and provides outputs (see below)
# provide also positions for legend or additional text on the graph
# use fun_prior_plot() before this function for initial inactivation of the axis drawings
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
Gael  MILLOT's avatar
Gael MILLOT committed
2953
2954
# fun_check()
# fun_open() to reinitialize graph parameters if par.reset = TRUE and custom.par = NULL
Gael  MILLOT's avatar
Gael MILLOT committed
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
# ARGUMENTS
# x.side: axis at the bottom (1) or top (3) of the region figure. Write 0 for no change
# x.log.scale: Log scale for the x-axis? Either TRUE or FALSE
# x.categ: character vector representing the classes (levels()) to specify when the x-axis is qualititative(stripchart, boxplot)
# x.categ.pos: position of the classes names (numeric vector of identical length than x.categ). If left NULL, this will be 1:length(levels())
# x.lab: label of the x-axis. If x.side == 0 and x.lab != "", then x.lab is printed
# x.axis.magnific: increase or decrease the value to increase or decrease the size of the x axis numbers. Also control the size of displayed categories
# x.label.magnific: increase or decrease the value to increase or decrease the size of the x axis legend
# x.dist.legend: increase the number to move x-axis legends away in inches (first number of mgp argument of par() but in inches)
# x.nb.inter.tick: number of secondary ticks between main ticks on x-axis (only if not log scale). 0 means no secondary ticks
# y.side: axis at the left (2) or right (4) of the region figure. Write 0 for no change
# y.log.scale: Log scale for the y-axis? Either TRUE or FALSE
# y.categ: classes (levels()) to specify when the y-axis is qualititative(stripchart, boxplot)
# y.categ.pos: position of the classes names (numeric vector of identical length than y.categ). If left NULL, this will be 1:length(levels())
# y.lab: label of the y-axis. If y.side == 0 and y.lab != "", then y.lab is printed
# y.axis.magnific: increase or decrease the value to increase or decrease the size of the y axis numbers. Also control the size of displayed categories
# y.label.magnific: increase or decrease the value to increase or decrease the size of the y axis legend
# y.dist.legend: increase the number to move y-axis legends away in inches (first number of mgp argument of par() but in inches)
# y.nb.inter.tick: number of secondary ticks between main ticks on y-axis (only if not log scale). 0 means non secondary ticks
# text.angle: angle of the text when axis is qualitative
# tick.length: length of the main ticks (1 means complete the distance between the plot region and the axis numbers, 0.5 means half the length, etc., 0 for no ticks)
# sec.tick.length: length of the secondary ticks (1 means complete the distance between the plot region and the axis numbers, 0.5 means half the length, etc., 0 for no ticks)
# bg.color: background color of the plot region. NULL for no color. BEWARE: cover/hide an existing plot !
# grid.lwd: if non NULL, activate the grid line (specify the line width)
# grid.col: grid line color (only if grid.lwd non NULL)
# corner.text: text to add at the top right corner of the window
# magnific.corner.text: increase or decrease the size of the text
# par.reset: to reset all the graphics parameters. BEWARE: TRUE can generate display problems, mainly in graphic devices with multiple figure regions
# just.label.add: just add axis labels (legend)? Either TRUE or FALSE. If TRUE, at least (x.side == 0 & x.lab != "") or (y.side == 0 & y.lab != "") must be set to display the corresponding x.lab or y.lab
# custom.par: list that provides the parameters that reset all the graphics parameters. BEWARE: if NULL and par.reset == TRUE, the default par() parameters are used
# RETURN
# a list containing: 
# $x.mid.left.dev.region: middle of the left margin of the device region, in coordinates of the x-axis
# $x.left.dev.region: left side of the left margin (including the potential margin of the device region), in coordinates of the x-axis
# $x.mid.right.dev.region: middle of the right margin of the device region, in coordinates of the x-axis
# $x.right.dev.region: right side of the right margin (including the potential margin of the device region), in coordinates of the x-axis
# $x.mid.left.fig.region: middle of the left margin of the figure region, in coordinates of the x-axis
# $x.left.fig.region: left side of the left margin, in coordinates of the x-axis
# $x.mid.right.fig.region: middle of the right margin of the figure region, in coordinates of the x-axis
# $x.right.fig.region: right side of the right margin, in coordinates of the x-axis
# $x.left.plot.region: left side of the plot region, in coordinates of the x-axis
# $x.right.plot.region: right side of the plot region, in coordinates of the x-axis
# $x.mid.plot.region: middle of the plot region, in coordinates of the x-axis
# $y.mid.bottom.dev.region: middle of the bottom margin of the device region, in coordinates of the y-axis
# $y.bottom.dev.region: bottom side of the bottom margin (including the potential margin of the device region), in coordinates of the y-axis
# $y.mid.top.dev.region: middle of the top margin of the device region, in coordinates of the y-axis