## ----cache=FALSE, include=FALSE-------------------------------------------------------------
## source("../setup_knitr.R")
source("config/setup_knitr.R")
opts_chunk$set(fig.path = "figures/01_tecnicas/")
library(RefManageR)
BibOptions(check.entries = FALSE,
           bib.style = "authoryear",
           cite.style = "authoryear",
           style = "markdown",
           hyperlink = FALSE,
           dashed = FALSE)
bib <- ReadBib("config/refs.bib", check = FALSE)
xaringanExtra::use_xaringan_extra("tachyons")
## knitr::opts_chunk$set(out.width = "80%")


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- 1:1e6
# out <- numeric(length(x))
# for(i in seq_along(x)){
#     out[i] <- x[i]^2
# }


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- 1:1e6
# out <- x^2


## ----eval=TRUE------------------------------------------------------------------------------
library(microbenchmark)
x <- 1:1e6

sq_loop <- function(x) {
    out <- numeric(length(x))
    for(i in seq_along(x)) out[i] <- x[i]^2
    out
}
sq_vec <- function(x) x^2

microbenchmark(sq_loop(x), sq_vec(x), times = 20)


## ----eval=FALSE-----------------------------------------------------------------------------
# out <- c()
# for(i in 1:n){
#     out <- c(out, f(i))
# }


## ----eval=FALSE-----------------------------------------------------------------------------
# out <- numeric(n)
# for(i in 1:n){
#     out[i] <- f(i)
# }


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- 1:5
# y <- x               # duas referências ao mesmo objeto
# tracemem(x)
# # [1] "<0x560c12a34b88>"
#
# y[1] <- 10L          # precisa copiar para preservar x
# # tracemem[0x560c12a34b88 -> 0x560c12b01c40]:
#
# untracemem(x)


## ----eval=TRUE------------------------------------------------------------------------------
library(lobstr)
x <- 1:5
obj_addr(x)   # endereço
obj_size(x)   # tamanho

y <- x        # NÃO copia!
obj_addr(y)   # mesmo endereço

y[1] <- 10L   # agora copia
obj_addr(y)   # outro endereço
obj_addr(x)   # x inalterado


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- c(1, 2, 3, 4, 5)  # uma referência
# tracemem(x)
# x[1] <- 10             # SEM cópia!
# x[2] <- 20             # SEM cópia!
# ## Nenhum tracemem[...] é
# ## impresso


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- c(1, 2, 3, 4, 5)
# y <- x                 # duas referências
# tracemem(x)
# x[1] <- 10
# ## tracemem[...]: <- copiou
# x[2] <- 20
# ## silêncio: agora só x aponta
# ## para este objeto novo


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- 1:1e4
# out <- numeric(0)
# tracemem(out)
# for(i in seq_along(x)){
#     out[i] <- x[i]^2   # estende o vetor → realocação frequente
# }
# tracemem(out)


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- 1:1e4
# out <- numeric(length(x))
# tracemem(out)
# for(i in seq_along(x)){
#     out[i] <- x[i]^2   # modifica in place — sem cópias
# }
# tracemem(out)


## -------------------------------------------------------------------------------------------
(df <- data.frame(v = 1:4, name = letters[1:4]))


## -------------------------------------------------------------------------------------------
system.time(df[3, 2])
system.time(df[3, "name"])
system.time(df$name[3])


## -------------------------------------------------------------------------------------------
library(microbenchmark)
(mb1 <- microbenchmark(df[3, 2], df[3, "name"], df$name[3]))


## -------------------------------------------------------------------------------------------
x <- runif(1e6)
(mb2 <- microbenchmark(sqrt(x), x^0.5))


## -------------------------------------------------------------------------------------------
boxplot(mb1)


## -------------------------------------------------------------------------------------------
boxplot(mb2)


## -------------------------------------------------------------------------------------------
## Vetor com uma sequência de 1 a 10.000.000
x <- 1:1e7

## Cria um objeto de armazenamento com o mesmo tamanho do resultado
st1 <- system.time({
    out1 <- numeric(length(x))
    for(i in seq_along(x)){
        out1[i] <- x[i]^2
    }
})
st1

## Cria um objeto de tamanho "zero" e vai "crescendo" esse vetor
st2 <- system.time({
    out2 <- numeric(0)
    for(i in seq_along(x)){
        out2[i] <- x[i]^2
    }
})
st2


## -------------------------------------------------------------------------------------------
## Vetor menor e poucas repetições
x <- 1:1e5

## Primeira forma: pré-aloca
f_prealoc <- function(x) {
    out <- numeric(length(x))
    for(i in seq_along(x)){
        out[i] <- x[i]^2
    }
    out
}
## Segunda forma: cresce
f_cresce <- function(x) {
    out <- numeric(0)
    for(i in seq_along(x)){
        out[i] <- x[i]^2
    }
    out
}
## Importante: passar x como argumento!
(mb <- microbenchmark(f_prealoc(x), f_cresce(x),
                      times = 10))


## -------------------------------------------------------------------------------------------
boxplot(mb)


## ----eval=TRUE------------------------------------------------------------------------------
library(bench)
x <- 1:1e5

bm <- bench::mark(
    loop_prealoc = f_prealoc(x),
    loop_cresce  = f_cresce(x),
    vetorizado   = x^2,
    iterations = 20
)
bm


## ----eval=TRUE, out.width='90%'-------------------------------------------------------------
plot(bm)


## ----eval=FALSE-----------------------------------------------------------------------------
# ## IMPORTANTE: vetor grande o
# ## bastante para o profiler ver
# x <- 1:1e8
#
# ## Caso 1: pré-aloca
# Rprof() ## Abre a conexão
# out1 <- numeric(length(x))
# for(i in seq_along(x)){
#     out1[i] <- x[i]^2
# }
# Rprof(NULL) ## Fecha a conexão
# summaryRprof()


## ----eval=FALSE-----------------------------------------------------------------------------
# ## Caso 2: cresce o vetor
# x <- 1:1e8
#
# Rprof()
# out2 <- numeric(0)
# for(i in seq_along(x)){
#     out2[i] <- x[i]^2
# }
# Rprof(NULL)
# summaryRprof()


## ----eval=FALSE-----------------------------------------------------------------------------
# $by.self
# [1] self.time  self.pct   total.time total.pct
# <0 rows> (or 0-length row.names)
# $sampling.time
# [1] 0


## ----eval=FALSE-----------------------------------------------------------------------------
# x <- 1:1e7      # em vez de 1e5


## ----eval=FALSE-----------------------------------------------------------------------------
# Rprof(interval = 0.002)
# ## mínimo prático ~1 ms em Linux


## ----eval=FALSE-----------------------------------------------------------------------------
# library(profvis)
# ## Caso 1
# profvis({
#     out1 <- numeric(length(x))
#     for(i in seq_along(x)){
#         out1[i] <- x[i]^2
#     }
# })


## ----eval=FALSE-----------------------------------------------------------------------------
# ## Caso 2
# profvis({
#     out2 <- numeric(0)
#     for(i in seq_along(x)){
#         out2[i] <- x[i]^2
#     }
# })


## ----out.width='65%'------------------------------------------------------------------------
set.seed(123)
n <- 1000; b0 <- 10; b1 <- 0.5
x <- rnorm(n, mean = 150, sd = 15)
sigma2 <- 20
y <- b0 + b1*x + rnorm(n, mean = 0, sd = sqrt(sigma2))
plot(x, y)


## ----out.width='55%'------------------------------------------------------------------------
## Modelo
m <- lm(y ~ x)
## b0 e b1
coef(m)
## sigma^2
summary(m)$sigma^2
plot(x, y); abline(m, col = 2)


## ----p0, eval=TRUE, cache=TRUE, include=FALSE-----------------------------------------------
## Necessario rodar antes sem o profvis, porque dentro dele os objetos
## criados não são salvos

## Número de amostras
r <- 1e4
## Número de elementos em cada amostra
m <- 100

## Vetores para armazenar os resultados
b0.boot <- numeric(r)
b1.boot <- numeric(r)
s2.boot <- numeric(r)
set.seed(123)
for(i in seq_len(r)){
    select <- sample(1:length(y), size = m, replace = TRUE)
    x.boot <- x[select]
    y.boot <- y[select]
    mm <- lm(y.boot ~ x.boot)
    b0.boot[i] <- coef(mm)[1]
    b1.boot[i] <- coef(mm)[2]
    s2.boot[i] <- summary(mm)$sigma^2
}


## ----eval=FALSE, cache=TRUE-----------------------------------------------------------------
# ## Número de amostras
# r <- 1e4
# ## Número de elementos em cada amostra
# m <- 100
#
# ## Inicia o profiling
# library(profvis)
# profvis({ #<<
# ## Vetores para armazenar os resultados
# b0.boot <- numeric(r)
# b1.boot <- numeric(r)
# s2.boot <- numeric(r)
# set.seed(123)
# for(i in 1:r){
#     select <- sample(1:length(y), size = m, replace = TRUE)
#     x.boot <- x[select]
#     y.boot <- y[select]
#     mm <- lm(y.boot ~ x.boot)
#     b0.boot[i] <- coef(mm)[1]
#     b1.boot[i] <- coef(mm)[2]
#     s2.boot[i] <- summary(mm)$sigma^2
# }
# }) #<<


## ----fig.show='hold', out.width='80%'-------------------------------------------------------
par(mfrow = c(1, 3))
hist(b0.boot); abline(v = b0, col = 2, lwd = 2)
hist(b1.boot); abline(v = b1, col = 2, lwd = 2)
hist(s2.boot); abline(v = sigma2, col = 2, lwd = 2)
par(mfrow = c(1, 1))


## -------------------------------------------------------------------------------------------
lapply(list(b0.boot, b1.boot, s2.boot), summary)


## ----error=TRUE-----------------------------------------------------------------------------
try({
stop("Isso é um erro")
warning("Isso é um warning")
message("Isso é uma mensagem")
})


## ----error=TRUE-----------------------------------------------------------------------------
try({
f <- function(x) {
    stopifnot(is.numeric(x), length(x) == 1)
    x^2
}
f("a")
f(1:3)
})


## ----error=TRUE-----------------------------------------------------------------------------
try({
baskara <- function(a, b, c) {
    stopifnot(
        "`a`, `b` e `c` devem ser numericos" =
            is.numeric(a) && is.numeric(b) && is.numeric(c),
        "`a` nao pode ser zero" = a != 0,
        "argumentos devem ter tamanho 1" =
            length(a) == 1 && length(b) == 1 && length(c) == 1
    )
    delta <- b^2 - 4 * a * c
    if(delta < 0) stop("Delta e negativo.")
    denom <- 2 * a
    sqrt_delta <- sqrt(delta)
    c((-b - sqrt_delta)/denom, (-b + sqrt_delta)/denom)
}
baskara(0, 2, 1)
baskara("x", 2, 1)
})


## -------------------------------------------------------------------------------------------
baskara <- function(a, b, c) {
    denom <- 2 * a
    delta <- b^2 - 4 * a * c
    sqrt_delta <- sqrt(delta)
    x1 <- (-b - sqrt_delta)/denom
    x2 <- (-b + sqrt_delta)/denom
    return(c(x1, x2))
}


## -------------------------------------------------------------------------------------------
baskara(-3, 2, 1)
baskara(0, 2, 1) # 2 * a = 0
baskara(3, 2, 1) # 2^2 - 4 * 3 * 1 = -8


## ----eval=FALSE-----------------------------------------------------------------------------
# traceback()
# # No traceback available


## -------------------------------------------------------------------------------------------
baskara <- function(a, b, c) {
    if(a == 0) stop("Argumento `a` não pode ser zero.") #<<
    denom <- 2 * a
    delta <- b^2 - 4 * a * c
    sqrt_delta <- sqrt(delta)
    x1 <- (-b - sqrt_delta)/denom
    x2 <- (-b + sqrt_delta)/denom
    return(c(x1, x2))
}


## ----error=TRUE-----------------------------------------------------------------------------
try({
baskara(0, 2, 1)
})

## ----eval=FALSE-----------------------------------------------------------------------------
# traceback()
# # 2: stop("Argumento `a` não pode ser zero.") at #2
# # 1: baskara(0, 2, 1)


## ----eval=FALSE, include=FALSE--------------------------------------------------------------
# getOption("warn")
# options(warn = 2)
# baskara(3, 2, 1)
# traceback()
# options(warn = 0)


## -------------------------------------------------------------------------------------------
baskara <- function(a, b, c) {
    if(a == 0) stop("Argumento `a` não pode ser zero.")
    denom <- 2 * a
    delta <- b^2 - 4 * a * c
    if(delta < 0) stop("Delta é negativo.") #<<
    sqrt_delta <- sqrt(delta)
    x1 <- (-b - sqrt_delta)/denom
    x2 <- (-b + sqrt_delta)/denom
    return(c(x1, x2))
}


## ----error=TRUE-----------------------------------------------------------------------------
try({
baskara(3, 2, 1)
})

## ----eval=FALSE-----------------------------------------------------------------------------
# traceback()
# # 2: stop("Delta é negativo.") at #5
# # 1: baskara(3, 2, 1)


## ----eval=FALSE-----------------------------------------------------------------------------
# baskara <- function(a, b, c) {
#     denom <- 2 * a
#     delta <- b^2 - 4 * a * c
#     browser() #<<
#     sqrt_delta <- sqrt(delta)
#     x1 <- (-b - sqrt_delta)/denom
#     x2 <- (-b + sqrt_delta)/denom
#     return(c(x1, x2))
# }


## ----eval=FALSE-----------------------------------------------------------------------------
# baskara(3, 2, 1)
# # Called from: baskara(3, 2, 1)
# # Browse[1]> debug at #5: sqrt_delta <- sqrt(delta)
# # Browse[2]>


## ----eval=FALSE-----------------------------------------------------------------------------
# baskara <- function(a, b, c) {
#     denom <- 2 * a
#     delta <- b^2 - 4 * a * c
#     sqrt_delta <- sqrt(delta)
#     x1 <- (-b - sqrt_delta)/denom
#     x2 <- (-b + sqrt_delta)/denom
#     return(c(x1, x2))
# }


## ----eval=FALSE-----------------------------------------------------------------------------
# ## Para iniciar o debug, use:
# debug(baskara)
# ## Para entrar em modo de debug, chame a função com argumentos:
# baskara(3, 2, 1)
# ## Para sair do modo debug da função, faça:
# undebug(baskara)
# ## Ou, para entrar em modo de debug apenas uma vez e sair, use:
# debugonce(baskara)


## ----eval=FALSE-----------------------------------------------------------------------------
# options(error = recover)


## ----eval=FALSE-----------------------------------------------------------------------------
# options(error = recover)
# baskara(0, 2, 1)
#
# # Error in baskara(0, 2, 1) : Argumento `a` não pode ser zero.
# #
# # Enter a frame number, or 0 to exit
# #
# # 1: baskara(0, 2, 1)
# #
# # Selection:


## ----eval=FALSE-----------------------------------------------------------------------------
# options(error = NULL)


## ----eval=FALSE-----------------------------------------------------------------------------
# options(error = recover)    # interativo, post-mortem
# options(error = traceback)  # imprime a pilha e volta
# options(error = NULL)       # comportamento padrão
#
# options(warn = 0)           # padrão: warnings acumulados
# options(warn = 1)           # imprime warnings imediatamente
# options(warn = 2)           # converte warnings em errors


## -------------------------------------------------------------------------------------------
baskara <- function(a, b, c) {
    if(a == 0) stop("Argumento `a` não pode ser zero.") #<<
    denom <- 2 * a
    delta <- b^2 - 4 * a * c
    if(delta < 0) stop("Delta é negativo.") #<<
    sqrt_delta <- sqrt(delta)
    x1 <- (-b - sqrt_delta)/denom
    x2 <- (-b + sqrt_delta)/denom
    return(c(x1, x2))
}


## ----error=TRUE-----------------------------------------------------------------------------
try({
baskara(0, 2, 1)
er1 <- baskara(0, 2, 1)
er1
})


## ----error=TRUE-----------------------------------------------------------------------------
try({
try(baskara(0, 2, 1))
er2 <- try(baskara(0, 2, 1))
er2
class(er2)
})


## -------------------------------------------------------------------------------------------
fn <- function(...) {
    res <- try(baskara(...))
    ## Idiomático: inherits(), não class() ==
    if(inherits(res, "try-error")){ #<<
        warning("Deu erro seu jaguara")
    }
}
er3 <- fn(0, 2, 1)
er3


## -------------------------------------------------------------------------------------------
tryCatch(baskara(0, 2, 1),
         error = function(cmd) c(NA, NA))
tryCatch(baskara(3, 2, 1),
         error = function(cmd) c(NA, NA))


## -------------------------------------------------------------------------------------------
baskara2 <- function(a, b, c) {
    if(a == 0) stop("Argumento `a` não pode ser zero.") #<<
    denom <- 2 * a
    delta <- b^2 - 4 * a * c
    ## if(delta < 0) stop("Delta é negativo.") #<<
    sqrt_delta <- tryCatch(sqrt(delta), #<<
                           warning = function(cmd) NA) #<<
    x1 <- (-b - sqrt_delta)/denom
    x2 <- (-b + sqrt_delta)/denom
    return(c(x1, x2))
}


## ----error=TRUE-----------------------------------------------------------------------------
try({
baskara(0, 2, 1)
baskara2(0, 2, 1)

baskara(3, 2, 1)
baskara2(3, 2, 1)
})


## ----eval=FALSE-----------------------------------------------------------------------------
# b0.boot <- numeric(r)
# b1.boot <- numeric(r)
# s2.boot <- numeric(r)
# set.seed(123)
# for(i in 1:r){
#     select <- sample(seq_along(y), size = m, replace = TRUE)
#     res <- tryCatch(
#         lm(y[select] ~ x[select]),
#         error = function(e) NULL
#     )
#     if(is.null(res)){
#         b0.boot[i] <- NA
#         b1.boot[i] <- NA
#         s2.boot[i] <- NA
#     } else {
#         b0.boot[i] <- coef(res)[1]
#         b1.boot[i] <- coef(res)[2]
#         s2.boot[i] <- summary(res)$sigma^2
#     }
# }


## ----include=FALSE, eval=FALSE--------------------------------------------------------------
# ## Para gerar o PDF
# xaringanBuilder::build_pdf("01_tecnicas.Rmd")
# ## Nao funciona
