Dados

As principais fontes de dados foram:

População

data <- pe_dados %>% 
  filter(NM_MUN != 'Fernando de Noronha') %>% 
  mutate(name=factor(NM_MUN, unique(NM_MUN)),
         pop = população/1e6) %>% 
  arrange(pop)

# Criar cortes para escala de cor
cortes <- c(0, 0.01, .05,  .1, .5,  1, 1.5)

# Build the map
ggplot() +
  geom_sf(data = data, fill="grey", alpha=0.3, color = 'white') +
  geom_point(data = data, aes(x=longitude, y=latitude, size=pop, fill=pop, alpha=pop), shape=21, colour="black", stroke=1) +
  scale_size_continuous(name="População (em Milhões)", trans="log", 
                        range=c(.5,5), breaks=cortes) +
  scale_alpha_continuous(name="População (em Milhões)", trans="log", 
                         range=c(0.1, .95), breaks=cortes) +
  scale_fill_viridis(option="magma", trans="log",
                      breaks=cortes, name="População (em Milhões)" ) +
  theme_void() + 
  coord_sf() + 
  guides( fill = guide_legend()) +
  #ggtitle("População dos municípios de Pernambuco") +
  theme(legend.direction = "horizontal",
        legend.position = "bottom", #c(0.85, 0.8),
        text = element_text(color = "#22211d"),
        plot.background = element_rect(fill = "#f5f5f2", color = NA),
        panel.background = element_rect(fill = "#f5f5f2", color = NA),
        legend.background = element_rect(fill = "#f5f5f2", color = NA),
        #plot.title = element_text(size= 14, color = "#4e4d47", hjust=.5, vjust = 4,  margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
  )

data <- pe_dados %>% 
  filter(NM_MUN != 'Fernando de Noronha') %>% 
  mutate(name=factor(NM_MUN, unique(NM_MUN)),
         pop = população/1e6,
         scale = rescale((log(pop)), to = c(1500, 15000))) %>% 
  arrange(pop) %>% 
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade:</strong> ", name, "\n", 
    "</br><strong>População:</strong> ", format(população, decimal.mark = ",", big.mark = "."), sep="")
  ))


pal <- colorBin(viridis_pal(option = "magma")(6), data$scale, bins = rescale((log(cortes)), to = c(1500, 15000)))

caption <- tags$div(
             HTML('<span>População dos Municípios de Pernambuco</span>')
           )

data %>% 
  leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 2, color = "black", fillOpacity = 0) %>% 
  addCircles(lng = ~longitude, lat = ~latitude,
             radius = ~scale,
             fillColor = ~pal(scale),
             color = "black",
             stroke = TRUE,
             opacity = .3,
             weight = 2, 
             highlightOptions = highlightOptions(
               weight = 5,
               color = "black",
               dashArray = NULL,
               fillOpacity = 0.7,
               bringToFront = TRUE),
             fillOpacity = ~rescale(scale, to = c(.1, .9)),
             label = ~text,
             labelOptions = labelOptions(
               style = list("font-weight" = "normal", padding = "3px 8px"),
               textsize = "10pt",
               direction = "auto")) %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")

Nascimentos nos últimos 5 anos

library(ggrepel)
ggplot() + 
  geom_point(aes(x = população, y = demanda), data = transporte)  +
  geom_smooth(aes(x = população, y = demanda), data = transporte, method = "lm", formula = 'y ~ x') +
  geom_label_repel(aes(x = população, y = demanda, label = nome), 
                   data = transporte %>% filter(população > 150000), 
                   alpha = .9,
                   min.segment.length = 0) +
  theme_light() +
  labs(x = "População", y = "Média Mensal de Nascimentos") +
  ggtitle(label = "Demanda por local de residência")

Nascimentos em municípios que não residem.

data <- read_rds("../data/nascimento_outro_municipio.rds")

pal <- colorNumeric(viridis_pal(option = "magma")(10), data$scale)

caption <- tags$div(
             HTML('<span>Número de nascimentos de não residentes (externos)</span>')
           )

data %>%
  leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 2, color = "black", fillOpacity = 0) %>% 
  addCircles(lng = ~longitude, lat = ~latitude,
             radius = ~scale,
             fillColor = ~pal(scale),
             color = "black",
             stroke = TRUE,
             opacity = .3,
             weight = 2, 
             highlightOptions = highlightOptions(
               weight = 5,
               color = "black",
               dashArray = NULL,
               fillOpacity = 0.7,
               bringToFront = TRUE),
             fillOpacity = ~rescale(scale, to = c(.1, .9)),
             label = ~text,
             labelOptions = labelOptions(
               style = list("font-weight" = "normal", padding = "3px 8px"),
               textsize = "10pt",
               direction = "auto")) %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "topright")
breaks = c(0, 10000, 20000, 50000, 140000, 150000)
ggplot() +
    geom_sf(data = data %>% filter(NM_MUN != "Fernando de Noronha"), fill="grey", alpha=0.3, color = 'white') +
    geom_point(data = data %>% filter(NM_MUN != "Fernando de Noronha"), aes(x=longitude, y=latitude, size=externos, fill=externos, alpha=externos), shape=21, colour="black", stroke=1) +
    scale_size_continuous(name="Nascimentos externos", #trans="log", 
                          range=c(1,12), labels = comma, breaks = breaks) +
    scale_alpha_continuous(name="Nascimentos externos", #trans="log", 
                           range=c(0.4, .95), labels = comma, breaks = breaks) +
    scale_fill_gradient(low = "green", high = "red", name="Nascimentos externos", labels = comma, breaks = breaks) +
    theme_void() + 
    coord_sf() + 
    guides( fill = guide_legend()) +
    #ggtitle("População dos municípios de Pernambuco") +
    theme(legend.direction = "horizontal",
          legend.position = "bottom", #c(0.85, 0.8),
          text = element_text(color = "#22211d"),
          plot.background = element_rect(fill = "#f5f5f2", color = NA),
          panel.background = element_rect(fill = "#f5f5f2", color = NA),
          legend.background = element_rect(fill = "#f5f5f2", color = NA),
          #plot.title = element_text(size= 14, color = "#4e4d47", hjust=.5, vjust = 4,  margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm"))
    )

petrolina <- cost_linesf %>% 
  filter(Nome_origem == "Petrolina" | Nome_destino == "Petrolina") %>% 
  mutate(direção = if_else(Nome_origem == "Petrolina", "blue", "red")) %>% 
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade Origem:</strong> ", Nome_origem, 
    "</br><strong>Cidade destino:</strong> ", Nome_destino, 
    "</br><strong>Distância (Km):</strong> ", format(Distância/1000, decimal.mark = ",", big.mark = "."),
    "</br><strong>Nascimentos:</strong> ", format(Nascimentos, decimal.mark = ",", big.mark = "."),
    sep=""))) %>% 
  filter(Nascimentos >= 10)
 

data <- cost18a22 %>% 
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade Origem:</strong> ", município_origem, 
    "</br><strong>Cidade destino:</strong> ", município_destino, 
    "</br><strong>Distância (Km):</strong> ", format(Distância/1000, decimal.mark = ",", big.mark = ".", digits = 2),
    "</br><strong>Nascimentos:</strong> ", format(n, decimal.mark = ",", big.mark = "."),
    sep=""))) %>% 
  mutate(origem6 = str_sub(Origem, 1, 6),
         destino6 = str_sub(Destino, 1, 6)) %>% 
  left_join(pe_routes %>% 
              mutate(origem6 = str_sub(origem, 1, 6),
                     destino6 = str_sub(destino, 1, 6)), by = join_by(origem6, destino6)) %>% 
  st_as_sf() 

pals1 <- pals::brewer.set1(n=3)

caption <- tags$div(
  HTML('Nascimentos com origem ou destino em Petrolina</span>')
)


leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = petrolina, 
               weight = 2,
               color =  ~if_else(Nome_destino == "Petrolina", pals1[1], pals1[3]),
               label = ~text,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_origem,
                   lat = ~lat_origem,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~Nome_origem,
                   fillColor = ~if_else(Nome_destino == "Petrolina", pals1[1], pals1[3]),
                   data = petrolina %>% st_drop_geometry()) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_destino,
                   lat = ~lat_destino,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~Nome_destino,
                   fillColor = ~if_else(Nome_destino == "Petrolina", pals1[1], pals1[3]),
                   data = petrolina %>% st_drop_geometry() %>% filter(Nome_origem == "Petrolina")) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 8,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   fillColor = pals1[2],
                   data = pe_dados %>% st_drop_geometry() %>% filter(nome == "Petrolina"))  %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")
leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = data %>% 
                 filter(município_origem == "Petrolina" | município_destino == "Petrolina", 
                        n >= 5) , 
               weight = 2, opacity = .9,
               color =  ~if_else(município_destino == "Petrolina", pals1[1], pals1[3]),
               label = ~text,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_origem,
                   lat = ~lat_origem,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~município_origem,
                   fillColor = ~if_else(município_destino == "Petrolina", pals1[1], pals1[3]),
                   data = data %>% 
                     filter(município_origem == "Petrolina" | município_destino == "Petrolina", 
                            n >= 5) %>% 
                     st_drop_geometry()) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_destino,
                   lat = ~lat_destino,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~município_destino,
                   fillColor = ~if_else(município_origem == "Petrolina", pals1[1], pals1[3]),
                   data = data %>% 
                     filter(município_origem == "Petrolina" | município_destino == "Petrolina", 
                            n >= 5)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 8,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = pals1[2],
                   options = markerOptions(
                     zIndexOffset = 10000
                     ),
                   data = pe_dados %>% st_drop_geometry() %>% filter(nome == "Petrolina"))  %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")
caruaru <- cost_linesf %>% 
  filter(Nome_origem == "Caruaru" | Nome_destino == "Caruaru") %>% 
  mutate(direção = if_else(Nome_origem == "Caruaru", "blue", "red")) %>% 
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade Origem:</strong> ", Nome_origem, 
    "</br><strong>Cidade destino:</strong> ", Nome_destino, 
    "</br><strong>Distância (Km):</strong> ", format(Distância/1000, decimal.mark = ",", big.mark = "."),
    "</br><strong>Nascimentos:</strong> ", format(Nascimentos, decimal.mark = ",", big.mark = "."),
    sep=""))) %>% 
  filter(Nascimentos >= 10)
 

data <- cost18a22 %>% 
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade Origem:</strong> ", município_origem, 
    "</br><strong>Cidade destino:</strong> ", município_destino, 
    "</br><strong>Distância (Km):</strong> ", format(Distância/1000, decimal.mark = ",", big.mark = ".", digits = 2),
    "</br><strong>Nascimentos:</strong> ", format(n, decimal.mark = ",", big.mark = "."),
    sep=""))) %>% 
  mutate(origem6 = str_sub(Origem, 1, 6),
         destino6 = str_sub(Destino, 1, 6)) %>% 
  left_join(pe_routes %>% 
              mutate(origem6 = str_sub(origem, 1, 6),
                     destino6 = str_sub(destino, 1, 6)), by = join_by(origem6, destino6)) %>% 
  st_as_sf() 

pals1 <- pals::brewer.set1(n=3)

caption <- tags$div(
  HTML('Nascimentos com origem ou destino em Caruaru</span>')
)


leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = caruaru, 
               weight = 2,
               color =  ~if_else(Nome_destino == "Caruaru", pals1[1], pals1[3]),
               label = ~text,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_origem,
                   lat = ~lat_origem,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~Nome_origem,
                   fillColor = ~if_else(Nome_destino == "Caruaru", pals1[1], pals1[3]),
                   data = caruaru %>% st_drop_geometry()) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_destino,
                   lat = ~lat_destino,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~Nome_destino,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   fillColor = ~if_else(Nome_destino == "Caruaru", pals1[1], pals1[3]),
                   data = caruaru %>% st_drop_geometry() %>% filter(Nome_origem == "Caruaru")) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 8,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   options = markerOptions(
                     zIndexOffset = 10000
                     ),
                   fillColor = pals1[2],
                   data = pe_dados %>% st_drop_geometry() %>% filter(nome == "Caruaru"))  %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")
leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = data %>% 
                 filter(município_origem == "Caruaru" | município_destino == "Caruaru", 
                        n >= 5) , 
               weight = 2, opacity = .9,
               color =  ~if_else(município_destino == "Caruaru", pals1[1], pals1[3]),
               label = ~text,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_origem,
                   lat = ~lat_origem,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~município_origem,
                   fillColor = ~if_else(município_destino == "Caruaru", pals1[1], pals1[3]),
                   data = data %>% 
                     filter(município_origem == "Caruaru" | município_destino == "Caruaru", 
                            n >= 5) %>% 
                     st_drop_geometry()) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_destino,
                   lat = ~lat_destino,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~município_destino,
                   fillColor = ~if_else(município_origem == "Caruaru", pals1[1], pals1[3]),
                   data = data %>% 
                     filter(município_origem == "Caruaru" | município_destino == "Caruaru", 
                            n >= 5)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 8,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = pals1[2],
                   options = markerOptions(
                     zIndexOffset = 10000
                     ),
                   data = pe_dados %>% st_drop_geometry() %>% filter(nome == "Caruaru"))  %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")
recife <- cost_linesf %>% 
  filter(Nome_origem == "Recife" | Nome_destino == "Recife") %>% 
  mutate(direção = if_else(Nome_origem == "Recife", "blue", "red")) %>% 
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade Origem:</strong> ", Nome_origem, 
    "</br><strong>Cidade destino:</strong> ", Nome_destino, 
    "</br><strong>Distância (Km):</strong> ", format(Distância/1000, decimal.mark = ",", big.mark = "."),
    "</br><strong>Nascimentos:</strong> ", format(Nascimentos, decimal.mark = ",", big.mark = "."),
    sep=""))) %>% 
  filter(Nascimentos >= 10)
 

data <- cost18a22 %>%
   rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade Origem:</strong> ", município_origem, 
    "</br><strong>Cidade destino:</strong> ", município_destino, 
    "</br><strong>Distância (Km):</strong> ", format(Distância/1000, decimal.mark = ",", big.mark = ".", digits = 2),
    "</br><strong>Nascimentos:</strong> ", format(n, decimal.mark = ",", big.mark = "."),
    sep=""))) %>% 
  mutate(origem6 = str_sub(Origem, 1, 6),
         destino6 = str_sub(Destino, 1, 6)) %>% 
  left_join(pe_routes %>% 
              mutate(origem6 = str_sub(origem, 1, 6),
                     destino6 = str_sub(destino, 1, 6)), by = join_by(origem6, destino6)) %>% 
  st_as_sf() 

pals1 <- pals::brewer.set1(n=3)

caption <- tags$div(
  HTML('Nascimentos com origem ou destino em Recife</span>')
)


leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = recife, 
               weight = 2,
               color =  ~if_else(Nome_destino == "Recife", pals1[1], pals1[3]),
               label = ~text,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_origem,
                   lat = ~lat_origem,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~Nome_origem,
                   fillColor = ~if_else(Nome_destino == "Recife", pals1[1], pals1[3]),
                   data = recife %>% st_drop_geometry()) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_destino,
                   lat = ~lat_destino,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   options = markerOptions(
                     zIndexOffset = 1000
                     ),
                   label = ~Nome_destino,
                   fillColor = ~if_else(Nome_destino == "Recife", pals1[1], pals1[3]),
                   data = recife %>% st_drop_geometry() %>% filter(Nome_origem == "Recife")) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 8,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = pals1[2],
                   options = markerOptions(
                     zIndexOffset = 10000
                     ),
                   data = pe_dados %>% st_drop_geometry() %>% filter(nome == "Recife"))  %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")
leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = data %>% 
                 filter(município_origem == "Recife" | município_destino == "Recife", 
                        n >= 5) , 
               weight = 2, opacity = .9,
               color =  ~if_else(município_destino == "Recife", pals1[1], pals1[3]),
               label = ~text,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_origem,
                   lat = ~lat_origem,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~text,
                   fillColor = ~if_else(município_destino == "Recife", pals1[1], pals1[3]),
                   data = data %>% 
                     filter(município_origem == "Recife" | município_destino == "Recife", 
                            n >= 5) %>% 
                     st_drop_geometry()) %>% 
  addCircleMarkers(color = "black",
                   lng = ~long_destino,
                   lat = ~lat_destino,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~município_destino,
                   fillColor = ~if_else(município_origem == "Recife", pals1[1], pals1[3]),
                   data = data %>% 
                     filter(município_origem == "Recife" | município_destino == "Recife", 
                            n >= 5)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 8,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = pals1[2],
                   data = pe_dados %>% st_drop_geometry() %>% filter(nome == "Recife"))  %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")

Matriz de custo

A matriz de custo principal será a matriz de distäncia enrte as cidades de Pernambuco. A dimensão da matriz é \(185\times 185\).

costmatrix_table <- read_rds("../data/costtable_long.rds")

costmatrix_table %>% 
      arrange(Origem) %>% 
      select(Origem, Destino, `Distância (em Metros)` = Distäncia, Tempo = Tempo_Unidade) %>% 
      mutate(Tempo = str_replace(Tempo, pattern = "hours", replacement = "horas"),
             Tempo = str_replace(Tempo, pattern = "minutes", replacement = "minutos"),
             Tempo = str_replace(Tempo, pattern = "seconds", replacement = "segundos")) %>% 
      DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(#list(className = 'dt-left', targets = c(0,1)),
                                         list(className = 'dt-center', targets = c(0,1,2,3)),
                                         #list(className = 'dt-right', targets = c(8)),
                                         list(bSortable = TRUE, targets = 0:3) #,
                                         #list(visible = FALSE, targets = c(3, 8:9))
                       )#,
        #               rowCallback=JS(
        #                 'function(row,data) {                                                #              if($(row)["0"]["_DT_RowIndex"] % 2 <1)
        #                 $(row).css("background","#f2f9ec") //#e8f5e9
        #                 }')
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(3), digits = 0, dec.mark = ",", mark = ".")

Custo nos últimos 5 anos (2018 a 2022)

#cost18a22 <- read_rds("../data/cost18a22.rds")

cost18a22 %>% 
  arrange(-n) %>% 
  select(Origem = município_origem, Destino = município_destino, n, Distância) %>% 
  mutate(`Média Anual de Nascimentos` = n/5) %>% 
  rename(`Nascimentos` =  n) %>% 
        DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(#list(className = 'dt-left', targets = c(0,1)),
                                         list(className = 'dt-center', targets = c(0,1,2,3,4)),
                                         #list(className = 'dt-right', targets = c(8)),
                                         list(bSortable = TRUE, targets = 0:4) #,
                                         #list(visible = FALSE, targets = c(3, 8:9))
                       )#,
        #               rowCallback=JS(
        #                 'function(row,data) {                                                #              if($(row)["0"]["_DT_RowIndex"] % 2 <1)
        #                 $(row).css("background","#f2f9ec") //#e8f5e9
        #                 }')
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(3,4,5), digits = 0, dec.mark = ",", mark = ".")
value_box(
  title = "Verificar", 
  theme_color = "warning",
  value = "Natimortos entram na base do SINASC?",
  showcase = bs_icon("patch-question"),
  p("André Leite", bs_icon("emoji-smile"))
)
Verificar Natimortos entram na base do SINASC?

André Leite

Nascimento por Estabelecimento

estab_nascimento <- read_rds("../data/estab_nascimento.rds")

data <- estab_nascimento %>% 
    left_join(pe_dados %>% 
                st_drop_geometry() %>% 
                select(ibge = CD_MUN, Município = NM_MUN) %>% 
                mutate(ibge = str_sub(ibge, 1, 6)), 
              by = join_by(ibge)) %>% 
  mutate(Ordem = row_number()) 

data %>%   select(Ordem,
         Nome = nome,
         Nascimentos = n,
         Município,
         `Proporção` = prop,
         Acumulado = acumulado) %>% 
     DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(list(className = 'dt-left', targets = c(0)),
                                         list(className = 'dt-center', targets = 1:5),
                                         list(bSortable = TRUE, targets = 0:5) #,
                                         #list(visible = FALSE, targets = c(3, 8:9))
                       )#,
        #               rowCallback=JS(
        #                 'function(row,data) {                                                #              if($(row)["0"]["_DT_RowIndex"] % 2 <1)
        #                 $(row).css("background","#f2f9ec") //#e8f5e9
        #                 }')
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatPercentage(columns = c(5,6))
breaks = c(0, 5000, 10000, 20000, 30000, 40000)

ggplot() +
    geom_sf(data = pe_limits, fill="grey", alpha=0.3, color = 'white') +
    geom_point(data = data %>% 
                 filter(`Município` != "Fernando de Noronha") %>% 
                 mutate(longitude = as.numeric(longitude),
                        latitude = as.numeric(latitude)) %>% 
                 filter((!is.na(latitude))|(!is.na(longitude))) %>% 
                 arrange(n), 
               aes(x=longitude, 
                   y=latitude, 
                   size=n, fill=n, alpha=n), 
               shape=21, colour="black", stroke=1) +
    scale_size_continuous(name="Nascimentos", #trans="log", 
                          range=c(1,12), labels = comma, breaks = breaks) +
    scale_alpha_continuous(name="Nascimentos", #trans="log", 
                           range=c(0.25, .95), labels = comma, breaks = breaks) +
    scale_fill_gradient(low = "green", high = "red", name="Nascimentos", labels = comma, breaks = breaks) +
    theme_void() + 
    coord_sf() + 
    guides( fill = guide_legend()) +
    #ggtitle("População dos municípios de Pernambuco") +
    theme(legend.direction = "horizontal",
          legend.position = "bottom", #c(0.85, 0.8),
          text = element_text(color = "#22211d"),
          plot.background = element_rect(fill = "#f5f5f2", color = NA),
          panel.background = element_rect(fill = "#f5f5f2", color = NA),
          legend.background = element_rect(fill = "#f5f5f2", color = NA),
          #plot.title = element_text(size= 14, color = "#4e4d47", hjust=.5, vjust = 4,  margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm"))
    )

pal <- colorNumeric(viridis_pal(option = "magma")(10), data$n)

caption <- tags$div(
             HTML('<span>Número de nascimentos por Estabelecimento</span>')
           )

data %>% 
  mutate(longitude = as.numeric(longitude),
  latitude = as.numeric(latitude)) %>% 
  filter((!is.na(latitude))|(!is.na(longitude))) %>% 
  arrange(n) %>%   
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Município:</strong> ", Município, "\n", 
    "</br><strong>Estabelecimento:</strong> ", nome,
    "</br><strong>Nascimentos:</strong> ", format(n, decimal.mark = ",", big.mark = "."), 
    "</br><strong>Proporção:</strong> ", format(prop, decimal.mark = ",", big.mark = ".", digits = 2),
    sep=""))) %>% 
  leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 2, color = "black", fillOpacity = 0) %>% 
  addCircleMarkers(lng = ~longitude, lat = ~latitude,
             radius = ~rescale(n, to = c(2, 15)),
             fillColor = ~pal(n),
             color = "black",
             stroke = TRUE,
             opacity = .3,
             weight = 2, 
             # highlightOptions = highlightOptions(
             #   weight = 5,
             #   color = "black",
             #   dashArray = NULL,
             #   fillOpacity = 0.7,
             #   bringToFront = TRUE),
             fillOpacity = ~rescale(n, to = c(.1, .9)),
             label = ~text,
             labelOptions = labelOptions(
               style = list("font-weight" = "normal", padding = "3px 8px"),
               textsize = "10pt",
               direction = "auto")) %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "topright")

Leitos Obstétricos

monnb <- function(d) { 
  lt <- as.POSIXlt(as.Date(d, origin="1900-01-01"))
  lt$year*12 + lt$mon 
} 

nascimentos <- read_rds("../data/nasc5a.rds") 
leitos <- read_parquet("../data/leitos_pe.parquat")
  
data <- nascimentos %>% 
  filter(str_sub(CODMUNNASC , 1, 2) == "26") %>% 
  group_by(CODMUNNASC) %>% 
  summarise(Nascimentos = n(), 
            Fim = max(date, na.rm = TRUE), 
            Inicio  = min(date, na.rm = TRUE)) %>% 
  mutate(Amplitude_dias = Fim - Inicio,
         Amplitude_meses = monnb(Fim) -monnb(Inicio),
         `Média Diária` = ceiling(Nascimentos/as.numeric(Amplitude_dias)),
         `Média Mensal` = ceiling(Nascimentos/as.numeric(Amplitude_meses))) %>% 
  left_join(leitos, by = c("CODMUNNASC" = "ibge")) %>% 
  filter(!is.na(Município)) %>% 
  arrange(-Obstétrico) %>% rename(Pedriátrico = Pediátrico) %>% 
  select(-Inicio, -Fim, -Amplitude_dias, -Amplitude_meses) %>% 
  filter(!is.na(Pedriátrico))


data %>%   
  select(Município,
         Nascimentos,
         `Média Diária`,
         `Média Mensal`,
         `Leitos Obstétricos` = Obstétrico,
         `Total de Leitos` = Total) %>% 
     DT::datatable(
        rownames = TRUE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(list(className = 'dt-left', targets = c(1)),
                                         list(className = 'dt-center', targets = c(0, 2:6)),
                                         list(bSortable = TRUE, targets = 0:6) 
                       )
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
  formatRound(columns = c(2:6), mark = ".", dec.mark = ",", digits = 0) 

Modelo inicial: o problema das \(p\) medianas

Procura-se determinar os locais de \(p\) instalações (denominadas medianas) em uma rede de \(n\) nós, de modo a minimizar a soma das distâncias entre cada nó de demanda e a mediana mais próxima.

Considere o seguinte modelo de programação binária em que

\[ \text{Minimizar} \sum_{i = 1}^n\sum_{j = 1}^n c_{ij}\cdot x_{ij} \]

Sujeito a:

\[ \begin{align*} \text{R1:}&\qquad \sum_{j = 1}^n x_{ij} = 1,\text{ para todo }j, \\ \text{R2:}&\qquad \sum_{j = 1}^n y_j = p, \\ \text{R3:}&\qquad x_{i,j} \leqslant y_j,\text{ para todo }j, \\ \end{align*} \]

Note que a função objetivo é a distântia total a ser percorrida e as restrições \(\text{R1}\), \(\text{R2}\) , \(\text{R3}\) garantem que:

Solução para Pernambuco

if(.Platform$OS.type == "unix") {
  result <- system('/home/leite/ampl/ampl ../glpk/Modelo_1a.run', intern = TRUE)
} else {
  if (!stringr::str_detect(Sys.getenv("PATH"), "ampl\\.mswin64"))
    Sys.setenv(PATH = paste0(Sys.getenv("PATH"),";C:\\Users\\andre.leite\\Desktop\\ampl.mswin64"))
  result <- system('ampl ../glpk/Modelo_1a.run', intern = TRUE)
}

model_stats <- read_csv("../glpk/Modelo_1_stats.csv", show_col_types = FALSE)
  • Software: HiGHS 1.5.1
  • Status: ótimo encontrado
  • Número de iterações: 5.122
  • Objetivo: 13.042Km
  • Número de Variáveis: 34.410
  • Número de Restrições: 34.411
  • Tempo de execução: 1,23 segundos
x <- read_delim("../glpk/Modelo_1_x.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Origem = col_character(), 
                                 Destino = col_character()))

y <- read_delim("../glpk/Modelo_1_y.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Cidade = col_character()))



xsf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  left_join(x, by = c("ibge6" = "Origem")) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(ibge6, nome_destino = nome, latitude_destino = latitude, longitude_destino = longitude), 
                     by = c("Destino" = "ibge6")
            )


xsf_routes <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(origem6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, origem6, nome, latitude, longitude) %>% 
  left_join(x, by = c("origem6" = "Origem")) %>% 
  rename(destino6 = Destino) %>% 
  left_join(pe_routes %>% 
              mutate(origem6 = str_sub(origem, 1, 6),
                     destino6 = str_sub(destino, 1, 6)), by = join_by(origem6, destino6)) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(destino6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(destino6, nome_destino = nome, 
                     latitude_destino = latitude, 
                     longitude_destino = longitude), 
            by = "destino6") %>% 
  st_as_sf() 



pal <- colorFactor("Set1", xsf$nome_destino)


ysf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  filter(ibge6 %in% y$Cidade)


xsf_lines <- xsf %>% 
  group_split(nome, nome_destino) %>%
  map_df(.x = ., 
         
         .f = function(x) tibble(ibge = x$ibge, nome = x$nome, nome_destino = x$nome_destino, 
                                 long = c(x$longitude, x$longitude_destino), 
                                 lat = c(x$latitude, x$latitude_destino))) %>% 
  st_as_sf(coords = c("long", "lat"), crs = 4326) %>% 
  dplyr::group_by(nome, nome_destino) %>%
  dplyr::summarize(.groups = "drop", 
                   do_union = FALSE) %>%
  st_cast("LINESTRING") 


leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_lines, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")
leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_routes, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")

Distâncias médias e maiores distâncias percoridas para cada instalação

distancias <- read_rds("../data/costmatrix_table.rds")

x %>% left_join(distancias %>% mutate(Origem  = str_sub(Origem,  1,6),
                                      Destino = str_sub(Destino, 1,6)),
                join_by(Origem, Destino)) %>% 
  filter(!is.na(Distância)) %>% 
  group_by(município_destino) %>% 
  summarise(`Distância Média (Km)` = mean(Distância)/1000,
            `Distância Máxima (Km)` = max(Distância)/1000) %>% 
  rename(Cidade = município_destino) %>% 
   DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       dom = 't',
                       pageLength = 10,
                       columnDefs = list(list(className = 'dt-left', targets = c(0)),
                                         list(className = 'dt-center', targets = c(1,2)),
                                         list(bSortable = TRUE, targets = 0:2)
                       )
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(2:3), digits = 0, dec.mark = ",", mark = ".")

Modelo com ponderação da demanda

Considera-se agora o modelo anterior com a inclusão de uma demanda específica de cada nó, proporcional a sua população, nese caso, o número médio de nascimentos por mês. Neste caso, cada nascimento seria uma viajem e deseja-se minimizar a distância percorrida total dentro de uma mês. Sendo a demanda de cada nó \(\delta_i\), o novo problema é:

\[ \text{Minimizar} \sum_{i = 1}^n \sum_{j = 1}^n \delta_i\cdot c_{ij}\cdot x_{ij} \]

Sujeito às mesmas restrições anteriores.

value_box(
  title = "Verificar", 
  theme_color = "warning",
  value = "Considerar expoentes para a demanda e distância como forma de ponderação.",
  showcase = bs_icon("patch-question"),
  p("André Leite", bs_icon("emoji-smile"))
)
Verificar Considerar expoentes para a demanda e distância como forma de ponderação.

André Leite

Solução para Pernambuco

  • Software: HiGHS 1.5.1
  • Status: ótimo encontrado
  • Número de iterações: 5.769
  • Objetivo: 24.279Km
  • Número de Variáveis: 34.040
  • Número de Restrições: 34.041
  • Tempo de execução: 1,28 segundos
x <- read_delim("../glpk/Modelo_2_x.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Origem = col_character(), 
                                 Destino = col_character()))

y <- read_delim("../glpk/Modelo_2_y.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Cidade = col_character()))




xsf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  left_join(x, by = c("ibge6" = "Origem")) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(ibge6, nome_destino = nome, latitude_destino = latitude, longitude_destino = longitude), 
                     by = c("Destino" = "ibge6")
            )

xsf_routes <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(origem6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, origem6, nome, latitude, longitude) %>% 
  left_join(x, by = c("origem6" = "Origem")) %>% 
  rename(destino6 = Destino) %>% 
  left_join(pe_routes %>% 
              mutate(origem6 = str_sub(origem, 1, 6),
                     destino6 = str_sub(destino, 1, 6)), by = join_by(origem6, destino6)) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(destino6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(destino6, nome_destino = nome, 
                     latitude_destino = latitude, 
                     longitude_destino = longitude), 
            by = "destino6") %>% 
  st_as_sf(crs = '+proj=longlat +datum=WGS84')

pal <- colorFactor("Set1", xsf$nome_destino)

ysf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  filter(ibge6 %in% y$Cidade)


xsf_lines <- xsf %>% 
  group_split(nome, nome_destino) %>%
  map_df(.x = ., 
         
         .f = function(x) tibble(ibge = x$ibge, nome = x$nome, nome_destino = x$nome_destino, 
                                 long = c(x$longitude, x$longitude_destino), 
                                 lat = c(x$latitude, x$latitude_destino))) %>% 
  st_as_sf(coords = c("long", "lat"), crs = 4326) %>% 
  dplyr::group_by(nome, nome_destino) %>%
  dplyr::summarize(.groups = "drop", 
                   do_union = FALSE) %>%
  st_cast("LINESTRING") 


leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_lines, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")
leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_routes, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")

Distâncias médias e maiores distâncias percoridas para cada instalação

x %>% left_join(distancias %>% mutate(Origem  = str_sub(Origem,  1,6),
                                      Destino = str_sub(Destino, 1,6)),
                join_by(Origem, Destino)) %>% 
  filter(!is.na(Distância)) %>% 
  group_by(município_destino) %>% 
  summarise(`Distância Média (Km)` = mean(Distância)/1000,
            `Distância Máxima (Km)` = max(Distância)/1000) %>% 
  rename(Cidade = município_destino) %>% 
   DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       dom = 't',
                       pageLength = 10,
                       columnDefs = list(list(className = 'dt-left', targets = c(0)),
                                         list(className = 'dt-center', targets = c(1,2)),
                                         list(bSortable = TRUE, targets = 0:2)
                       )
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(2:3), digits = 0, dec.mark = ",", mark = ".")

Instância com 7 instalações

  • Software: HiGHS 1.5.1
  • Status: ótimo encontrado
  • Número de iterações: 4.083
  • Objetivo: 19.070Km
  • Número de Variáveis: 34.040
  • Número de Restrições: 34.041
  • Tempo de execução: 1,23 segundos
x <- read_delim("../glpk/Modelo_2b_x.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Origem = col_character(), 
                                 Destino = col_character()))

y <- read_delim("../glpk/Modelo_2b_y.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Cidade = col_character()))




xsf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  left_join(x, by = c("ibge6" = "Origem")) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(ibge6, nome_destino = nome, latitude_destino = latitude, longitude_destino = longitude), 
                     by = c("Destino" = "ibge6")
            )


xsf_routes <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(origem6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, origem6, nome, latitude, longitude) %>% 
  left_join(x, by = c("origem6" = "Origem")) %>% 
  rename(destino6 = Destino) %>% 
  left_join(pe_routes %>% 
              mutate(origem6 = str_sub(origem, 1, 6),
                     destino6 = str_sub(destino, 1, 6)), by = join_by(origem6, destino6)) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(destino6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(destino6, nome_destino = nome, 
                     latitude_destino = latitude, 
                     longitude_destino = longitude), 
            by = "destino6") %>% 
  st_as_sf(crs = '+proj=longlat +datum=WGS84')

pal <- colorFactor("Set1", xsf$nome_destino)

ysf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  filter(ibge6 %in% y$Cidade)


xsf_lines <- xsf %>% 
  group_split(nome, nome_destino) %>%
  map_df(.x = ., 
         
         .f = function(x) tibble(ibge = x$ibge, nome = x$nome, nome_destino = x$nome_destino, 
                                 long = c(x$longitude, x$longitude_destino), 
                                 lat = c(x$latitude, x$latitude_destino))) %>% 
  st_as_sf(coords = c("long", "lat"), crs = 4326) %>% 
  dplyr::group_by(nome, nome_destino) %>%
  dplyr::summarize(.groups = "drop", 
                   do_union = FALSE) %>%
  st_cast("LINESTRING") 


leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_lines, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")
leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_routes, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")

Distâncias médias e maiores distâncias percoridas para cada instalação

x %>% left_join(distancias %>% mutate(Origem  = str_sub(Origem,  1,6),
                                      Destino = str_sub(Destino, 1,6)),
                join_by(Origem, Destino)) %>% 
  filter(!is.na(Distância)) %>% 
  group_by(município_destino) %>% 
  summarise(`Distância Média (Km)` = mean(Distância)/1000,
            `Distância Máxima (Km)` = max(Distância)/1000) %>% 
  rename(Cidade = município_destino) %>% 
   DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       dom = 't',
                       pageLength = 10,
                       columnDefs = list(list(className = 'dt-left', targets = c(0)),
                                         list(className = 'dt-center', targets = c(1,2)),
                                         list(bSortable = TRUE, targets = 0:2)
                       )
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(2:3), digits = 0, dec.mark = ",", mark = ".")

Modelo com limite de distância

Seja \(\ell\) o valor da distância máxima desejada entre uma cidade e a instalação mais próxima e \(c_{ij}\) distância entre as cidades \(i\) e \(j\). Para satisfazer essa restrição devemos acrescentar a seguinte inequação no modelo:

\[ \text{R4:}\qquad c_{ij}\cdot x_{i,j} \leqslant \ell,\text{ para todo }i,j. \]

Considerado o limite de 150Km, tem-se o seguind resultado:

x <- read_delim("../glpk/Modelo_3_x.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Origem = col_character(), 
                                 Destino = col_character()))

y <- read_delim("../glpk/Modelo_3_y.csv", delim = ";", 
                escape_double = FALSE, trim_ws = TRUE,
                col_types = cols(Cidade = col_character()))




xsf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  left_join(x, by = c("ibge6" = "Origem")) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(ibge6, nome_destino = nome, latitude_destino = latitude, longitude_destino = longitude), 
                     by = c("Destino" = "ibge6")
            )

xsf_routes <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(origem6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, origem6, nome, latitude, longitude) %>% 
  left_join(x, by = c("origem6" = "Origem")) %>% 
  rename(destino6 = Destino) %>% 
  left_join(pe_routes %>% 
              mutate(origem6 = str_sub(origem, 1, 6),
                     destino6 = str_sub(destino, 1, 6)), by = join_by(origem6, destino6)) %>% 
  left_join(pe_dados %>% 
              st_drop_geometry() %>% 
              mutate(destino6 = str_sub(CD_MUN, 1, 6)) %>% 
              select(destino6, nome_destino = nome, 
                     latitude_destino = latitude, 
                     longitude_destino = longitude), 
            by = "destino6") %>% 
  st_as_sf()


pal <- colorFactor("Set1", xsf$nome_destino)

ysf <- pe_dados %>% 
  st_drop_geometry() %>% 
  filter(nome != "Fernando de Noronha") %>% 
  mutate(ibge6 = str_sub(CD_MUN, 1, 6)) %>% 
  select(ibge = CD_MUN, ibge6, nome, latitude, longitude) %>% 
  filter(ibge6 %in% y$Cidade)


xsf_lines <- xsf %>% 
  group_split(nome, nome_destino) %>%
  map_df(.x = ., 
         
         .f = function(x) tibble(ibge = x$ibge, nome = x$nome, nome_destino = x$nome_destino, 
                                 long = c(x$longitude, x$longitude_destino), 
                                 lat = c(x$latitude, x$latitude_destino))) %>% 
  st_as_sf(coords = c("long", "lat"), crs = 4326) %>% 
  dplyr::group_by(nome, nome_destino) %>%
  dplyr::summarize(.groups = "drop", 
                   do_union = FALSE) %>%
  st_cast("LINESTRING") 


leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_lines, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")
leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 4, color = "black", fillOpacity = 0) %>% 
  addPolylines(data = xsf_routes, 
               weight = 2,
               color =  ~pal(nome_destino),
               label = ~nome,
               highlightOptions = highlightOptions(
                 weight = 7,
                 color = "black",
                 dashArray = NULL,
                 fillOpacity = 0.7,
                 bringToFront = TRUE)) %>% 
  addCircleMarkers(color = "black",
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 2, 
                   radius = 3,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome_destino), 
                   data = xsf) %>% 
  addCircleMarkers(color = ~pal(nome),
                   lng = ~longitude,
                   lat = ~latitude,
                   weight = 4, 
                   radius = 6,
                   opacity = 1,
                   fillOpacity = 1,
                   label = ~nome,
                   fillColor = ~pal(nome), 
                   data = ysf) %>% 
  addLegend(pal = pal,
            values = ~nome, 
            data = ysf, position = "topright",
            opacity = 1,title = "Centros")

Distâncias médias e maiores distâncias percoridas para cada instalação

x %>% left_join(distancias %>% mutate(Origem  = str_sub(Origem,  1,6),
                                      Destino = str_sub(Destino, 1,6)),
                join_by(Origem, Destino)) %>% 
  filter(!is.na(Distância)) %>% 
  group_by(município_destino) %>% 
  summarise(`Distância Média (Km)` = mean(Distância)/1000,
            `Distância Máxima (Km)` = max(Distância)/1000) %>% 
  rename(Cidade = município_destino) %>% 
   DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       dom = 't',
                       pageLength = 10,
                       columnDefs = list(list(className = 'dt-left', targets = c(0)),
                                         list(className = 'dt-center', targets = c(1,2)),
                                         list(bSortable = TRUE, targets = 0:2)
                       )
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(2:3), digits = 0, dec.mark = ",", mark = ".")


Modelo com limite de capacidade

Vamos considerar agora a quantidade de leitos obstétricos e colocar estes como limites para atentidimento.