Preliminares

Packages used

suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(knitr))
suppressPackageStartupMessages(library(kableExtra))
suppressPackageStartupMessages(library(future))
suppressPackageStartupMessages(library(furrr))

Loading data

pop19 <- read_csv("data/20211216T104300/POP19.csv", 
                  col_types = cols(cod_setor = col_character(), 
                                   cod_municipio = col_character(), 
                                   a06_domicilio = col_character(), 
                                   NumberHits = col_character(), 
                                   b00_numero = col_character(), 
                                   b04_idade = col_integer(), 
                                   rep = col_character(), 
                                   elegivel = col_integer(), 
                                   domicilio = col_character()))


# Estatística por setor
setores <- pop19 %>% 
  group_by(cod_setor, domicilio) %>% 
  count() %>% ungroup() %>% 
  group_by(cod_setor) %>% 
  summarise(ndomicilios = n(), npessoas = sum(n))


# Bases por domicílios

## Pessoas por domícilio
dom_pessoas <- pop19 %>% 
  group_by(cod_municipio, cod_setor, domicilio) %>% 
  summarise(npessoas = n(), .groups = "drop") 

## Categoria do teste IGM por domicílio
dom_igm <- pop19 %>% 
  count(cod_municipio, cod_setor, domicilio, resp_igm_tr) %>% 
  pivot_wider(cod_municipio:domicilio, 
              names_from = "resp_igm_tr", 
              names_prefix = "igm_", 
              names_sort = TRUE, 
              values_from = "n", 
              values_fill = 0L) 

## Categoria do teste IGG por domicílio
dom_igg <- pop19 %>% 
  count(cod_municipio, cod_setor, domicilio, resp_igg_tr) %>% 
  pivot_wider(cod_municipio:domicilio, 
              names_from = "resp_igg_tr", 
              names_prefix = "igg_", 
              names_sort = TRUE, 
              values_from = "n", 
              values_fill = 0L) 


## Base de domicílio com número de pessoas, número de testes IGG e IGM por
## categoria e elegibilidade.
domicilios <- dom_pessoas %>% 
  full_join(dom_igg, by = c("cod_municipio", "cod_setor", "domicilio")) %>% 
  full_join(dom_igm, by = c("cod_municipio", "cod_setor", "domicilio")) %>% 
  mutate(elegivel = sample(x = 1:0, size =  n(), replace = TRUE, prob = c(.80, .20)))

Retirado de Amostragem: Teoria e Prática Usando o R.

Amostragem sequencial de Poisson

O método de Amostragem Sequencial de Poisson - ASP, como apresentado em Amostragem: Teoria e Prática Usando o R, é uma modificação do método de Amostragem de Poisson que elimina a variabilidade do tamanho efetivo da amostra. O custo dessa modificação é um procedimento de amostragem um pouco mais complexo e que requer uso de resultados aproximados para a estimação tanto do total como de sua variância.

Um algoritmo baseado em processamento sequencial de lista para implementar o método para selecionar uma amostra de tamanho \(n\) da população \(U\) consiste nos seguintes passos.

  1. Gere um número aleatório uniforme independente \(A_i\) para cada unidade \(i\) da população.
  2. Calcule a medida de tamanho relativo \(p_i = x_i / X\) para cada unidade \(i\) da população.
  3. Calcule o número aleatório modificado \(C_i = A_i / p_i\).
  4. Ordene as unidades crescentemente segundo os valores dos números aleatórios modificados \(C_i\).
  5. Selecione para a amostra as \(n\) unidades com os menores valores de \(C_i\).

Amostragem PPT de Pareto

A seleção com Amostragem PPT de Pareto - AP, de acordo com Amostragem: Teoria e Prática Usando o R, segue os seguintes passos:

  1. Gere número aleatório uniforme independente \(A_i\) para cada unidade \(i\) da população.
  2. Calcule a probabilidade de inclusão desejável da unidade \(i: \lambda_i = n x_i/X\).
  3. Calcule o número aleatório modificado \(\displaystyle C_i=\frac{A_i(1-\lambda_i)}{(1-A_i)\lambda_i}\).
  4. Ordene as unidades crescentemente segundo valores dos números aleatórios modificados \(C_i\).
  5. Selecione para a amostra as \(n\) unidades com os menores valores de \(C_i\).

Target value

target <- domicilios %>% 
  select(starts_with(c("igg", "igm"))) %>% 
  pivot_longer(everything(), names_to = "teste", values_to = "n") %>% 
  separate(teste, into = c("teste", "resultado"), sep = "_") %>%
  group_by(teste, resultado) %>% 
  summarise(Frequência = sum(n), .groups = "drop") %>% 
  mutate(resultado = factor(as.numeric(resultado), 
                            levels = 1:4,
                            labels = c("Positivo",
                                       "Negativo", 
                                       "Inconclusivo", 
                                       "Não testado"))) %>% 
  arrange(teste, resultado)  %>% 
  group_by(teste) %>% 
  mutate(Percent = 100*`Frequência`/sum(`Frequência`), 
         FreqAcumulada = cumsum(`Frequência`), 
         PerAcumulada = cumsum(Percent)) %>% 
  ungroup()
target %>% 
  select(Resultado = resultado, 
         Frequência, 
         Percentagem = Percent, 
         `Frequência Acumulada` = FreqAcumulada, 
         `Percentagem Acumulada` = PerAcumulada) %>% 
  mutate(
    Frequência = format(Frequência, decimal.mark = ",", big.mark = "."),
    Percentagem = format(Percentagem,  decimal.mark = ",", big.mark = ".", digits = 1,  nsmall = 2, scientific = FALSE),
    `Frequência Acumulada` = format(`Frequência Acumulada`, decimal.mark = ",", big.mark = "."),
    `Percentagem Acumulada` = format(`Percentagem Acumulada`,  decimal.mark = ",", big.mark = ".", digits = 1,  nsmall = 2)) %>% 
  kbl( align = "lrrrr") %>%
  kable_material(c("striped", "hover")) %>% 
  
  column_spec(1, bold = TRUE) %>%
  pack_rows("Teste IGG", 1, 4) %>%
  pack_rows("Teste IGM", 5, 8) %>% 
  kable_styling(font_size = 11)
Resultado Frequência Percentagem Frequência Acumulada Percentagem Acumulada
Teste IGG
Positivo 31.323 9,10 31.323 9,10
Negativo 290.611 84,44 321.934 93,54
Inconclusivo 51 0,01 321.985 93,56
Não testado 22.176 6,44 344.161 100,00
Teste IGM
Positivo 11.755 3,42 11.755 3,42
Negativo 310.102 90,10 321.857 93,52
Inconclusivo 128 0,04 321.985 93,56
Não testado 22.176 6,44 344.161 100,00

Samping and Monte Carlo functions

Sampling function

survey_sample <- function(first_stage_base,
                          first_stage_size_variable, 
                          n_first_stage, 
                          first_stage = "poisson",
                          second_stage_base, 
                          n_second_stage, 
                          second_stage = "inverse"){
  
  if (!(first_stage %in% c("poisson", "pareto"))) {
    stop("firt_stage must be 'poisson' or 'pareto'")
  }
  
  if (!(second_stage %in% c("inverse", "systematic"))) {
    stop("second_stage must be 'inverse' or 'systematic'")
  }
  
  if ((!is.integer(n_first_stage))||(n_first_stage <= 0)){
    stop("n_first_stage must be interger greater then zero")
  }

  if ((!is.integer(n_second_stage))||(n_second_stage <= 0)){
    stop("n_second_stage must be interger greater then zero")
  }

    
  if (!is_tibble(second_stage_base)){
    stop("second_stage_base must be a tibble")
  }
  
  if (!is_tibble(first_stage_base)){
    stop("first_stage_base must be a tibble")
  }
  
  if (!(first_stage_size_variable %in% names(first_stage_base))) {
    stop("first_stage_size_variable must be a variable in first_stage_base")
  }
  
  # if (!is.null(seed)) {
  #   if (!is.integer(seed)){
  #     stop("Seed must be a interger")
  #   }
  #   set.seed(seed = seed)
  # }
  
  #### Drawing first stage sample
  
  ###print(first_stage_base)
  
  if (first_stage == "poisson"){
    if (is.null(first_stage_size_variable)) stop("You must choose a size variable")
    first_stage_sample <- first_stage_base %>% 
      ungroup() %>% 
      mutate(ai = runif(n()), 
             pi := (!!sym(first_stage_size_variable))/sum((!!sym(first_stage_size_variable))), 
             lambdai = n_first_stage*pi,
             ci = ai/pi) %>%
      slice_min(order_by = ci, n = n_first_stage)
  } 
  
  if (first_stage == "pareto"){
    if (is.null(first_stage_size_variable)) stop("You must choose a size variable")
    first_stage_sample <- first_stage_base %>% 
      ungroup() %>% 
      mutate(ai = runif(n()), 
             pi := (!!sym(first_stage_size_variable))/sum((!!sym(first_stage_size_variable))), 
             lambdai = n_first_stage*pi,
             ci = (ai*(1 - lambdai))/((1 - ai)*lambdai)) %>%
      slice_min(order_by = ci, n = n_first_stage) 
  }
  
  #### Preparing data for second stage
  second_stage_base <- first_stage_sample %>% 
    select(cod_setor, setor_ai = ai, setor_pi = pi, setor_lambdai = lambdai, setor_ci = ci) %>% 
    left_join(second_stage_base, by = "cod_setor")
  
  if (second_stage == "inverse"){
    second_stage_sample <- second_stage_base %>% 
      ungroup() %>% 
      mutate(ai = runif(n())) %>%
      group_by(cod_setor) %>% 
      mutate(pi = n_second_stage/n()) %>% 
      filter(elegivel > .5) %>% 
      slice_min(order_by = ai, n = n_second_stage) %>% 
      ungroup()
  }
  
  
  
  if (second_stage == "systematic"){
    
    systematics_s <- second_stage_base %>% 
      #filter(elegivel > .5) %>% 
      count(cod_setor, name = "N") %>% 
      group_by(cod_setor) %>%  
      mutate(ai = floor(N/n_second_stage), 
             pi = 1/ai,
             epsiloni = sample(1:ai, 1), # (round(runif(1, max = ai))), 
             S = list(ceiling(epsiloni + (0:(n_second_stage))*ai))) %>% 
      unnest(S) %>% 
      filter(S <= N)
    
    second_stage_sample <- systematics_s %>% 
      left_join(
        second_stage_base %>% 
          #filter(elegivel > .5) %>% 
          group_by(cod_setor) %>% 
          mutate(k = 1:n()) %>% 
          ungroup(),
        by = c("cod_setor", "S" = "k")
    )
  }
  return(second_stage_sample %>% mutate(p = setor_pi*pi))
}
## Testing function

sample_df <- survey_sample(first_stage_base = setores,
              first_stage_size_variable = "ndomicilios",
              n_first_stage = 100L,
              first_stage = "pareto", 
              second_stage_base = domicilios,
              n_second_stage = 20L,
              second_stage = "inverse")

Estimate totals function

estimate_totals <- function(sample_data, n_first_stage){
  estimativas_setor <- sample_data %>% 
    select(cod_setor, setor_pi, pi, starts_with(c("igg", "igm"))) %>% 
    pivot_longer(-cod_setor:-pi, names_to = "teste", values_to = "yi") %>% 
    separate(teste, into = c("teste", "resultado"), sep = "_") %>% 
    group_by(cod_setor, setor_pi, teste, resultado) %>% 
    summarise(ti_hat = sum(yi/pi), .groups = "drop")
  
  estimativas <- estimativas_setor %>% 
    group_by(teste, resultado) %>% 
    summarise(t_hat = sum(ti_hat/(n_first_stage*setor_pi)), .groups = "drop")
  
  estimativas_setor %>% 
    left_join(estimativas,
              by = c("teste", "resultado")) %>% 
    group_by(teste, resultado, t_hat) %>% 
    summarise(Var_t_hat = sum(((ti_hat/setor_pi) - t_hat)^2)/(n_first_stage*(n_first_stage - 1)), 
              .groups = "drop") 
    #mutate(sd_t = sqrt(Var_t))
}
estimate_totals(sample_df, 100) %>% 
  mutate(resultado = factor(as.numeric(resultado), 
                            levels = 1:4,
                            labels = c("Positivo",
                                       "Negativo", 
                                       "Inconclusivo", 
                                       "Não testado"))) %>% 
  arrange(teste, resultado) %>% 
  select(Resultado = resultado, t_hat, Var_t_hat) %>% 
  mutate(
    t_hat = format(t_hat, decimal.mark = ",", big.mark = ".", digits = 0, nsmall = 1, scientific = FALSE),
    Var_t_hat = format(Var_t_hat, decimal.mark = ",", big.mark = ".", scientific = FALSE)) %>% 
  kbl( align = "lrr") %>%
  kable_material(c("striped", "hover")) %>% 
  column_spec(1, bold = TRUE) %>%
  pack_rows("Teste IGG", 1, 4) %>%
  pack_rows("Teste IGM", 5, 8) %>% 
  kable_styling(font_size = 11)
Resultado t_hat Var_t_hat
Teste IGG
Positivo 26.411,2 11.588.731,890
Negativo 278.036,2 140.968.766,892
Inconclusivo 44,9 2.017,537
Não testado 23.401,8 12.310.215,309
Teste IGM
Positivo 9.791,9 3.343.731,137
Negativo 294.296,2 142.289.254,975
Inconclusivo 404,3 106.358,839
Não testado 23.401,8 12.310.215,309

Function get_replica

get_replica <- function(first_stage,
                        second_stage,
                        n_first_stage,
                        n_second_stage,
                        replica){
  sample_tibble <- survey_sample(first_stage_base = setores,
                first_stage_size_variable = "ndomicilios",
                n_first_stage = n_first_stage,
                first_stage = first_stage, 
                second_stage_base = domicilios,
                n_second_stage = n_second_stage,
                second_stage = second_stage)
  
  results <- estimate_totals(sample_tibble, n_first_stage)
  return(results)
}

Monte Carlo simulations

Sequencial version

N_replicas = 100

# expand_grid(
#   replica = 1:N_replicas,
#   first_stage = c('poisson', 'pareto'),
#   second_stage = c('inverse', 'systematic'),
#   n_first_stage = 100L,
#   n_second_stage = 10L
# ) %>% 
#   mutate(simulation = 1:n()) %>% 
#   map2_dfr
  

design_factors <- list(
  replica = 1:N_replicas,
  first_stage = c('poisson', 'pareto'),
  second_stage = c('inverse', 'systematic')
)

params <- cross_df(design_factors) %>%
  mutate(
    n_first_stage = 100L,
    n_second_stage = 10L#,
    #seed = as.integer(round(runif(1) * 2^30) + 1:n())
  ) 

# system.time(
#   results <- params %>%
#     mutate(
#       res = pmap(. , .f = get_replica)
#     ) %>%
#     unnest(cols = res)
# )

Parallel version

plan(multisession) # choose an appropriate plan from the future package

system.time(
  results <-
    params %>%
    mutate(res = future_pmap(., .f = get_replica, .options = furrr_options(seed = TRUE))) %>%
    unnest(cols = res)
)
##    user  system elapsed 
##   2.059   0.126  23.740

Results

estimates <- results %>% 
  group_by(teste, resultado, first_stage, second_stage) %>% 
  summarise(t_hat_mean = mean(t_hat),
            Var_t_hat_mean = mean(Var_t_hat),
            Replicas = n(), .groups = "drop") %>% 
  mutate(resultado = factor(as.numeric(resultado), 
                            levels = 1:4,
                            labels = c("Positivo",
                                       "Negativo", 
                                       "Inconclusivo", 
                                       "Não testado"))) %>% 
  arrange(teste, resultado, first_stage, second_stage)


estimates %>% 
    mutate(t_hat_mean = format(t_hat_mean, 
                               dec.mark = ",", 
                               big.mark = ",", 
                               scientific = FALSE, 
                               digits = 0, 
                               nsmall = 1),
           Var_t_hat_mean = format(Var_t_hat_mean, 
                                   dec.mark = ",", 
                                   big.mark = ",", 
                                   scientific = FALSE, 
                                   digits = 0)) %>% 
  kbl( align = "llllrrr") %>%
  kable_material(c("striped", "hover")) %>% 
  column_spec(1, bold = TRUE) %>% 
  kable_styling(font_size = 11)
teste resultado first_stage second_stage t_hat_mean Var_t_hat_mean Replicas
igg Positivo pareto inverse 31,296.4 20,077,547 100
igg Positivo pareto systematic 31,475.9 16,667,063 100
igg Positivo poisson inverse 32,028.5 20,844,362 100
igg Positivo poisson systematic 31,347.9 16,372,301 100
igg Negativo pareto inverse 289,510.7 215,008,671 100
igg Negativo pareto systematic 290,057.7 191,522,562 100
igg Negativo poisson inverse 290,387.5 222,044,242 100
igg Negativo poisson systematic 290,131.1 198,842,838 100
igg Inconclusivo pareto inverse 57.5 12,099 100
igg Inconclusivo pareto systematic 54.8 6,859 100
igg Inconclusivo poisson inverse 45.8 9,114 100
igg Inconclusivo poisson systematic 60.1 8,417 100
igg Não testado pareto inverse 21,834.2 9,630,290 100
igg Não testado pareto systematic 22,012.9 8,369,985 100
igg Não testado poisson inverse 22,419.9 10,342,294 100
igg Não testado poisson systematic 22,093.0 8,252,832 100
igm Positivo pareto inverse 11,499.7 7,688,817 100
igm Positivo pareto systematic 11,345.3 6,426,495 100
igm Positivo poisson inverse 11,995.5 8,619,452 100
igm Positivo poisson systematic 11,536.5 6,226,225 100
igm Negativo pareto inverse 309,250.0 230,711,191 100
igm Negativo pareto systematic 310,101.0 206,281,037 100
igm Negativo poisson inverse 310,355.8 238,829,073 100
igm Negativo poisson systematic 309,854.4 213,817,930 100
igm Inconclusivo pareto inverse 115.0 33,348 100
igm Inconclusivo pareto systematic 142.1 34,673 100
igm Inconclusivo poisson inverse 110.5 33,431 100
igm Inconclusivo poisson systematic 148.2 38,465 100
igm Não testado pareto inverse 21,834.2 9,630,290 100
igm Não testado pareto systematic 22,012.9 8,369,985 100
igm Não testado poisson inverse 22,419.9 10,342,294 100
igm Não testado poisson systematic 22,093.0 8,252,832 100
results %>% 
  group_by(teste, resultado, first_stage, second_stage) %>% 
  mutate(resultado = recode(resultado, 
                            '1' = "Positivo",
                            '2' = "Negativo",
                            '3' = "Inconclusivo",
                            '4' = "Não testado")) %>%
  mutate(plano = paste0("(", first_stage ,", ", second_stage, ")")) %>% 
  ggplot() +
  geom_boxplot(aes(y = t_hat, x = plano, fill = plano), 
               alpha = .8) + 
  # geom_jitter(aes(y = t_hat, x = plano), 
  #             alpha = .2, color = "red") +
facet_wrap( ~ resultado + teste, scales = "free", 
            nrow = 8) +
  theme(legend.position="bottom") +
  geom_hline(aes(yintercept = Frequência), 
             size = 1, 
             color = "red", 
             data = target) + 
  geom_text(aes(x = 0, 
                y = Frequência),
            label = "True value", 
            vjust = -.5, 
            hjust = -.25,
            data = target)

Stay Tuned

Please visit the CASTLab page for latest updates and news. Comments, bug reports and pull requests are always welcome.