##generate the synthetic control and make first plot

library(tidysynth)
library(ggplot2)
library(readxl)
base_para_synth <- read_excel("/Users/joseandressumanorodriguez/Desktop/bases clases/base para synth.xlsx")
synthout <- base_para_synth %>% 
  synthetic_control(outcome = TasaHomicidios,
                    unit= Alcaldia,
                    time= Tiempo,
                    i_unit = "AlvaroObregon",
                    i_time = 21,
                    generate_placebos = T) %>%
  generate_predictor(time_window = 1:21, Gini =mean(Gini, na.rm=T)) %>%
  generate_predictor(time_window=1:21, PoblacionenExtremaPobreza=mean(Poblacionenextremapobreza,na.rm=T))%>%
  generate_predictor(time_window = 1:21, Densidad= mean(Densidad, na.rm=T))%>%
  generate_predictor(time_window = 1:21, IDH =mean(IDH, na.rm=T))%>%
  generate_predictor(time_window = 1:21, Percepciondeinseguridad =mean(Percepciondeinseguridad, na.rm=T))%>%
  generate_predictor(time_window = 1:21, ConfianzaenPolicia =mean(ConfianzaenPolicia, na.rm=T))%>%
  generate_predictor(time_window = 1:21, Conflictos= mean(Conflictos, na.rm=T))%>%
  generate_predictor(time_window = 1:21, Disparos = mean(Disparos, na.rm=T))%>%
  generate_predictor(time_window = 1:21, Drogas =mean (Drogas, na.rm=T))%>%
  generate_weights(optimization_window = 1:21, margin_ipop = .02, sigf_ipop = 7, bound_ipop = 6) %>% generate_control()
  
synthout %>% plot_trends()  

##generate second plot

synthout %>% plot_differences()

#generate third plot

synthout %>% plot_weights()

#generate fourth plot

synthout %>% plot_placebos()+labs(x="Time", y="Homicide Rate")

#generate fifth plot

synthout %>% plot_mspe_ratio()   

#generate sixth visualization

synthout %>% grab_signficance()   
## # A tibble: 8 × 8
##   unit_name          type    pre_mspe post_mspe mspe_ratio  rank fishe…¹ z_score
##   <chr>              <chr>      <dbl>     <dbl>      <dbl> <int>   <dbl>   <dbl>
## 1 BenitoJuarez       Donor      0.157     0.209      1.33      1   0.125  2.15  
## 2 Coyoacán           Donor      0.202     0.158      0.783     2   0.25   0.505 
## 3 Tlalpan            Donor      0.763     0.514      0.673     3   0.375  0.180 
## 4 MagdalenaContreras Donor      0.574     0.354      0.617     4   0.5    0.0125
## 5 Cuajimalpa         Donor      0.603     0.260      0.431     5   0.625 -0.543 
## 6 AlvaroObregon      Treated    0.339     0.130      0.385     6   0.75  -0.680 
## 7 Azcapotzalco       Donor      0.728     0.251      0.345     7   0.875 -0.799 
## 8 Cuauhtemoc         Donor      2.20      0.738      0.336     8   1     -0.828 
## # … with abbreviated variable name ¹​fishers_exact_pvalue