-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrole_sintetico.R
356 lines (313 loc) · 16 KB
/
controle_sintetico.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
library(tidyverse)
# install.packages("devtools")
# library(devtools)
# install_github("bcastanho/SCtools")
#Não fatais ----
df.original <- data.table::fread("dados/acidentes_naofatais.csv", encoding = "Latin-1")
## preprocessamento para utilizar dados do infosiga que contenham um sinistro com vítima em que uma motocicleta
## estava envolvida na cidade de São Paulo
df.preprocessado <- df.original %>%
as_tibble() %>%
select(nm_municipio = Município,
data = "Data do Acidente", rua = "Logradouro", id = ID,
motocicletas = "Veículos Envolvidos - Motocicleta",
feridos_graves = "Pessoas Envolvidas - Grave",
feridos_leves = "Pessoas Envolvidas - Leve") %>%
mutate(motocicleta = motocicletas > 0,
feridos = (feridos_graves > 0 | feridos_leves > 0)) %>%
filter(nm_municipio == "SAO PAULO", feridos > 0, motocicletas > 0) %>%
mutate(ano = lubridate::year(data),
mes = lubridate::month(data)) %>%
group_by(ano, mes, rua) %>%
summarize(acidentes = sum(motocicleta))
## Aqui é criado o dataframe que será empregado nas análises
## Primeiramente é criado um dataframe com cada ano e mês de interesse (entre 2019 e a data mais atual)
## com cada uma das ruas que apresentaram mais de 100 sinistros ao longo desse periodo
df <- data.frame(ano = c(2019:2023),
mes = rep(c(1:12), each = 5),
rua = rep(df.preprocessado %>%
group_by(rua) %>%
summarize(acidentes = sum(acidentes)) %>%
filter(acidentes > 100) %>%
distinct(rua) %>%
pull(rua),
each = 5*12)) %>%
as_tibble() %>%
## aqui é realizada a inserção dos dados do infosiga preprocessados anteriormente
left_join(df.preprocessado) %>%
arrange(rua, desc(ano), desc(mes)) %>%
## o mutate abaixo serve para substituir o dado faltante de 03/2023 em que não foram registrados
## ocorrências na base (ainda que tenham ocorrido sinistros no período)
## para tanto, foi realizada a substituição pela média dos três meses anteriores
mutate(acidentes = replace_na(acidentes, 0),
acidentes_mm = zoo::rollapply(acidentes, 3, mean, align = "left", fill = NA),
acidentes = ifelse(ano == 2023 & mes == 3, lead(acidentes_mm), acidentes)) %>%
select(-acidentes_mm) %>%
## por fim os dados são agrupados para cada rua e é aplicado o filtro HP com freq apropriada para dados mensais
## e recuperamos o valor de tendencia (uma das componentes retornadas pela função)
group_by(rua) %>%
mutate(acidentes_hp = mFilter::hpfilter(sqrt(acidentes), freq = 144)$trend[,1]) %>%
ungroup()
## plot de comparação dos dados da Av. dos Bandeirantes com e sem a aplicação do filtro HP
df %>%
filter(rua == "AVENIDA DOS BANDEIRANTES") %>%
mutate(data = zoo::yearmon(ano + (mes - 1)/12)) %>%
ggplot(aes(x = data)) +
geom_line(aes(y = acidentes, linetype = "Sinistros")) +
geom_line(aes(y = acidentes_hp ^ 2, linetype = "Sinistros (filtro HP)")) +
scale_linetype_manual(values = c("Sinistros" = "solid", "Sinistros (filtro HP)" = "dashed")) +
labs(x = "Data", y="Quantidade de sinistros", linetype = "") +
theme_classic()
ggsave("output/FiltroHP.png", dpi = 600, width = 9, height = 4)
df.prep <- df %>%
group_by(rua) %>%
summarize(id = 1) %>%
mutate(id = cumsum(id)) %>%
right_join(df) %>%
mutate(mes = (mes)/12,
ano = round(ano + mes, 3)) %>%
as.data.frame()
id.tratamento <- df.prep %>% filter(rua == "AVENIDA DOS BANDEIRANTES") %>% pull(id) %>% .[1]
n.avenidas <- df.prep %>% distinct(id) %>% count() %>% as.numeric()
#Controle sintético BANDEIRANTES ----
dataprep_out <- Synth::dataprep(
foo = df.prep %>%
select(id, rua, ano, resposta = acidentes_hp) %>%
drop_na(),
predictors = c("resposta"),
special.predictors = list(list("resposta", seq(2019 + 1/12, 2020 + 1/12, by = 1/12) %>% round(3), "mean"),
list("resposta", seq(2020 + 1/12, 2021 + 1/12, by = 1/12) %>% round(3), "mean"),
list("resposta", seq(2021 + 1/12, 2022 + 1/12, by = 1/12) %>% round(3), "mean"),
list("resposta", seq(2022 + 1/12, 2022 + 10/12, by = 1/12) %>% round(3), "mean")),
time.predictors.prior = seq(2019 + 1/12, 2022 + 10/12, by = 1/12) %>% round(3),
predictors.op = "mean",
dependent = "resposta",
unit.variable = "id",
unit.names.variable = "rua",
time.variable = "ano",
treatment.identifier = id.tratamento,
controls.identifier = c(1:n.avenidas)[-id.tratamento],
time.optimize.ssr = seq(2019 + 1/12, 2022 + 10/12, by = 1/12) %>% round(3),
time.plot = seq(2019 + 1/12, 2023 + 12/12, by = 1/12) %>% round(3)
)
synth_out <- Synth::synth(data.prep.obj = dataprep_out)
## plot de comparação da Bandeirantes real e sintética
data.frame(sintetico = dataprep_out$Y0plot %*% synth_out$solution.w,
data = dataprep_out$tag$time.plot,
band = dataprep_out$Y1plot) %>%
as_tibble() %>%
select(data, bandeirantes = paste("X", id.tratamento, sep = ""), sintetico = w.weight) %>%
mutate(across(c(bandeirantes, sintetico), ~ .^2),
fill = data > 2022 + 10/12,
ymax = ifelse(fill == TRUE, bandeirantes, NA),
ymin = ifelse(fill == TRUE, sintetico, NA)) %>%
ggplot(aes(x = data)) +
annotate("rect", xmin = 2022 + 10/12, xmax = 2023 + 9/12, ymin = -Inf, ymax = Inf, fill = "black", alpha =.05) +
geom_line(aes(y = sintetico, linetype = "Sintético")) +
geom_line(aes(y = bandeirantes, linetype = "Observado")) +
geom_ribbon(aes(ymin = ymin, ymax = ymax), fill = "blue", alpha = .2) +
annotate("segment", x = 2022, y = 4.5, xend = 2022.6, yend = 4.5,
arrow = arrow(length = unit(0.01, "npc"))) +
annotate('text', x = 2021.6, y = 4.5,label = 'Faixa Azul', size = 3.5) +
geom_vline(xintercept = 2022 + 10/12, alpha = 1, linetype = "dotted") +
scale_linetype_manual(values = c("Sintético" = "dashed", "Observado" = "solid")) +
scale_y_continuous(limits = c(3,25), trans = "log10") +
labs(x = "Data", y = "Número de sinistros por mês", linetype = "") +
theme_classic() +
theme(legend.position = c(0.25,0.75))
ggsave("output/sintetico.png", dpi = 600, width = 5, height = 3.5)
ggsave("output/sintetico_wide.png", dpi = 600, width = 8, height = 4)
## plot de comparação da Bandeirantes real e sintética na diferença
data.frame(sintetico = dataprep_out$Y0plot %*% synth_out$solution.w,
data = dataprep_out$tag$time.plot,
band = dataprep_out$Y1plot) %>%
as_tibble() %>%
select(data, bandeirantes = paste("X", id.tratamento, sep = ""), sintetico = w.weight) %>%
mutate(across(c(bandeirantes, sintetico), ~ .^2),
fill = data > 2022 + 10/12,
ymax = ifelse(fill == TRUE, 0, NA),
ymin = ifelse(fill == TRUE, bandeirantes - sintetico, NA),
cor = ifelse(ymax > ymin, 0, 1)) %>%
ggplot(aes(x = data)) +
annotate("rect", xmin = 2022 + 10/12, xmax = 2023 + 11/12, ymin = -Inf, ymax = Inf, fill = "black", alpha =.05) +
geom_hline(yintercept = 0, linetype = "dashed") +
geom_line(aes(y = bandeirantes - sintetico)) +
geom_ribbon(aes(ymin = ymin, ymax = ymax, fill = factor(cor)), alpha = .2) +
annotate("segment", x = 2022, y = -2, xend = 2022.6, yend = -2,
arrow = arrow(length = unit(0.01, "npc"))) +
annotate('text', x = 2021.6, y = -2,label = 'Faixa Azul', size = 3.5) +
geom_vline(xintercept = 2022 + 10/12, alpha = 1, linetype = "dotted") +
labs(x = "Data", y = "Número de sinistros por mês", linetype = "") +
scale_fill_manual(values = c("0" = "blue", "1" = "red")) +
theme_classic() +
theme(legend.position = c(0.25,0.75)) +
ylim(c(-5,5)) +
guides(color=guide_legend("facotor(cor)"), fill = "none")
ggsave("output/sintetico_dif.png", dpi = 600, width = 5, height = 3.5)
ggsave("output/sintetico_dif_wide.png", dpi = 600, width = 8, height = 4)
#Número de sinistros pós tratamento
data.frame(sintetico = dataprep_out$Y0plot %*% synth_out$solution.w,
data = dataprep_out$tag$time.plot,
band = dataprep_out$Y1plot) %>%
as_tibble() %>%
select(data, bandeirantes = paste("X", id.tratamento, sep = ""), sintetico = w.weight) %>%
mutate(across(c(bandeirantes, sintetico), ~ .^2)) %>%
filter(data > 2022 + 10/12) %>%
summarize(sinistros_bandeirantes = sum(bandeirantes),
sinistros_sintetico = sum(sintetico)) %>%
mutate(diff = sinistros_bandeirantes - sinistros_sintetico,
variacao = diff / sinistros_bandeirantes)
### Tabela com os coeficientes de cada componente do controle sintetico
data.frame(list(rua = dataprep_out[["names.and.numbers"]][["unit.names"]][2:n.avenidas],
peso = synth_out[["solution.w"]] %>% round(4))) %>%
arrange(desc(w.weight)) %>%
head(12) %>%
summarize(sum(w.weight)) - 1
#Teste placebo ----
dataprep_out.placebo <- Synth::dataprep(
foo = df.prep %>%
select(id, rua, ano, resposta = acidentes_hp) %>%
drop_na(),
predictors = c("resposta"),
special.predictors = list(list("resposta", seq(2019 + 1/12, 2020 + 1/12, by = 1/12) %>% round(3), "mean"),
list("resposta", seq(2020 + 1/12, 2021 + 1/12, by = 1/12) %>% round(3), "mean"),
list("resposta", seq(2021 + 1/12, 2022 + 1/12, by = 1/12) %>% round(3), "mean"),
list("resposta", seq(2022 + 1/12, 2022 + 2/12, by = 1/12) %>% round(3), "mean")),
time.predictors.prior = seq(2019 + 1/12, 2022 + 2/12, by = 1/12) %>% round(3),
predictors.op = "mean",
dependent = "resposta",
unit.variable = "id",
unit.names.variable = "rua",
time.variable = "ano",
treatment.identifier = id.tratamento,
controls.identifier = c(1:n.avenidas)[-id.tratamento],
time.optimize.ssr = seq(2019 + 1/12, 2022 + 2/12, by = 1/12) %>% round(3),
time.plot = seq(2019 + 1/12, 2023 + 12/12, by = 1/12) %>% round(3)
)
synth_out.placebo <- Synth::synth(data.prep.obj = dataprep_out.placebo)
data.frame(sintetico = dataprep_out.placebo$Y0plot %*% synth_out.placebo$solution.w,
data = dataprep_out.placebo$tag$time.plot,
band = dataprep_out.placebo$Y1plot) %>%
as_tibble() %>%
select(data, bandeirantes = paste("X", id.tratamento, sep = ""), sintetico = w.weight) %>%
mutate(across(c(bandeirantes, sintetico), ~ .^2),
fill = data > 2022 + 2/12,
ymax = ifelse(fill == TRUE, bandeirantes, NA),
ymin = ifelse(fill == TRUE, sintetico, NA),
cor = ifelse(ymax > ymin, 1, 0)) %>%
ggplot(aes(x = data)) +
annotate("rect", xmin = 2022 + 10/12, xmax = 2023 + 12/12, ymin = 0, ymax = Inf, fill = "black", alpha =.05) +
annotate("rect", xmin = 2022 + 2/12, xmax = 2022 + 10/12, ymin = 0, ymax = Inf, fill = "orange", alpha =.05) +
geom_line(aes(y = sintetico, linetype = "Sintético")) +
geom_line(aes(y = bandeirantes, linetype = "Observado")) +
geom_vline(xintercept = 2022 + 10/12, alpha = 1, linetype = "dotted") +
geom_vline(xintercept = 2022 + 2/12, alpha = 1, linetype = "dotted") +
geom_ribbon(aes(ymin = ymin, ymax = ymax, fill = factor(cor)), alpha = .2) +
annotate("segment", x = 2023.3, y = 4.5, xend = 2023.3, yend = 3.5) +
annotate("segment", x = 2023.3, y = 3.5, xend = 2022.9, yend = 3.5,
arrow = arrow(length = unit(0.01, "npc"))) +
annotate('text', x = 2023.3, y = 5,label = 'Faixa Azul', size = 3.5) +
annotate("segment", x = 2021.4, y = 4.5, xend = 2022.1, yend = 4.5,
arrow = arrow(length = unit(0.01, "npc"))) +
annotate('text', x = 2021.05, y = 4.5,label = 'Placebo', size = 3.5) +
scale_linetype_manual(values = c("Sintético" = "dashed", "Observado" = "solid")) +
scale_y_continuous(limits = c(3,25), trans = "log10") +
labs(x = "Data", y = "Número de sinistros por mês", linetype = "") +
scale_fill_manual(values = c("0" = "blue", "1" = "red")) +
theme_classic() +
theme(legend.position = c(0.25,0.75)) +
guides(color=guide_legend("facotor(cor)"), fill = "none")
ggsave("output/placebo.png", dpi = 600, width = 5, height = 3.5)
ggsave("output/placebo_wide.png", dpi = 600, width = 8, height = 4)
data.frame(list(rua = dataprep_out.placebo[["names.and.numbers"]][["unit.names"]][2:n.avenidas],
peso = synth_out.placebo[["solution.w"]] %>% round(2))) %>%
arrange(desc(w.weight))
#Teste placebo "vassoura" ----
tdf <- SCtools::generate.placebos(dataprep_out, synth_out, Sigf.ipop = 1, strategy = "multisession")
tdf$t1 <- 2022 + 10/12
create.df <- function(tdf, mspe.limit){
n <- tdf$n
tr <- tdf$tr
names.and.numbers<-tdf$names.and.numbers
treated.name<-as.character(tdf$treated.name)
df.plot<-NULL
for(i in 1:n){
a<-cbind(tdf$df$year,tdf$df[,i],tdf$df[,n+i],i)
df.plot<-rbind(df.plot, a)
}
df.plot<-data.frame(df.plot)
colnames(df.plot)<-c('year','cont','tr','id')
df.plot<-df.plot[ ! df.plot$id %in% which(tdf$mspe.placs/tdf$loss.v[1] >= mspe.limit),]
return(df.plot)
}
create.df(tdf, mspe.limit = 20) %>%
as_tibble() %>%
ggplot(aes(x=year, y=(tr^2-cont^2)))+
geom_line(aes(group=id, color = "Controle"), lwd = 0.75)+
geom_vline(xintercept = 2022 + 9/12, linetype = "dotted") +
geom_hline(yintercept = 0, linetype = 'dashed')+
geom_line(data=data.frame(tdf$df), aes(x = year, y=(Y1^2-synthetic.Y1^2), color = "Bandeirantes"),
lwd = 0.75) +
ylim(c(-7.5,7.5)) +
scale_color_manual(values = c("Controle" = "#d3d3d3", "Bandeirantes" = "black")) +
labs(y="Número mensal de sinistros", x="Data", title = "", color = "") +
theme_classic()
ggsave("output/vassoura.png", dpi = 600, width = 9, height = 4)
(SCtools::mspe.test(tdf)$p.val * 100) %>% round(2)
(SCtools::mspe.test(tdf, discard.extreme = TRUE, mspe.limit = 20)$p.val * 100) %>% round(2)
(SCtools::mspe.test(tdf, discard.extreme = TRUE, mspe.limit = 10)$p.val * 100) %>% round(2)
(SCtools::mspe.test(tdf, discard.extreme = TRUE, mspe.limit = 3)$p.val * 100) %>% round(2)
p.values <- c()
for (mspe.limit in 1:40){
p.values <- append(p.values, c(SCtools::mspe.test(tdf, discard.extreme = TRUE, mspe.limit = mspe.limit)$p.val * 100))
}
create.df(tdf, mspe.limit = 10) %>%
as_tibble()
SCtools::mspe.test(tdf)$test %>%
as_tibble() %>%
select(avenida = "unit", ratio = "MSPE.ratios") %>%
arrange(desc(ratio))
gg <- SCtools::mspe.test(tdf, discard.extreme = TRUE, mspe.limit = 20)$test %>%
as_tibble() %>%
select(avenida = "unit", ratio = "MSPE.ratios") %>%
arrange(desc(ratio)) %>%
ggplot() +
geom_density(aes(x = ratio)) +
geom_vline(xintercept = 113) +
scale_x_log10()
g <- ggplot_build(gg)
tibble(x = g$data[[1]]$x, y = g$data[[1]]$y) %>%
mutate(ymax = ifelse(x > 2.05307, y, NA),
ymin = ifelse(x > 2.05307, 0, NA)) %>%
ggplot(aes(x = x, y = y)) +
geom_line() +
geom_vline(xintercept = 2.05307, linetype = "dotted") +
geom_ribbon(aes(ymin = ymin, ymax = ymax), alpha = .15, fill = "darkred") +
labs(y = "", x = "Log da razão de erro pré/pós tratamento") +
annotate("segment", x = 1.5, y = 0.1, xend = 2, yend = 0.1,
arrow = arrow(length = unit(0.01, "npc"))) +
annotate('text', x = 1, y = 0.1,label = 'Bandeirantes', size = 3.5) +
theme_classic()
SCtools::mspe.test(tdf)$test %>%
as_tibble() %>%
select(avenida = "unit", ratio = "MSPE.ratios") %>%
arrange(desc(ratio)) %>%
mutate(cor = ifelse(avenida != "AVENIDA DOS BANDEIRANTES", "Outras", "Bandeirantes")) %>%
ggplot() +
geom_histogram(aes(x = ratio, fill = cor), binwidth = 7.5) +
theme_classic() +
labs(x = "Razão MSPE Pós/Pré", y = "Frequência", fill = "Avenida") +
coord_flip() +
theme(legend.position = c(0.85, 0.85))
ggsave("output/histograma_ratio_flip.png", dpi = 600, width = 4, height = 5)
SCtools::mspe.test(tdf, discard.extreme = FALSE)$test %>%
as_tibble() %>%
select(avenida = "unit", ratio = "MSPE.ratios") %>%
arrange(desc(ratio)) %>%
mutate(cor = ifelse(avenida != "AVENIDA DOS BANDEIRANTES", "Outras", "Bandeirantes")) %>%
ggplot() +
geom_histogram(aes(x = ratio, fill = cor), binwidth = 7.5) +
theme_classic() +
labs(x = "Razão MSPE Pós/Pré", y = "Frequência", fill = "Avenida") +
theme(legend.position = c(0.85, 0.85))
ggsave("output/histograma_ratio.png", dpi = 600, width = 7, height = 3.5)