---
title: "S4 - RSSI Histogram"
output:
  html_document:
    theme: cerulean
    number_sections: true
---

```{r setup, include=FALSE, echo=FALSE, message=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  echo = FALSE, 
  message = FALSE, 
  warning = FALSE,
  comment = "#>"
)

rm(list=ls())
gc()



# CRAN libraries 
library(cowplot)
library(tidyverse)
library(magrittr)
library(RColorBrewer)

# Download and install from Github https://github.com/jmueller17/sociometrics
library(sociometrics)

# Download and install from Zenodo https://doi.org/10.5281/zenodo.3446071
library(gediismtrx)
data("gedii_sociodemo_fix")
data("gedii_rr")
data("gedii_interaction")

source("S4_utility.fun.R")


# indicating RSSI levels included 
rssi_range <- c(-53:-91) 

str_teams <- c(paste0("Team_", c(1:6, 8)), "Team_7A", "Team_7B")

# get all teams, using all RSSI levels. 
bt <- gedii_interaction %>%
  filter(Team %in% str_teams & !is.na(RSSI)) %>% 
  mreverse(cols=c("Badge.ID", "Other.ID"), into="edge")

# assign organizational type to each team 
bt$org <- sapply(bt$Team, team2org)

```



# Bluetooth frequencies 


## Boxplot of BT detects (all teams)

```{r fig.width=3, fig.height=4}

box <- bt %>% 
  ggplot(aes(y=RSSI)) + 
  geom_boxplot(outlier.colour = "red") +
  scale_y_continuous(breaks=seq(-95,-20, by=5)) +
  labs(x="") +
  theme_bw() + 
  theme(plot.margin=unit(c(1.2,1,0,1),"cm"))

box
```

## Histogram of BT detecs per RSSI level (all teams)

```{r fig.width=7, fig.height=4}

g1 <- bt %>%
  group_by(RSSI) %>% 
  summarize(detects = n()) %>% 
  mutate(outlier = if_else((RSSI > -53 | RSSI < -91), T, F)) %>% 
  ggplot(aes(x=RSSI, y=detects, fill=outlier)) +
    geom_histogram(stat="identity") + 
    scale_x_continuous(limits=c(-95, -43), breaks=seq(-95,-43, by=5)) +
    scale_fill_manual(values=c("#000000", "#ff0000"), guide=F) + 
    labs(x="RSSI", y="Total detects") +
    theme_bw() + 
    theme(plot.margin=unit(c(1.2,1,0,1),"cm"))

g1
```


## Statistics on outliers

```{r}

total <- nrow(bt)

included <- bt %>%
  filter(RSSI %in% rssi_range) %>% 
  group_by(RSSI) %>% 
  summarize(count=n())

total.incl <- sum(included$count)

removed <- total - total.incl

total
-removed
total.incl

paste("Total observations:", total, " Removing", removed , "outliers. BT observations included in analysis:", total.incl)
```



## Frequencies of BT detects by organizational contexts 

```{r fig.width=9, fig.height=4}

bt %>%
  mutate(org = if_else((RSSI > -53 | RSSI < -91), "Outlier", org)) %>% 
  ggplot(aes(x=RSSI, fill=org)) +
    geom_bar(stat="count", position="stack", alpha=1) + 
    scale_x_continuous(limits=c(-95, -45), breaks=seq(-95,-45, by=5)) +
    scale_fill_manual(values=c("#d3d3d3", "#1f9bde","#de1f9b", "#9bde1f"))  +
    labs(guide=F, x="RSSI", y="Total BT detects") +
    theme_bw() + 
    theme(plot.margin=unit(c(1.2,1,0,1),"cm"), 
          legend.position="right", 
          legend.title=element_blank())

```


<p>&nbsp;</p>
<p>&nbsp;</p>

