# Carpeta de trabajo
setwd("Z:/Grupos/IDE/GR14MIM/176_SESION_CARTOGRAFIA")

# Libreria analisis espacial
library(sf)
## Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
# Libreria Data Frame
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# Carga de SS.CC.
SSCC <- st_read("DESCARGAS/SECC_CE_20230101.shp")
## Reading layer `SECC_CE_20230101' from data source 
##   `Z:\Grupos\IDE\GR14MIM\176_SESION_CARTOGRAFIA\DESCARGAS\SECC_CE_20230101.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 36462 features and 16 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -1004502 ymin: 3132130 xmax: 1126932 ymax: 4859240
## Projected CRS: ETRS89 / UTM zone 30N
head(SSCC)
## Simple feature collection with 6 features and 16 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 496339.8 ymin: 4737085 xmax: 543234.1 ymax: 4768804
## Projected CRS: ETRS89 / UTM zone 30N
##        CUSEC CUMUN CSEC CDIS CMUN CPRO CCA   CUDIS CLAU2        NPRO        NCA
## 1 0100101001 01001  001   01  001   01  16 0100101 01001 Araba/Álava País Vasco
## 2 0100101002 01001  002   01  001   01  16 0100101 01001 Araba/Álava País Vasco
## 3 0100201001 01002  001   01  002   01  16 0100201 01002 Araba/Álava País Vasco
## 4 0100201002 01002  002   01  002   01  16 0100201 01002 Araba/Álava País Vasco
## 5 0100201003 01002  003   01  002   01  16 0100201 01002 Araba/Álava País Vasco
## 6 0100201004 01002  004   01  002   01  16 0100201 01002 Araba/Álava País Vasco
##   CNUT0 CNUT1 CNUT2 CNUT3             NMUN                       geometry
## 1    ES     2     1     1 Alegría-Dulantzi MULTIPOLYGON (((539753 4743...
## 2    ES     2     1     1 Alegría-Dulantzi MULTIPOLYGON (((539559.7 47...
## 3    ES     2     1     1          Amurrio MULTIPOLYGON (((503618.6 47...
## 4    ES     2     1     1          Amurrio MULTIPOLYGON (((505948.3 47...
## 5    ES     2     1     1          Amurrio MULTIPOLYGON (((499919.5 47...
## 6    ES     2     1     1          Amurrio MULTIPOLYGON (((500127.9 47...
# Capa de Municipios
Municipios <- SSCC %>%
  group_by(CUMUN,NMUN) %>%
  summarise() %>%
  mutate(area=as.numeric(st_area(geometry)))
## `summarise()` has grouped output by 'CUMUN'. You can override using the
## `.groups` argument.
head(Municipios)
## Simple feature collection with 6 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 485212.1 ymin: 4725226 xmax: 543234.1 ymax: 4778871
## Projected CRS: ETRS89 / UTM zone 30N
## # A tibble: 6 × 4
## # Groups:   CUMUN [6]
##   CUMUN NMUN                                                     geometry   area
##   <chr> <chr>                                          <MULTIPOLYGON [m]>  <dbl>
## 1 01001 Alegría-Dulantzi    (((538082.6 4741170, 538092 4741150, 538092.… 1.99e7
## 2 01002 Amurrio             (((503623 4759535, 503623.3 4759533, 503624.… 9.60e7
## 3 01003 Aramaio             (((538451.2 4766641, 538453.7 4766633, 53845… 7.35e7
## 4 01004 Artziniega          (((491147.6 4776743, 491147.2 4776735, 49115… 2.73e7
## 5 01006 Armiñón             (((511054.1 4731637, 511056.3 4731634, 51164… 1.28e7
## 6 01008 Arratzua-Ubarrundia (((533035.8 4757979, 533099.5 4757846, 53323… 5.75e7
# Datos Poblacion
Padron <- read.csv2("DESCARGAS/29005.csv",sep=";",dec=".")
Padron$Total <- gsub("\\.","",Padron$Total)
Padron <- Padron %>%
  mutate(CPRO=substr(Municipios, 1,2),CUMUN=substr(Municipios, 1,5),Total=as.numeric(Total)) %>%
  select(CPRO,CUMUN,Total)
head(Padron)
##   CPRO CUMUN Total
## 1   44 44001    70
## 2   40 40001   859
## 3   10 10001   338
## 4   27 27001  2203
## 5   48 48001  7708
## 6   31 31001    82
# Union Alfanumerica
unionAlfa <- inner_join(Municipios,Padron,by="CUMUN")

# Area
unionAlfa <- unionAlfa %>%
  mutate(densidad=Total/area)

# Libreria Mapas
library(ggplot2)

# Mapa
unionAlfaSelec <- unionAlfa %>%
  filter(CPRO==28)

ggplot() +
geom_sf(data=unionAlfaSelec,aes(fill=densidad)) +
scale_fill_continuous(type = "gradient",breaks=seq(min(unionAlfaSelec$densidad),max(unionAlfaSelec$densidad),length.out = 10))

# Catastro Madrid
Direcciones <- st_read("DESCARGAS/A.ES.SDGC.AD.28900.gml")
## Multiple layers are present in data source Z:\Grupos\IDE\GR14MIM\176_SESION_CARTOGRAFIA\DESCARGAS\A.ES.SDGC.AD.28900.gml, reading layer `Address'.
## Use `st_layers' to list all layer names and their type in a data source.
## Set the `layer' argument in `st_read' to read a particular layer.
## Warning in CPL_read_ogr(dsn, layer, query, as.character(options), quiet, :
## automatically selected the first layer in a data source containing more than
## one.
## Reading layer `Address' from data source 
##   `Z:\Grupos\IDE\GR14MIM\176_SESION_CARTOGRAFIA\DESCARGAS\A.ES.SDGC.AD.28900.gml' 
##   using driver `GML'
## Simple feature collection with 164867 features and 11 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: 429026.6 ymin: 4463622 xmax: 455986.8 ymax: 4497064
## Projected CRS: ETRS89 / UTM zone 30N
# Funcion Union Espacial
UnionEspacial <- function(puntos,poligonos) {
  Resultado <- as.data.frame(st_intersects(puntos,poligonos))
  puntos <- puntos %>%
    mutate(row.id=1:nrow(puntos))
  poligonos <- poligonos %>%
    mutate(col.id=1:nrow(poligonos))
  Resultado <- inner_join(Resultado,puntos,by="row.id")
  Resultado <- inner_join(Resultado,poligonos,by="col.id")
  Resultado <- Resultado %>%
    select(-row.id,-col.id,-geometry.y)
  return(Resultado)
}

SSCCMadrid <- SSCC %>%
  filter(CPRO==28) %>%
  group_by(CUDIS) %>%
  summarise()

unionEspa <- UnionEspacial(Direcciones,SSCCMadrid)
head(unionEspa)
##                                   gml_id                     localId  namespace
## 1  ES.SDGC.AD.28.900.10.1.1730101VK4813B  28.900.10.1.1730101VK4813B ES.SDGC.AD
## 2 ES.SDGC.AD.28.900.10.10.1630113VK4813B 28.900.10.10.1630113VK4813B ES.SDGC.AD
## 3 ES.SDGC.AD.28.900.10.12.1630114VK4813B 28.900.10.12.1630114VK4813B ES.SDGC.AD
## 4  ES.SDGC.AD.28.900.10.3.1730101VK4813B  28.900.10.3.1730101VK4813B ES.SDGC.AD
## 5  ES.SDGC.AD.28.900.10.6.1630111VK4813B  28.900.10.6.1630111VK4813B ES.SDGC.AD
## 6  ES.SDGC.AD.28.900.10.8.1630112VK4813B  28.900.10.8.1630112VK4813B ES.SDGC.AD
##   specification      method default designator type     level validFrom
## 1      Entrance fromFeature    TRUE          1    1 siteLevel      <NA>
## 2      Entrance fromFeature    TRUE         10    1 siteLevel      <NA>
## 3      Entrance fromFeature    TRUE         12    1 siteLevel      <NA>
## 4        Parcel fromFeature    TRUE          3    1 siteLevel      <NA>
## 5      Entrance fromFeature    TRUE          6    1 siteLevel      <NA>
## 6      Entrance fromFeature    TRUE          8    1 siteLevel      <NA>
##   beginLifespanVersion               geometry.x   CUDIS
## 1  2003-01-14T00:00:00 POINT (441569.8 4482828) 2807908
## 2  2001-12-13T00:00:00   POINT (441564 4482801) 2807908
## 3  2006-01-04T00:00:00 POINT (441561.3 4482787) 2807908
## 4  2003-01-14T00:00:00 POINT (441577.5 4482829) 2807908
## 5  2001-12-13T00:00:00 POINT (441565.7 4482819) 2807908
## 6  2001-12-13T00:00:00 POINT (441564.9 4482809) 2807908
# Conteo de direcciones por Distrito Censal
agrupaDist <- unionEspa %>%
  group_by(CUDIS) %>%
  summarise(n=n())
unionEspa <- inner_join(SSCC,agrupaDist,by="CUDIS")

ggplot(unionEspa) +
geom_sf(aes(fill = n)) +
  scale_fill_continuous(type = "gradient",breaks = as.integer(seq(min(unionEspa$n),max(unionEspa$n),length.out = 10)))