```{r, echo=FALSE, results="hide", warning=FALSE, message=FALSE}

##
## GWL 2016-10-10
## Putting 20_Map_dev_v1.R into map_demo.Rmd

##==============================================================================
## INITIALIZE
##==============================================================================

rm(list=ls())

library("geneorama")
sourceDir("functions")
loadinstall_libraries(c("leaflet", "data.table", "sp", "rgdal", "KernSmooth",
                        "maptools", "knitr"))
opts_chunk$set(tidy=FALSE, echo = FALSE, results="hide", warning=FALSE, message=FALSE)


##==============================================================================
## LOAD DATA
##==============================================================================

dat <- readRDS("data/wnv.Rds")
census_tracts <- download_census_tracts()
wards <- download_ward_map()
wards <- readRDS("data/BoundariesWards.Rds")

##==============================================================================
## MAPBOX KEY
## Register at mapbox.com and create a map... or use the one I made
##==============================================================================
MAPBOX_STYLE_TEMPLATE <- paste0("https://api.mapbox.com/styles/v1/coc375492/",
                                "cirqd7mgf001ygcnombg4jtb4/tiles/256/{z}/{x}/{y}",
                                "?access_token=pk.eyJ1IjoiY29jMzc1NDkyIiwiYSI6ImN",
                                "pcnBldzVqMTBmc3J0N25rZTIxZ3ludDIifQ.DgJIcLDjC1h9MtT8CaJ-pQ")
mb_attribution <- paste("© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> ",
                        "© <a href='http://www.openstreetmap.org/about/'>OpenStreetMap</a>")

##==============================================================================
## AGGREGATE MOSQUITO DATA
##==============================================================================

## Here's the data without aggregating:
dat

## These steps create fields which will be used for the aggregation step:
dat[ , .N, species]
dat[ , mix := species == "CULEX PIPIENS/RESTUANS"]
dat[ , pip := species == "CULEX PIPIENS"]
dat[ , res := species == "CULEX RESTUANS" ]
dat[ , oth := !mix & !pip & !res]
dat[ , .N, list(species, mix, pip, res, oth)]

dat[ , species_short := species]
dat[grep("CULEX PIPIENS/RESTUANS", species_short), species_short := "mix"]
dat[grep("CULEX PIPIENS", species_short), species_short := "pip"]
dat[grep("CULEX RESTUANS", species_short), species_short := "res"]
dat[grep("CULEX RESTUANS", species_short), species_short := "res"]
dat[!species_short %in% c("pip", "res", "mix"), species_short := "OTHER"]

```


Results for `r dat[,  max(date)]`


## West Nile results with total mosquitos

This is how I had been showing the data, but I realized lateer that it's misleading unless you know what you're looking at.  

It's not *really* total positive / total, it's actually "the absolutely biggest possible number of positive" / total.


```{r}
# opts_chunk$set(eval=FALSE)

```

```{r}
## This is the aggregation step:
counts <- dat[date == max(date),
              list(TOTAL = sum(number_of_mosquitoes),
                   TOTAL_POS = sum(number_of_mosquitoes[result==T]),
                   MIX = sum(number_of_mosquitoes[species_short=="mix"]),
                   MIX_POS = sum(number_of_mosquitoes[species_short=="mix" & result==T]),
                   PIPIENS = sum(number_of_mosquitoes[species_short=="pip"]),
                   PIPIENS_POS = sum(number_of_mosquitoes[species_short=="pip" & result==T]),
                   RESTUANS = sum(number_of_mosquitoes[species_short=="res"]),
                   RESTUANS_POS = sum(number_of_mosquitoes[species_short=="res" & result==T]),
                   OTHER = sum(number_of_mosquitoes[species_short=="OTHER"]),
                   OTHER_POS = sum(number_of_mosquitoes[species_short=="OTHER" & result==T])),
              keyby = list(TRAP = trap,
                           WARD,
                           latitude,
                           longitude)]
counts <- counts[,
                 LABEL := htmltools::HTML(
                     paste(paste0("TRAP: ", TRAP),
                           paste0("TOTAL: ", TOTAL_POS, " / ", TOTAL),
                           paste0("MIX: ", MIX_POS, " / ", MIX),
                           paste0("PIPIENS: ", PIPIENS_POS, " / ", PIPIENS),
                           paste0("RESTUANS: ", RESTUANS_POS, " / ", RESTUANS),
                           paste0("OTHER: ", OTHER_POS, " / ", OTHER),
                           sep = "<br>")),
                 keyby = list(TRAP = TRAP,
                              WARD,
                              latitude,
                              longitude)][]

## Here's the data after aggregating:
counts
```


```{r, results="show"}
##==============================================================================
## RESULT MAP
##==============================================================================
leaflet() %>%
    addTiles(urlTemplate = MAPBOX_STYLE_TEMPLATE, attribution = mb_attribution) %>%
    addPolygons(data=wards, weight=1, fillOpacity=.05, color="black", 
                label=paste0("WARD ", wards$ward), smoothFactor=.02) %>%
    addCircles(lng=~longitude, lat=~latitude,  radius=~TOTAL*5, 
               label=~LABEL, fill="blue", col="blue", weight=1, data=counts) %>%
    addCircles(lng=~longitude, lat=~latitude,  radius=~TOTAL_POS*5, 
               label=~LABEL, fill="red", col="red", weight=1, data=counts)
```

## Mosquito results with sample counts


This is ugly, but the pop ups show the underlying sample information. 


```{r}
## This is the aggregation step:
counts <- dat[date == max(date),
              list(TOTAL = sum(number_of_mosquitoes),
                   TOTAL_POS = sum(number_of_mosquitoes[result==T]),
                   Ns_POS = paste(number_of_mosquitoes[result==TRUE], collapse=","),
                   Ns_NEG = paste(number_of_mosquitoes[result==FALSE], collapse=","),
                   SPECIES_POS = paste(species_short[result==TRUE], collapse=","),
                   SPECIES_NEG = paste(species_short[result==FALSE], collapse=",")),
              keyby = list(TRAP = trap,
                           WARD,
                           latitude,
                           longitude)]
counts <- counts[,
                 LABEL := htmltools::HTML(
                     paste(paste0("TRAP: ", TRAP),
                           paste0("TOTAL: ", TOTAL_POS, " / ", TOTAL),
                           paste0("COUNTS_POS: ", Ns_POS),
                           paste0("COUNTS_NEG: ", Ns_NEG),
                           paste0("SPECIES_POS: ", SPECIES_POS),
                           paste0("SPECIES_NEG: ", SPECIES_NEG),
                           sep = "<br>")),
                 keyby = list(TRAP = TRAP,
                              WARD,
                              latitude,
                              longitude)][]
## Here's the data after aggregating:
counts
```

```{r, results="show"}
##==============================================================================
## RESULT MAP
##==============================================================================
leaflet() %>%
    addTiles(urlTemplate = MAPBOX_STYLE_TEMPLATE, attribution = mb_attribution) %>%
    addPolygons(data=wards, weight=1, fillOpacity=.05, color="black", 
                label=paste0("WARD ", wards$ward), smoothFactor=.02) %>%
    addCircles(lng=~longitude, lat=~latitude,  radius=~TOTAL*5, 
               label=~LABEL, fill="blue", col="blue", weight=1, data=counts) %>%
    addCircles(lng=~longitude, lat=~latitude,  radius=~TOTAL_POS*5, 
               label=~LABEL, fill="red", col="red", weight=1, data=counts)
```



