---
title: "3_global_local_comparisons"
output:
  pdf_document: default
  html_document: default
date: "2025-03-26"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

*loading library*
====================================================================================================================================
```{r}
#install.packages("readxl")
library(readxl)
#install.packages("tidyverse")
library(tidyverse)
#install.packages("janitor")
library(janitor)
#install.packages("writexl")
library(writexl)
#install.packages("ggsci")
library(ggsci)
#install.packages("patchwork")
library(patchwork)
#install.packages("ggpubr")
library(ggpubr)
#install.packages("ComplexUpset")
library(ComplexUpset)
#install.packages("maps")
library(maps)
#install.packages("viridis")
library(viridis)
```

*uploading all data*
====================================================================================================================================
# amr genes
# characterisation of genomes sheet (kleborate data)
## note: these kleborate data are derived from but separate (slightly modified) to the output from 1_cleaning_Rmd/3_char_genomes_output.Rmd
```{r}
char_genomes_gl <- read_xlsx("/Users/jonahrodgus/Desktop/declutter/genomic_analyses/global_local_comparisons/isolates_of_top7STs_with_metadata.xlsx",
                             sheet="Sheet1") %>%
  distinct()
```
# peg344 BLAST data
```{r}
# uploading all 
peg344_BLAST <-
  read_xlsx(
   # mac mini
  "~/Library/Mobile Documents/com~apple~CloudDocs/Desktop/declutter/genomic_analyses/global_local_comparisons/3_char_genomes_cont/peg344_blast.xlsx",
  # macbook  
  #"/Users/jonahrodgus/Desktop/declutter/genomic_analyses/colebrook.xlsx",
  sheet="all_STs_peg344_blast_results") %>%
  separate(sseqid,into = c("isolate_code","junk"), sep ="\\|") %>%
  # selecting columns of interest
  select(isolate_code,
         `peg344 % identity`=pident) %>%
  mutate(peg344_locus = "TRUE") %>%
  # relocating column
  relocate(peg344_locus, .before = `peg344 % identity`) %>%
  # mostly unimportant
  select(-`peg344 % identity`)
```
# defining genomic resistance profiles, HvKp, genomic convergence on same terms as colebrook isolates
```{r}
char_genomes_gl <-
char_genomes_gl  %>%
  # genomic resistance profiles
  mutate(resistance_profile = if_else(resistance_score == 0,
                                      "ESBL-/CPE-",
                                      as.character(resistance_score))) %>%
  mutate(resistance_profile = if_else(resistance_score == 1,
                                      "ESBL+/CPE-",
                                      resistance_profile)) %>%
  mutate(resistance_profile = if_else(resistance_score > 1,
                                      "CPE+",
                                      resistance_profile)) %>%
  mutate(resistance_profile = resistance_profile %>%
           # relevelling factors
           fct_relevel("ESBL-/CPE-","ESBL+/CPE-","CPE+")) %>%
  # renaming virulence gene columns
  rename(iuc = Aerobactin,
         iro = Salmochelin) %>%
  mutate(
    # this in not allele specific - THIS IS A LOCUS
    iuc_locus = if_else(str_detect(iuc, "iuc"), "TRUE", "FALSE"),
    # this in not allele specific - THIS IS A LOCUS
    iro_locus = if_else(str_detect(iro, "iro"), "TRUE", "FALSE"),
    # this in not allele specific - THIS IS A LOCUS
    rmpA_locus = if_else(str_detect(rmpA2, "rmpA"), "TRUE", "FALSE"),
    # is this allele specific?
    irp2_locus = if_else(irp2 != "-", "TRUE", "FALSE"),
         ) %>%
  # tidying gene names
   mutate(
      iuc = case_when(
        str_detect(iuc, "iuc 1")  ~ "*iuc1*",
        iuc == "iuc 2"           ~ "*iuc2*",
        str_detect(iuc, "iuc 2A") ~ "*iuc2A*",
        TRUE                            ~ iuc
      ),
      iro = case_when(
        str_detect(iro, "iro 1")  ~ "*iro1*",
        str_detect(iro, "iro 2")  ~ "*iro2*",
        iro == "iro unknown"      ~ "*iroOther*",
        TRUE                              ~ iro
      ),
      irp2 = if_else(str_detect(irp2, "\\d"), "*irp2*", irp2)
    ) %>%
  separate(
      col   = rmpA2,
      # splitting into rmpA and rmp by any other name
      into  = c("rmpA", "rmpA%"),
      sep   = "-",
      fill  = "right",
      extra = "merge",
      remove = FALSE
    ) %>%
    mutate(
      # removing last character (if present) and convert to numeric
      `rmpA%` = str_remove(`rmpA%`, ".$"), 
      `rmpA%` = as.numeric(`rmpA%`)
      ) %>%
  # adding *s
  mutate(rmpA = if_else(str_detect(rmpA, "rmpA"), paste0("*", rmpA, "*"), rmpA)) %>%
  select(-c(rmpA2)) %>%
  # removing allele version from rmpA2 column
  mutate(rmpA = str_remove(rmpA, "_.*?(?=\\*)")) %>%
  # removing blank values
  mutate(across(c(iuc:rmpA,irp2), ~ if_else(.x == "" | .x == "-", NA_character_, .x))) %>%
  # creating peg344 column
  left_join(peg344_BLAST,
            by = "isolate_code") %>%
  # marking NAs as false
  mutate(peg344_locus = replace_na(peg344_locus, "FALSE")) %>%
  # creating gene column
  mutate(peg344 = if_else(peg344_locus == "TRUE", "*peg344*", NA)) %>%
  relocate(peg344, .after = irp2) %>%
  # marking genomic_hypervirulence
  mutate(genomic_hypervirulence = if_else(
    if_any(iuc_locus:peg344_locus, ~ . == TRUE),
    # carries HvKp genes
    "HvKp+", 
    # does not carry HvKp genes
    "HvKp-"
  )) %>%
  # reordering levels
  mutate(genomic_hypervirulence = factor(genomic_hypervirulence, levels = c("HvKp-", "HvKp+"))) %>%
  # genomic convergence
  group_by(isolate_code) %>%
  mutate(genomic_convergence = if_else(
    any(resistance_profile == "CPE+" & 
          # carries one or more of the HvKp genes
          if_any(iuc_locus:peg344_locus, ~ . == TRUE)), 
    "Convergent",
    "Non-Convergent"
  )) %>% ungroup() %>%
  distinct()
```
# char_genomes data final handlings steps
```{r}
char_genomes_gl <-
char_genomes_gl %>% 
  # relevelleing ST factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # relevelling source factors
  mutate(source = fct_recode(source,"Wound/Soft Tissue"="Wound Or Soft Tissue, e.g., Liver Abscess")) %>%
  mutate(source = factor(source, levels = c(
    "Blood",
    "Urine",
    "Wound/Soft Tissue",
    "Respiratory",
    "Faeces",
    "Rectal Swab",
    "Screening Swab",
    "Bile",
    "Catheter",
    "Cerebrospinal Fluid",
    "Sterile Site",
    "Other Secretion",
    "Not Reported"
  ))) %>%
  # grouping locations
  mutate(region = case_when(
    location == "London, UK" ~ "London, UK",
    location %in% c("Oxford, UK", "Wales, UK", "UK") ~ "Other, UK",
    location %in% c("Austria", "Belgium", "France", "Germany", "Italy", "Spain", "Portugal", "Switzerland", "Ireland", "Luxembourg", "Malta") ~ "Western Europe",
    location %in% c("Poland", "Slovakia", "Hungary", "Croatia", "Montenegro", "Romania", "Russia", "Estonia") ~ "Eastern Europe",
    location == "Norway" ~ "Northern Europe",
    location %in% c("Turkey", "Israel", "Iran") ~ "Middle East",
    location == "USA" ~ "North America",
    location == "Australia" ~ "Oceania",
    location %in% c("Nigeria", "Senegal", "South Africa") ~ "Sub-Saharan Africa",
    location %in% c("India", "Pakistan", "Bangladesh") ~ "South Asia",
    location %in% c("China", "Hong Kong") ~ "East Asia",
    location %in% c("Singapore", "Vietnam", "Thailand", "Laos", "Cambodia") ~ "Southeast Asia",
    location == "Madagascar" ~ "East Africa",
    TRUE ~ "UNKNOWN"
  )) %>%
  # relevelling location factors
  mutate(region = factor(region, levels = c(
    "London, UK",
    "Other, UK",
    "Western Europe",
    "Eastern Europe",
    "Middle East",
    "Northern Europe",
    "North America",
    "Southeast Asia",
    "East Asia",
    "South Asia",
    "Oceania",
    "Sub-Saharan Africa",
    "East Africa",
    "West Africa"
  ))) %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341"))
```
# abricate data
```{r}
abricate<-read_tsv("/Users/jonahrodgus/Desktop/declutter/genomic_analyses/global_local_comparisons/3_char_genomes_cont/all_isolates_abricate.tsv",
                   col_names = TRUE)

# making column names lowercase
colnames(abricate)<-tolower(colnames(abricate))

# converting to data frame
abricate<-as.data.frame(abricate)

abricate_gl<-
abricate %>%
  # filtering header rows
  filter(`#file` != "#FILE") %>%
  # renaming first column
  mutate(coco_id=as.factor(`#file`)) %>%
  # separating isolate code
  separate(coco_id, into = c("ST","coco_id"), sep = "/") %>%
  mutate(coco_id = str_remove(coco_id, "_filtered.fasta")) %>%
  select(-`#file`) %>%
  # mapping coco ids to isolate codes
  mutate(isolate_code = case_when(
    coco_id == "951_S24_L001" ~ "CAS951",
    coco_id == "CAS905_S11_L001" ~ "CAS905",
    coco_id == "CAS906_S12_L001" ~ "CAS906",
    coco_id == "Kpn01732-merged" ~ "GCF_902703025.1",
    coco_id == "kpneu006_ill" ~ "GCF_900607435.1",
    coco_id == "kpneu015_ill" ~ "GCF_900607685.1",
    coco_id == "kpneu022_ill" ~ "GCF_900607875.1",
    coco_id == "kpneu033_ill" ~ "GCF_900608135.1",
    coco_id == "kpneu044_ill" ~ "GCF_900608315.1",
    coco_id == "Kpneumoniae-Nordmann_S2_L001" ~ "NUH02_S2_L001",
    coco_id == "K-pneumoniae-TG21982_GCACTA_L003" ~ "ERR720264",
    # fallback to coco_id if no match
    TRUE ~ coco_id  
  )) %>%
  # reordering columns
  relocate(c(isolate_code, coco_id, ST), .before = everything())
```
# mobtyper data
```{r}
mobtyper<-read_tsv(
  "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/global_local_comparisons/4_char_plasmids/all_mobtyper_results.tsv",
                           col_names = TRUE)

# making column names lowercase
colnames(mobtyper)<-tolower(colnames(mobtyper))

mobtyper<-mobtyper %>%
  # renaming and reordering columns
  separate(sample_id, into=c("coco_id","plasmid_id"),sep=":") %>%
  # selecting columns of interest
  select(coco_id,
         plasmid_id,
         size,
         `rep_type(s)`,
         `relaxase_type(s)`,
         predicted_mobility) %>%
  mutate(coco_id = str_remove(coco_id, "_filtered")) %>%
  # mapping coco ids to isolate codes
  mutate(isolate_code = case_when(
    coco_id == "951_S24_L001" ~ "CAS951",
    coco_id == "CAS905_S11_L001" ~ "CAS905",
    coco_id == "CAS906_S12_L001" ~ "CAS906",
    coco_id == "Kpn01732-merged" ~ "GCF_902703025.1",
    coco_id == "kpneu006_ill" ~ "GCF_900607435.1",
    coco_id == "kpneu015_ill" ~ "GCF_900607685.1",
    coco_id == "kpneu022_ill" ~ "GCF_900607875.1",
    coco_id == "kpneu033_ill" ~ "GCF_900608135.1",
    coco_id == "kpneu044_ill" ~ "GCF_900608315.1",
    coco_id == "Kpneumoniae-Nordmann_S2_L001" ~ "NUH02_S2_L001",
    coco_id == "K-pneumoniae-TG21982_GCACTA_L003" ~ "ERR720264",
    # fallback to coco_id if no match
    TRUE ~ coco_id  
  )) %>%
  # reordering columns
  relocate(c(isolate_code, coco_id), .before = everything())
```
# plasmid abricate data
```{r}
plasmid_abricate<-read_xlsx(
  "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/global_local_comparisons/4_char_plasmids/all_plasmids_abricate.xlsx")

# making column names lowercase
colnames(plasmid_abricate)<-tolower(colnames(plasmid_abricate))

plasmid_abricate <-
plasmid_abricate %>%
  # renaming columns
  rename(coco_id=`#file`) %>%
  # filtering out chromosome scans
  filter(!str_detect(coco_id,"chromosome")) %>%
  # separating columns
  separate(coco_id, into = c("coco_id","plasmid_id"), sep = "_mobsuite_plasmid_") %>%
  # removing .fasta from plasmid id
  mutate(plasmid_id = str_remove(plasmid_id, ".fasta")) %>%
  # mapping coco ids to isolate codes
  mutate(isolate_code = case_when(
    coco_id == "951_S24_L001" ~ "CAS951",
    coco_id == "CAS905_S11_L001" ~ "CAS905",
    coco_id == "CAS906_S12_L001" ~ "CAS906",
    coco_id == "Kpn01732-merged" ~ "GCF_902703025.1",
    coco_id == "kpneu006_ill" ~ "GCF_900607435.1",
    coco_id == "kpneu015_ill" ~ "GCF_900607685.1",
    coco_id == "kpneu022_ill" ~ "GCF_900607875.1",
    coco_id == "kpneu033_ill" ~ "GCF_900608135.1",
    coco_id == "kpneu044_ill" ~ "GCF_900608315.1",
    coco_id == "Kpneumoniae-Nordmann_S2_L001" ~ "NUH02_S2_L001",
    coco_id == "K-pneumoniae-TG21982_GCACTA_L003" ~ "ERR720264",
    # fallback to coco_id if no match
    TRUE ~ coco_id  
  )) %>%
  # reordering columns
  relocate(c(isolate_code, coco_id, plasmid_id), .before = everything()) %>%
  mutate(start = as.character(start),
         end = as.character(end),
         `%coverage` = as.character(`%coverage`))
```
# joining all abricate data with mobtyper data
```{r}
# creating all_args data frame
all_args <- 
  # colebrook
  abricate_gl %>%
  select(isolate_code:end,
         gene,
         `%coverage`,
         drug=resistance
         ) %>%
  select(-`%coverage`) %>%
  # verifying genes found across both abricate runs
  left_join(plasmid_abricate,
            by = c("isolate_code",
                   "coco_id",
                   "sequence",
                   "start",
                   "end",
                   "gene")) %>%
  left_join(mobtyper,
            by = c("isolate_code",
                   "coco_id",
                   "plasmid_id"))

# tidying empty fields
all_args$`rep_type(s)` <- na_if(all_args$`rep_type(s)`, "-")
all_args$`relaxase_type(s)` <- na_if(all_args$`relaxase_type(s)`, "-") 

all_args_gl<-all_args
```
# checking join
```{r}
# should be 4583 plasmid-carried genes
all_args_gl %>%
  group_by(is.na(plasmid_id)) %>%
  tally()
```

# hvkp markers
# creating hvkp markers data
```{r}
all_hvkp_markers <-
  char_genomes_gl %>%
  select(isolate_code,
         coco_id,
         ST,
         source,
         iuc,
         iro,
         rmpA,
         irp2,
         peg344) %>%
  pivot_longer(cols=c(iuc:peg344),
               names_to = "HvKp_marker",
               values_to = "variant") %>%
  filter(!is.na(variant))
```
# peg344 plasmid BLAST data
```{r}
# uploading all 
peg344_plasmid_BLAST <-
  read_xlsx(
   # mac mini
  "~/Library/Mobile Documents/com~apple~CloudDocs/Desktop/declutter/genomic_analyses/global_local_comparisons/4_char_plasmids/all_plasmids_peg344_blast.xlsx") %>%
  separate(sseqid,into = c("coco_id","plasmid_id","junk"), sep ="\\|") %>%
  # selecting columns of interest
  select(coco_id,
         plasmid_id,
         `peg344 % identity`=pident) %>%
  mutate(peg344_locus = "TRUE") %>%
  # relocating column
  relocate(peg344_locus, .before = `peg344 % identity`) %>%
  # mostly unimportant
  select(-`peg344 % identity`) %>%
  # mapping coco ids to isolate codes
  mutate(isolate_code = case_when(
    coco_id == "951_S24_L001" ~ "CAS951",
    coco_id == "CAS905_S11_L001" ~ "CAS905",
    coco_id == "CAS906_S12_L001" ~ "CAS906",
    coco_id == "Kpn01732-merged" ~ "GCF_902703025.1",
    coco_id == "kpneu006_ill" ~ "GCF_900607435.1",
    coco_id == "kpneu015_ill" ~ "GCF_900607685.1",
    coco_id == "kpneu022_ill" ~ "GCF_900607875.1",
    coco_id == "kpneu033_ill" ~ "GCF_900608135.1",
    coco_id == "kpneu044_ill" ~ "GCF_900608315.1",
    coco_id == "Kpneumoniae-Nordmann_S2_L001" ~ "NUH02_S2_L001",
    coco_id == "K-pneumoniae-TG21982_GCACTA_L003" ~ "ERR720264",
    # fallback to coco_id if no match
    TRUE ~ coco_id  
  )) %>%
  # reordering columns
  relocate(c(isolate_code, coco_id), .before = everything())
```
# plasmid kleborate data
```{r}
plasmid_kleborate<-read_xlsx(
  "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/global_local_comparisons/4_char_plasmids/all_plasmids_kleborate.xlsx",
                           col_names = TRUE)
```
# joining plasmid kleborate data with mobtyper data
```{r}
plasmid_kleborate <-
plasmid_kleborate  %>%
  # renaming and reordering columns
  separate(strain, into=c("coco_id","plasmid_id"),sep="_mobsuite_plasmid_") %>%
  # mapping coco ids to isolate codes
  mutate(isolate_code = case_when(
    coco_id == "951_S24_L001" ~ "CAS951",
    coco_id == "CAS905_S11_L001" ~ "CAS905",
    coco_id == "CAS906_S12_L001" ~ "CAS906",
    coco_id == "Kpn01732-merged" ~ "GCF_902703025.1",
    coco_id == "kpneu006_ill" ~ "GCF_900607435.1",
    coco_id == "kpneu015_ill" ~ "GCF_900607685.1",
    coco_id == "kpneu022_ill" ~ "GCF_900607875.1",
    coco_id == "kpneu033_ill" ~ "GCF_900608135.1",
    coco_id == "kpneu044_ill" ~ "GCF_900608315.1",
    coco_id == "Kpneumoniae-Nordmann_S2_L001" ~ "NUH02_S2_L001",
    coco_id == "K-pneumoniae-TG21982_GCACTA_L003" ~ "ERR720264",
    # fallback to coco_id if no match
    TRUE ~ coco_id  
  )) %>%
  # reordering columns
  select(isolate_code,
         coco_id,
         plasmid_id,
         iuc=Aerobactin,
         iro=Salmochelin,
         rmpA2,
         irp2) %>%
  # tidying gene names
   mutate(
      iuc = case_when(
        str_detect(iuc, "iuc 1")  ~ "*iuc1*",
        iuc == "iuc 2"           ~ "*iuc2*",
        str_detect(iuc, "iuc 2A") ~ "*iuc2A*",
        TRUE                            ~ iuc
      ),
      iro = case_when(
        str_detect(iro, "iro 1")  ~ "*iro1*",
        str_detect(iro, "iro 2")  ~ "*iro2*",
        iro == "iro unknown"      ~ "*iroOther*",
        TRUE                              ~ iro
      ),
      irp2 = if_else(str_detect(irp2, "\\d"), "*irp2*", irp2)
    ) %>%
  separate(
      col   = rmpA2,
      # splitting into rmpA and rmp by any other name
      into  = c("rmpA", "rmpA%"),
      sep   = "-",
      fill  = "right",
      extra = "merge",
      remove = FALSE
    ) %>%
    mutate(
      # removing last character (if present) and convert to numeric to represent % coverage
      `rmpA%` = str_remove(`rmpA%`, ".$"), 
      `rmpA%` = as.numeric(`rmpA%`)
      ) %>%
  # adding *s
  mutate(rmpA = if_else(str_detect(rmpA, "rmpA"), paste0("*", rmpA, "*"), rmpA)) %>%
  # removing unwatned columns
  select(-c(rmpA2,`rmpA%`)) %>%
  # removing allele version from rmpA2 column
  mutate(rmpA = str_remove(rmpA, "_.*?(?=\\*)")) %>%
  # removing blank values
  mutate(across(c(iuc:rmpA,irp2), ~ if_else(.x == "" | .x == "-", NA_character_, .x))) %>%
  # creating peg344 column
  left_join(peg344_plasmid_BLAST,
            by = c("isolate_code",
                   "coco_id",
                   "plasmid_id")) %>%
  # marking NAs as false
  mutate(peg344_locus = replace_na(peg344_locus, "FALSE")) %>%
  # creating gene column
  mutate(peg344 = if_else(peg344_locus == "TRUE", "*peg344*", NA)) %>%
  # removing unwanted column
  select(-peg344_locus) %>%
  relocate(peg344, .after = irp2) %>%
  # marking plasmids that contain 1 or more HvKp markers
  mutate(vir_plasmid = rowSums(across(iuc:peg344, ~ !is.na(.))) > 0) %>%
  relocate(vir_plasmid, .before = "iuc") %>%
  left_join(mobtyper,
            by = c("isolate_code",
                   "coco_id",
                   "plasmid_id")) %>%
  # pivoting longer
  pivot_longer(cols=c(iuc:peg344),
               names_to = "HvKp_marker",
               values_to = "variant") %>%
  relocate(c(HvKp_marker,variant), .before = "size") %>%
  filter(!is.na(variant))

```
# joining hvkp markers data and plasmid data with metadata
```{r}
all_hvkp_markers <-
all_hvkp_markers %>%
  left_join(plasmid_kleborate,
            by = c("isolate_code",
                   "coco_id",
                   "HvKp_marker",
                   "variant"))

all_hvkp_markers_gl <- all_hvkp_markers
```
# checking accessions mapping 
```{r}
# abricate %>%
# mobtyper %>%
all_args_gl %>%
  select(isolate_code,coco_id) %>%
  filter(isolate_code != coco_id) %>%
  distinct()
```
# distances data
```{r}
# setting common path prefix
path <- "/Users/jonahrodgus/Desktop/declutter/genomic_analyses/tree_building/global_local_comparisons/distances/"

distances_global_local <- map_dfr(top7STs, ~ {
  file_path <- file.path(path, paste0(.x, "_distances.csv"))
  read.csv(file_path) %>%
    mutate(ST = .x)
})

# formatting distances data
distances_global_local <- distances_global_local %>%
  # removing suffix
  mutate(isolate_1 = str_replace(isolate_1, "_filtered", ""),
         isolate_2 = str_replace(isolate_2, "_filtered", ""))

distances_global_local <- distances_global_local %>%
  # removing self-comparisons
  filter(isolate_1 != isolate_2) %>%
  # removing reverse duplicates
  mutate(
    pair_sorted = pmap_chr(list(isolate_1, isolate_2), ~ paste(sort(c(...)), collapse = "_"))) %>%
  distinct(pair_sorted, .keep_all = TRUE) %>%
  select(-pair_sorted)
```

>>>          >>>
>>> PLOTTING >>>
>>>          >>>

*clinical characterisation*
====================================================================================================================================
# figure: world map of genomes
```{r}
mapdata <- map_data("world")
#View(mapdata)

df <-
char_genomes_gl %>%
  separate(location, into = c("before_comma", "after_comma"), sep = ", ", extra = "merge", fill = "right") %>%
  mutate(country = if_else(is.na(after_comma), before_comma, after_comma))

colnames(mapdata)[5] <- "country"

# checking if any countries misaligned
df %>%
  select(isolate_code,
         country) %>%
  filter(country %!in% mapdata$country) #%>%
#View()

#check United States
mapdata$country <- gsub("Hong Kong", "China", mapdata$country)

to_plot <- 
  left_join(mapdata,
            df %>%
              select(isolate_code,
                     country) %>%
              group_by(country) %>%
              mutate(count = n()),
            by = "country")


#View(to_plot)  

to_plot$count <- as.numeric(to_plot$count)

summary(to_plot$count)

# making NAs 0
to_plot <- to_plot %>%
  mutate(count = if_else(is.na(count), 0, count))

to_plot %>%
  select(country,count) %>%
  distinct() %>%
  filter(count>0) %>%
View()

to_plot %>%
ggplot() +
  geom_polygon(aes(fill = count,
                   x = long,
                   y = lat,
                   group = group),
               colour = "black") +
  theme_bw() +
  ylab("") +
  xlab("") +
  scale_fill_viridis(option = "plasma",
                     direction = 1,
                     trans = "log",
                     breaks=c(1,10,50,100, 200, 400),
                     labels=c("1","10","50","100","200","400"),
                     na.value="white") +
  theme(axis.title = element_blank(),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        plot.margin = unit(c(1,1,1,1),"cm"),
        strip.text.x = element_blank(),
        #legend.text = element_text(size=40),
        # add legend box
        legend.background = element_blank(), 
        legend.box.background = element_rect(colour = "black"),
        # legend title size
        #legend.title = element_text(size=60),
        # key size
        #legend.key.size = unit(1.5, "cm"),
        # space between title and key
        #legend.spacing.y = unit(1, 'cm'),
        # space between box and legend
        legend.margin = margin(8,8,10,8)
        # space between box and plot
        #legend.box.spacing = margin(40)
        ) +
  labs(fill="Genome Count")

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/8_comparison_to_global_genomes/world_map_genomes.jpeg",
       width = 14.88,
  height = 8.27)

```
# figure: location-wise distribution of genomes by source
```{r}

char_genomes_gl %>%
  # removing duplicates
  distinct() %>%
  # counting per ST
  group_by(ST) %>%
  mutate(STlabel = paste0(ST," (n=",n(),")")) %>%
  ungroup() %>%
  # counting per source
  group_by(source) %>%
  mutate(sourcelabel = paste0(source," (n=",n(),")")) %>%
  ungroup() %>%
  # reordering labels to match columns
  mutate(
    STlabel = factor(STlabel, levels = unique(STlabel[match(levels(ST), ST)])),
    sourcelabel = factor(sourcelabel, levels = unique(sourcelabel[match(levels(source), source)]))) %>%
  # counting combinations
  group_by(STlabel, region, source) %>%
  tally() %>%
#View()
  # plotting
  ggplot(aes(x=source,
             y=fct_rev(region),
             alpha=n)) +
  geom_tile(aes(fill=STlabel)) +
  theme_bw() +
  # sizing
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle=90,hjust=1),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        #legend.position = c(0.6,0.11),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  labs(y=NULL,
       x=NULL,
       alpha="Genome Count"
         ) +
  guides(fill=FALSE) +
  scale_alpha_continuous(range=c(0.2,1)) +
  scale_fill_manual(values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f",
                               "#008080"
                                )) +
  facet_wrap(STlabel~.#, scales= "free_x"
             )

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/8_comparison_to_global_genomes/global_source_distribution.jpeg",
       height=8.27,
       width=9)
```
# description: STs across locations and sources
```{r}
n_distinct(char_genomes_gl$source)
n_distinct(char_genomes_gl$location)

#df <-
char_genomes_gl  %>%
  distinct() %>%
  group_by(
    ST,
    #isolate_code %in% colebrook_final_isolates$isolate_code,
    #location == "London, UK"
    region,
    source,
    #resistance_score,
    #virulence_score
           ) %>%
  tally() #%>%
  group_by(ST) %>%
  mutate(total=n_distinct(
    #region
    source
                          )) %>%
  select(ST, total) %>%
  distinct()


char_genomes_gl %>%
  filter(isolate_code %!in% colebrook_final_isolates$isolate_code &
           location == "London, UK") %>%
  group_by(dataset) %>%
  tally()

write_xlsx(df, "/Users/jonahrodgus/Desktop/STs_locations_sources.xlsx")
```

*genomic diversity*
====================================================================================================================================
# description: trees
```{r}
char_genomes_gl %>%
  filter(ST == "ST147") %>%
  group_by(
    #resistance_profile,
    #genomic_hypervirulence
    irp2_locus == "TRUE"
           ) %>%
  tally()

# resistance gene profiles
char_genomes_gl %>%
  filter(ST == "ST13", resistance_profile %in% c("ESBL+/CPE-","CPE+")) %>%
#View()
  # creating "no carbapenemase gene" 
  mutate(Bla_ESBL_acquired = if_else(Bla_ESBL_acquired == "-", "No ESBL Gene", Bla_ESBL_acquired),
         Bla_Carb_acquired = if_else(Bla_Carb_acquired == "-", "No Carb Gene", Bla_Carb_acquired)) %>%
  group_by(Bla_ESBL_acquired,Bla_Carb_acquired) %>%
  tally() %>%
  arrange(desc(n))

# virulence gene count
char_genomes_gl %>%
  filter(ST == "ST23") %>%
  mutate(virulence_count = rowSums(select(., iuc_locus:peg344_locus) == TRUE)) %>%
  group_by(virulence_count) %>%
  tally()
```
# supplementary figur: within-ST diversity snp distances distributions)
```{r}
df<- distances_global_local %>%
  group_by(ST) %>%
  summarise(
    n_comparisons = n(),
    n_isolates = n_distinct(c(isolate_1,isolate_2)),
    height = max(distance)+2000
  ) %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  mutate(label = paste0("Genomes = ", n_isolates, "\n",
                        "Comparisons = ", n_comparisons))

distances_global_local %>%
  ggplot(aes(x=ST,y=distance)) +
  geom_jitter(width = 0.4, size=0.1,colour="black") +
  geom_violin(alpha=0.9, width = 1,linewidth = 0.3,aes(fill = ST,colour=ST)) +
  stat_summary(fun = median, geom = "point", shape = 23, size = 4, fill = "grey", color = "grey") +
  geom_text(data=df,
            aes(x = ST, y = height, label = label),
            size = 3, inherit.aes = FALSE) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_text(vjust = 2)) +
  labs(x="Sequence Type",
       y="Genome SNP Distance") +
  scale_fill_npg() +
  scale_colour_npg() +
  guides(fill=F,colour=F)

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/8_comparison_to_global_genomes/global_st_snp_distances.jpeg",
       width=8,
       height=4)
```
# statistics
```{r}
distances_global_local %>%
  group_by(ST) %>%
  summarise(
    mean(distance),
    median(distance)
    
  )
```

*resistance: genomic*
====================================================================================================================================
# checking important bla genes: which genes may appear in most common resistance gene profiles?
```{r}
# checking for acquired SHV  genes in kleborate data
isolates_of_top7STs_EDITED %>%
  filter(if_any(c(Bla_acquired:Bla_Carb_acquired), ~ str_detect(.x, "SHV")))

# defining SHV acquired genes using kleborate data
SHV_acquired <- c("blaSHV-49^", "blaSHV-2A^", "blaSHV-2", "blaSHV-30", "blaSHV-31.v1*")

all_args_gl %>%
filter(str_detect(gene, "bla")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # collapsing genes
  mutate(gene_cat = case_when(
    str_detect(gene, "blaTEM") ~ "blaTEM",
    str_detect(gene, "OXA-181|OXA-48|OXA-162|OXA-232|OXA-244") ~ "blaOXA-48-Like",
    str_detect(gene, "OXA-1|OXA-10|OXA-9|OXA-534") ~ "blaOXA-Type",
    str_detect(gene, "KPC-2|KPC-3") ~ "blaKPC",
    str_detect(gene, "VIM") ~ "blaVIM",
    str_detect(gene, "NDM") ~ "blaNDM",
    str_detect(gene, "blaCTX-M") ~ "blaCTX-M",
    str_detect(gene, "blaOXY|blaLAP|blaDHA|blaCMY|OKP|blaSCO") ~ str_extract(gene, ".*(?=-[^-]*$)"),
    TRUE ~ gene)
    ) %>%
  group_by(
          gene_cat
          #gene
           ) %>%
  tally() %>%
  arrange(desc(n))
```
# figure: number of resistance genes by ST
```{r}
abricate_gl %>%
  group_by(ST, isolate_code) %>%
  count() %>%
  ungroup() %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  group_by(ST) %>%
  mutate(label = paste0("n=",n()),
         yval=max(n)) %>%
  ungroup() %>%
  ggplot(aes(x=ST,
             y=n)) +
  geom_jitter(width = 0.4, size=0.1,colour="black") +
  geom_violin(alpha=0.9, width = 1,linewidth = 0.3,aes(fill = ST,colour=ST)) +
  stat_summary(fun = median, geom = "point", shape = 23, size = 4, fill = "grey", color = "grey") +
  geom_text(aes(x = ST, y = yval+1, label = label),
            size = 3, inherit.aes = FALSE) +
  scale_y_continuous(breaks = c(0,10,20,30)) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_text(vjust = 2)) +
  scale_fill_npg() +
  scale_colour_npg() +
  labs(x="Sequence Type",
       y="Resistance Gene Count") +
  guides(fill=FALSE,colour=FALSE) +
  scale_fill_manual(values = c("ST15" = "#6376a0",
                               "ST37" =  "#a6dace",
                               "ST307" =  "#9da6c3",
                               "ST133" =  "#71c9dd",
                               "ST23" =  "#f5af98",
                               "ST13" =  "#ea705d",
                               "ST147" =  "#33b29f")) +
  scale_colour_manual(values = c("ST15" = "#6376a0",
                               "ST37" =  "#a6dace",
                               "ST307" =  "#9da6c3",
                               "ST133" =  "#71c9dd",
                               "ST23" =  "#f5af98",
                               "ST13" =  "#ea705d",
                               "ST147" =  "#33b29f")) +
  guides(fill=FALSE,colour=FALSE)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/8_comparison_to_global_genomes/global_arg_counts.jpeg",
       width=8,
       height=4)
```
# description: number of resistance genes by ST
```{r}
abricate_gl %>%
  group_by(ST, isolate_code) %>%
  count() %>%
  ungroup() %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  group_by(ST) %>%
  mutate(label = paste0("n=",n()),
         yval=max(n)) %>%
  ungroup() %>%
#View()
  group_by(ST) %>%
  summarise(
    mean(n),
    median(n)
  )
```
# figure: genomic resistance profiles by location and source
```{r}
# creating upset data
upset <-
all_args_gl  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             # same order as in phenotypic profiles plot
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (Inc. Cephalosporins\n& Pencillins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide|Trimethoprim") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
      select(-drug) %>%
  # filtering "Other" genes
  filter(drug_class!="Other")

# checking drug class levels
levels(as.factor(upset$drug_class))

upset <-
upset %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # collapsing genes
  mutate(gene_cat = case_when(
    str_detect(gene, "blaTEM") ~ "blaTEM",
    str_detect(gene, "OXA-181|OXA-48|OXA-162|OXA-232|OXA-244") ~ "blaOXA-48-Like",
    str_detect(gene, "OXA-1|OXA-10|OXA-9|OXA-534") ~ "blaOXA-Type",
    str_detect(gene, "KPC-2|KPC-3") ~ "blaKPC",
    str_detect(gene, "VIM") ~ "blaVIM",
    str_detect(gene, "NDM") ~ "blaNDM",
    # preserving blaCTX-M-15 as no other CTX-M variant comes close
    #str_detect(gene, "blaCTX-M") ~ "blaCTX-M",
    str_detect(gene, "blaOXY|blaLAP|blaDHA|blaCMY|OKP|blaSCO") ~ str_extract(gene, ".*(?=-[^-]*$)"),
    str_detect(gene, "catA") ~ "catA",
    str_detect(gene, "catB") ~ "catB",
    str_detect(gene, "cmlA") ~ "cmlA",
    str_detect(gene, "dfrA") ~ "dfrA",
    str_detect(gene, "fosA") ~ "fosA",
    str_detect(gene, "fosB") ~ "fosB",
    str_detect(gene, "oqxA") ~ "oqxA",
    str_detect(gene, "oqxB") ~ "oqxB",
    str_detect(gene, "qnrB") ~ "qnrB",
    TRUE ~ gene))

upset <-
upset %>%
  select(isolate_code,
         gene_cat) %>%
  distinct() %>%
  left_join(char_genomes_gl %>%
              select(isolate_code,
                     ST,
                     region,
                     source),
            by = "isolate_code") %>%
  # filtering "Other genes"
  filter(gene_cat %!in% c("floR", "cmlA", "catA", "catB", "tet(D)", "tet(A)", "arr-3", "fosA", "dfrA"))

upset<-
upset %>%
  pivot_wider(names_from = gene_cat,
              values_from = gene_cat,
              values_fill = FALSE,
              values_fn = ~ TRUE)

# ordering the same as phenotypic resistance by drug class plot
sets_ordered <- c(
  # Aminoglycosides
  "aac(6')-Ib-AKT", "aac(3)-IId", "aph(3')-Ia", "aadA16","aadA2", "aadA1",
  "aac(6')-Ib-cr5","aac(6')-Ib-D181Y", "aac(3)-IIe", "aph(6)-Id", "aph(3'')-Ib",

  # Carbapenems
  "blaOXA-48-Like", "blaOXA-Type","blaKPC",

  # β-Lactams (inc. Cephalosporins)
  "blaSHV-Chromosomal",
  #"blaSHV-Acquired",
  "blaCTX-M-15", "blaTEM",

  # Fluoroquinolones
  "qnrS1", "oqxA", "oqxB", "qnrB",

  # Macrolides
  #"mph(A)",

  # Sulfonamides
  "sul1", "sul2"

  # Other
  #"floR", "cmlA", "catA", "catB", "tet(D)", "tet(A)",
  #"arr-3", "fosA", "dfrA"
)

# reversing the column order to reorder columns (keeping other columns intact)
upset <- upset[, c(colnames(upset)[1:4], rev(sets_ordered))]

# italicising column names
colnames(upset)[5:27] <- paste0("*", colnames(upset)[5:27], "*")

# defining sets
# BE CAREFUL TO LIST CORRECT COLUMNS- the above code filters by n() < X based on plotting
sets <- as.character(colnames(upset)[5:27])
sets

presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
    aggregate(
        as.formula(paste0(presence, "~ intersection")),
        df,
        FUN=sum
    )
}

# plotting
upset(as.data.frame(upset),
      sets,
      stripes = "white",
      sort_sets=FALSE,
      name = "\n Antimicrobial Resistance Gene Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=5
      # check genes above this threshold by toggling this line
      #)
,
      base_annotations=list(
        # checking counts
        #"Intersection size"=intersection_size(counts=TRUE),
        "Count"=(
            ggplot() +
              geom_bar(
                data=summarise_values,
                stat="identity",
                aes(y = !!presence),
                alpha=0.8,
                fill="#008080")+
              #ylim(0,10) +
              scale_y_continuous(labels = scales::number_format(accuracy = 1)) +
              ylab("Genome Count") +
              theme(axis.title.y = element_text(vjust = -20),
                    legend.title = element_blank(),
                    legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")))),
      annotations = list(
        "ST"=(
            ggplot(mapping=aes(fill=as.factor(ST))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              labs(y="Proportion (%)",
                   fill=NULL) +
              theme(axis.title.y = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white"))+
              guides(fill=guide_legend(title=NULL,
                                       ncol = 1)) +
              scale_fill_manual(values = c("#6376a0",
                                           "#a6dace",
                                           "#9da6c3",
                                           "#71c9dd",
                                           "#f5af98",
                                           "#ea705d",
                                           "#33b29f",
                                           "#008080"))
              ),
        "Location"=(
            ggplot(mapping=aes(fill=as.factor(region))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion (%)",
                   fill="Location") +
              theme(axis.title.y = element_text(
                vjust = -20#,
                #hjust=-20
                ),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(
                    values = c(
                      "London, UK" = "#3B4992",
                      "Other, UK" = "#D3D3D3",
                      "Western Europe" = "#EE0000",
                      "Eastern Europe" = "#008B45",
                      "Middle East" = "#808180",
                      "Northern Europe" = "#631879",
                      "North America" = "#FFA500",
                      "Southeast Asia" = "#FF7F50",
                      "East Asia" = "#00B2EE",
                      "South Asia" = "#FFD700",
                      "Oceania" = "#9370DB",
                      "Sub-Saharan Africa" = "#A20056",
                      "East Africa" = "#D55E00",
                      "West Africa" = "#E69F00"
                    )
                  ) +
              guides(fill=guide_legend(title="Location",
                                       ncol = 2))
              ),
        "Source"=(
            ggplot(mapping=aes(fill=as.factor(source))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion (%)",
                   fill="Source") +
              theme(axis.title.y = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(values = c(
                    "Blood" = "#D73027",
                    "Urine" = "#FEE08B",
                    "Wound or Soft Tissue" = "#4575B4",
                    "Respiratory" = "#74ADD1",
                    "Faeces" = "#A6D96A",
                    "Rectal Swab" = "#FDAE61",
                    "Screening Swab" = "#F46D43",
                    "Bile" = "#66C2A5",
                    "Catheter" = "#E6AB02",
                    "Cerebrospinal Fluid" = "#9E0142",
                    "Sterile Site" = "#5E4FA2",
                    "Other Secretion" = "#ABD9E9",
                    "Not Reported" = "#B0B0B0")) +
              guides(fill=guide_legend(title="Source",
                                       ncol = 2))
        )),
        set_sizes=(
            upset_set_size(
                geom=geom_bar(width=0.9,
                              aes(y=..count..),
                              alpha=0.8),
            ) +
              ylab("\nGenome Count")),
      # colouring by drug class
        queries = list(
          # Aminoglycosides
          #upset_query(set = "*aac(6')-Ib-AKT*", fill = "3B4992CC", color_by = "fill"),
          upset_query(set = "*aac(3)-IId*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aph(3')-Ia*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aadA16*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aadA2*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aadA1*", fill = "#3B4992CC", color_by = "fill"),
          #upset_query(set = "*aac(6')-Ib-cr5*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aac(6')-Ib-D181Y*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aac(3)-IIe*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aph(6)-Id*", fill = "#3B4992CC", color_by = "fill"),
          upset_query(set = "*aph(3'')-Ib*", fill = "#3B4992CC", color_by = "fill"),
        
          # Carbapenems
          upset_query(set = "*blaOXA-48-Like*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaOXA-Type*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaKPC*", fill = "#EE0000CC", color_by = "fill"),
        
          # β-Lactams (Inc. Cephalosporins & Pencillins)
          upset_query(set = "*blaSHV-Chromosomal*", fill = "#008B45CC", color_by = "fill"),
          #upset_query(set = "*blaSHV-Acquired*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaCTX-M-15*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaTEM*", fill = "#008B45CC", color_by = "fill"),
        
          # Fluoroquinolones
          #upset_query(set = "*qnrS1*", fill = "631879CC", color_by = "fill"),
          #upset_query(set = "*aac(6')-Ib-cr5*", fill = "631879CC", color_by = "fill"),   #Appears in both classes
          upset_query(set = "*oqxA*", fill = "#631879CC", color_by = "fill"),
          upset_query(set = "*oqxB*", fill = "#631879CC", color_by = "fill"),
          upset_query(set = "*qnrB*", fill = "#631879CC", color_by = "fill"),
        
          # Macrolides
          #upset_query(set = "*mph(A)*", fill = "#008280CC", color_by = "fill"),
        
          # Sulfonamides
          upset_query(set = "*sul1*", fill = "#A20056CC", color_by = "fill"),
          upset_query(set = "*sul2*", fill = "#A20056CC", color_by = "fill")
                            # Other
                            #upset_query(set = "floR", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "cmlA", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "catA", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "catB", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "tet(D)", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "tet(A)", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "arr-3", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "fosA", fill = "808180CC", color_by = "fill"),
                            #upset_query(set = "dfrA", fill = "808180CC", color_by = "fill")
                            )
              ) +
  theme(axis.text.y = element_markdown())


ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/8_comparison_to_global_genomes/global_upset_genotypic_resistance.jpeg",
       width=13,
       height=16)
```
# figure: bla gene resistance profiles by location and source
```{r}
# checking for acquired SHV  genes in kleborate data
isolates_of_top7STs_EDITED %>%
  filter(if_any(c(Bla_acquired:Bla_Carb_acquired), ~ str_detect(.x, "SHV")))

# defining SHV acquired genes using kleborate data
SHV_acquired <- c("blaSHV-49^", "blaSHV-2A^", "blaSHV-2", "blaSHV-30", "blaSHV-31.v1*")

# creating upset data
upset <-
all_args_gl  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             # same order as in phenotypic profiles plot
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (inc. Cephalosporins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide|Trimethoprim") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
      select(-drug) %>%
  # filtering "Other" genes
  filter(drug_class!="Other")

# checking drug class levels
levels(as.factor(upset$drug_class))

upset <-
upset %>%
filter(str_detect(gene, "bla")) %>%
  # collapsing genes
  mutate(gene_cat = case_when(
    str_detect(gene, "blaTEM") ~ "blaTEM",
    str_detect(gene, "OXA-181|OXA-48|OXA-162|OXA-232|OXA-244") ~ "blaOXA-48-Like",
    str_detect(gene, "OXA-1|OXA-10|OXA-9|OXA-534") ~ "blaOXA-Type",
    str_detect(gene, "KPC-2|KPC-3") ~ "blaKPC",
    str_detect(gene, "VIM") ~ "blaVIM",
    str_detect(gene, "NDM") ~ "blaNDM",
    str_detect(gene, "blaCTX-M") ~ "blaCTX-M",
    str_detect(gene, "blaOXY|blaLAP|blaDHA|blaCMY|OKP|blaSCO") ~ str_extract(gene, ".*(?=-[^-]*$)"),
    TRUE ~ gene)
    )

upset <-
upset %>%
  select(isolate_code,
         gene_cat) %>%
  distinct() %>%
  left_join(isolates_of_top7STs_EDITED %>%
              select(isolate_code,
                     ST,
                     location,
                     source),
            by = "isolate_code")

upset<-
upset %>%
  pivot_wider(names_from = gene_cat,
              values_from = gene_cat,
              values_fill = FALSE,
              values_fn = ~ TRUE)

colnames(upset)[5:18]

# ordering the same as phenotypic resistance by drug class plot
sets_ordered <- c(
  # Carbapenems
  "blaOXA-48-Like",
  "blaOXA-Type",
  "blaKPC",
  "blaNDM",
  "blaVIM",
  # other Bla
  #"blaSHV-Acquired",
  "blaSHV-Chromosomal",
  "blaCTX-M",
  "blaCMY",
  "blaSCO",
  #"blaDHA",
  "blaLAP",
  "blaOXY-1"
  #"blaCARB-2"
  )

# reversing the column order to reorder columns (keeping other columns intact)
upset <- upset[, c(colnames(upset)[1:4], rev(sets_ordered))]

# italicising column names
colnames(upset)[5:15] <- paste0("*", colnames(upset)[5:15], "*")

# defining sets
# BE CAREFUL TO LIST CORRECT COLUMNS- the above code filters by n() < X based on plotting
sets <- as.character(colnames(upset)[5:15])
sets

presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
    aggregate(
        as.formula(paste0(presence, "~ intersection")),
        df,
        FUN=sum
    )
}

# plotting
upset(as.data.frame(upset),
      sets,
      stripes = "white",
      sort_sets=FALSE,
      name = "\n Antimicrobial Resistance Gene Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=2,
      base_annotations=list(
        # checking counts
        #"Intersection size"=intersection_size(counts=TRUE),
        "Count"=(
            ggplot() +
              geom_bar(
                data=summarise_values,
                stat="identity",
                aes(y = !!presence),
                alpha=0.8,
                fill="#008080")+
              #ylim(0,10) +
              scale_y_continuous(labels = scales::number_format(accuracy = 1)) +
              ylab("Number of Genomes") +
              theme(axis.title.y = element_text(vjust = -20),
                    legend.title = element_blank(),
                    legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")))),
      annotations = list(
        "Location"=(
            ggplot(mapping=aes(fill=as.factor(location))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion of Genomes (%)",
                   fill="Location") +
              theme(axis.title.y = element_text(vjust = -20,hjust=-20),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(
                    values = c(
                      "London, UK" = "#3B4992",
                      "Other, UK" = "#D3D3D3",
                      "Western Europe" = "#EE0000",
                      "Eastern Europe" = "#008B45",
                      "Middle East" = "#808180",
                      "Northern Europe" = "#631879",
                      "North America" = "#FFA500",
                      "Southeast Asia" = "#FF7F50",
                      "East Asia" = "#00B2EE",
                      "South Asia" = "#FFD700",
                      "Oceania" = "#9370DB",
                      "Sub-Saharan Africa" = "#A20056",
                      "East Africa" = "#D55E00",
                      "West Africa" = "#E69F00"
                    )
                  ) +
              guides(fill=guide_legend(title="Location",
                                       ncol = 2))
              ),
        "Source"=(
            ggplot(mapping=aes(fill=as.factor(source))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion of Genomes (%)",
                   fill="Source") +
              theme(axis.title.y = element_blank(),
                    #legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(values = c(
                    "Blood" = "#D73027",
                    "Urine" = "#FEE08B",
                    "Wound or Soft Tissue" = "#4575B4",
                    "Respiratory" = "#74ADD1",
                    "Faeces" = "#A6D96A",
                    "Rectal Swab" = "#FDAE61",
                    "Screening Swab" = "#F46D43",
                    "Bile" = "#66C2A5",
                    "Catheter" = "#E6AB02",
                    "Cerebrospinal Fluid" = "#9E0142",
                    "Sterile Site" = "#5E4FA2",
                    "Other Secretion" = "#ABD9E9",
                    "Not Reported" = "#B0B0B0")) +
              guides(fill=guide_legend(title="Source",
                                       ncol = 2))
        )),
        set_sizes=(
            upset_set_size(
                geom=geom_bar(width=0.9,
                              aes(y=..count..),
                              alpha=0.8),
            ) +
              ylab("\nNumber of Genomes")),
      # colouring by drug class
        queries = list(
          # Carbapenems
          upset_query(set = "*blaOXA-48-Like*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaOXA-Type*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaKPC*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaNDM*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaVIM*", fill = "#EE0000CC", color_by = "fill"),
        
          # β-Lactams (inc. Cephalosporins)
          upset_query(set = "*blaSHV-Chromosomal*", fill = "#008B45CC", color_by = "fill"),
          #upset_query(set = "*blaSHV-Acquired*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaTEM*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaCTX-M*", fill = "#008B45CC", color_by = "fill"),
          #upset_query(set = "*blaCMY*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaSCO*", fill = "#008B45CC", color_by = "fill"),
          #upset_query(set =  "*blaDHA*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set =   "*blaLAP*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set =   "*blaOXY-1*", fill = "#008B45CC", color_by = "fill")
          #upset_query(set =  "*blaCARB-2*", fill = "#008B45CC", color_by = "fill")
          )
              ) +
  theme(axis.text.y = element_markdown())


ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/.jpeg",
       width=11.75,
       height=10)
```
# figure: bla gene resistance profiles by ST
```{r}
# checking for acquired SHV  genes in kleborate data
isolates_of_top7STs_EDITED %>%
  filter(if_any(c(Bla_acquired:Bla_Carb_acquired), ~ str_detect(.x, "SHV")))

# defining SHV acquired genes using kleborate data
SHV_acquired <- c("blaSHV-49^", "blaSHV-2A^", "blaSHV-2", "blaSHV-30", "blaSHV-31.v1*")

# creating upset data
upset <-
all_args_gl  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             # same order as in phenotypic profiles plot
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (inc. Cephalosporins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide|Trimethoprim") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
      select(-drug) %>%
  # filtering "Other" genes
  filter(drug_class!="Other")

# checking drug class levels
levels(as.factor(upset$drug_class))

upset <-
upset %>%
filter(str_detect(gene, "bla")) %>%
  # collapsing genes
  mutate(gene_cat = case_when(
    str_detect(gene, "blaTEM") ~ "blaTEM",
    str_detect(gene, "OXA-181|OXA-48|OXA-162|OXA-232|OXA-244") ~ "blaOXA-48-Like",
    str_detect(gene, "OXA-1|OXA-10|OXA-9|OXA-534") ~ "blaOXA-Type",
    str_detect(gene, "KPC-2|KPC-3") ~ "blaKPC",
    str_detect(gene, "VIM") ~ "blaVIM",
    str_detect(gene, "NDM") ~ "blaNDM",
    str_detect(gene, "blaCTX-M") ~ "blaCTX-M",
    str_detect(gene, "blaOXY|blaLAP|blaDHA|blaCMY|OKP|blaSCO") ~ str_extract(gene, ".*(?=-[^-]*$)"),
    TRUE ~ gene)
    )

upset <-
upset %>%
  select(isolate_code,
         gene_cat) %>%
  distinct() %>%
  left_join(isolates_of_top7STs_EDITED %>%
              select(isolate_code,
                     ST,
                     location,
                     source),
            by = "isolate_code")

upset<-
upset %>%
  pivot_wider(names_from = gene_cat,
              values_from = gene_cat,
              values_fill = FALSE,
              values_fn = ~ TRUE)

colnames(upset)[5:18]

# ordering the same as phenotypic resistance by drug class plot
sets_ordered <- c(
  # Carbapenems
  "blaOXA-48-Like",
  "blaOXA-Type",
  "blaKPC",
  "blaNDM",
  "blaVIM",
  # other Bla
  #"blaSHV-Acquired",
  "blaSHV-Chromosomal",
  "blaCTX-M",
  "blaCMY",
  "blaSCO",
  #"blaDHA",
  "blaLAP",
  "blaOXY-1"
  #"blaCARB-2"
  )

# reversing the column order to reorder columns (keeping other columns intact)
upset <- upset[, c(colnames(upset)[1:4], rev(sets_ordered))]

# italicising column names
colnames(upset)[5:15] <- paste0("*", colnames(upset)[5:15], "*")

# defining sets
# BE CAREFUL TO LIST CORRECT COLUMNS- the above code filters by n() < X based on plotting
sets <- as.character(colnames(upset)[5:15])
sets

presence = ComplexUpset:::get_mode_presence("exclusive_intersection")

summarise_values = function(df) {
    aggregate(
        as.formula(paste0(presence, "~ intersection")),
        df,
        FUN=sum
    )
}

upset <-
  upset  %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147")))

# plotting
upset(as.data.frame(upset),
      sets,
      stripes = "white",
      sort_sets=FALSE,
      name = "\n Antimicrobial Resistance Gene Profile",
      width_ratio = 0.2,
      height_ratio = 1.5,
      min_size=2,
      base_annotations=list(
        # checking counts
        #"Intersection size"=intersection_size(counts=TRUE),
        "Count"=(
            ggplot() +
              geom_bar(
                data=summarise_values,
                stat="identity",
                aes(y = !!presence),
                alpha=0.8,
                fill="#008080")+
              #ylim(0,10) +
              scale_y_continuous(labels = scales::number_format(accuracy = 1)) +
              ylab("Number of Genomes") +
              theme(axis.title.y = element_text(vjust = -20),
                    legend.title = element_blank(),
                    legend.position = c(0.47, 0.43),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")))),
      annotations = list(
        "ST"=(
            ggplot(mapping=aes(fill=as.factor(ST))) +
              geom_bar(stat="count", position="fill",alpha=0.8) +
              scale_y_continuous(labels=percent_format()) +
              #scale_fill_manual(values=c("#fff2cc","#ffd966","#bf9000","black")) +
              labs(y="Proportion of Genomes (%)") +
              theme(axis.title.y = element_text(vjust = -20),
                    legend.title = element_blank(),
                    legend.margin=margin(4,4,4,4, unit = "mm"),
                    legend.box.background=element_rect(colour = "black"),
                    legend.background = element_rect(fill = "white")) +
              scale_fill_manual(values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f"))
                  )
              ),
        set_sizes=(
            upset_set_size(
                geom=geom_bar(width=0.9,
                              aes(y=..count..),
                              alpha=0.8),
            ) +
              ylab("\nNumber of Genomes")),
      # colouring by drug class
        queries = list(
          # Carbapenems
          upset_query(set = "*blaOXA-48-Like*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaOXA-Type*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaKPC*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaNDM*", fill = "#EE0000CC", color_by = "fill"),
          upset_query(set = "*blaVIM*", fill = "#EE0000CC", color_by = "fill"),
        
          # β-Lactams (inc. Cephalosporins)
          upset_query(set = "*blaSHV-Chromosomal*", fill = "#008B45CC", color_by = "fill"),
          #upset_query(set = "*blaSHV-Acquired*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaTEM*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaCTX-M*", fill = "#008B45CC", color_by = "fill"),
          #upset_query(set = "*blaCMY*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set = "*blaSCO*", fill = "#008B45CC", color_by = "fill"),
          #upset_query(set =  "*blaDHA*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set =   "*blaLAP*", fill = "#008B45CC", color_by = "fill"),
          upset_query(set =   "*blaOXY-1*", fill = "#008B45CC", color_by = "fill")
          #upset_query(set =  "*blaCARB-2*", fill = "#008B45CC", color_by = "fill")
          )
              ) +
  theme(axis.text.y = element_markdown())


ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/22_genomic_resistance_profiles_gl_by_ST.jpeg",
       width=11.75,
       height=8.5)
```

*hypervirulence/convergence*
====================================================================================================================================
# figure: number of resistance genes by HvKp genotype
```{r}
isolates_of_top7STs_EDITED %>%
  mutate(n_HvKp_genes = rowSums(across(iuc_locus:peg344_locus, ~ . == "TRUE"))) %>%
  # how to define HvKp?
  mutate(actual_HvKp = if_else(n_HvKp_genes == 5,"HvKp","CKp")) %>%
  select(isolate_code,
         genomic_hypervirulence,
         n_HvKp_genes,
         actual_HvKp) %>%
  left_join(abricate_gl %>%
              group_by(isolate_code,ST) %>%
              summarise(n_AMR_genes = n()) %>%
              ungroup(),
            by = "isolate_code") %>%
  # reordering factors
  mutate(ST = factor(ST,
                     # reversing usual factor levels
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  group_by(ST,genomic_hypervirulence) %>%
  mutate(label = paste0("n=",n()),
         yval=max(n_AMR_genes)) %>%
  ungroup() %>%
#View()
  ggplot(aes(x=ST,y=n_AMR_genes)) +
  geom_jitter(width = 0.3,
              size=0.1,
              colour="black") +
  geom_violin(alpha=0.9,
              width = 1,
              linewidth = 0.3,
              aes(fill = genomic_hypervirulence,colour=genomic_hypervirulence)) +
  stat_summary(aes(group = genomic_hypervirulence),fun = mean, geom = "point", shape = 23, size = 4, fill = "grey", color = "grey",position = position_dodge(width = 1)) +
  geom_text(aes(group = genomic_hypervirulence, x = ST, y = yval+2, label = label),
            size = 3, inherit.aes = FALSE, position = position_dodge(width = 1)) +
  #facet_wrap(~genomic_hypervirulence) +
  theme_bw() +
  # sizing
  theme(axis.title.x = element_blank(),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  labs(x="Sequence Type",
       y="Number of Resistance Genes",
       fill="Hypervirulence Genotype") +
  guides(colour=FALSE) +
  scale_colour_manual(values = c("HvKp-" = "#008080", "HvKp+" = "#FFA500")) +
  scale_fill_manual(
  values = c("HvKp-" = "#008080", "HvKp+" = "#FFA500"),
  guide = guide_legend(override.aes = list(colour = NA)))

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/23_no_AMR_genes_HvKp_genotype.jpeg",
       width=10,
       height=5)

# associated statistical tests
isolates_of_top7STs_EDITED %>%
  mutate(n_HvKp_genes = rowSums(across(iuc_locus:peg344_locus, ~ . == "TRUE"))) %>%
  select(isolate_code,
         genomic_hypervirulence,
         n_HvKp_genes) %>%
  left_join(abricate_gl %>%
              group_by(isolate_code,ST) %>%
              summarise(n_AMR_genes = n()) %>%
              ungroup(),
            by = "isolate_code") %>%
  # reordering factors
  mutate(ST = factor(ST,
                     # reversing usual factor levels
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  group_by(ST,genomic_hypervirulence) %>%
  mutate(label = paste0("n=",n()),
         yval=max(n_AMR_genes)) %>%
  ungroup() %>%
  group_by(ST) %>%
  # stat tests
  summarise(p = tryCatch(
    wilcox.test(n_AMR_genes ~ genomic_hypervirulence)$p.value,
    error = function(e) NA
  ))
```
# figure: number of HvKp genes by ST
```{r}
isolates_of_top7STs_EDITED %>%
  select(isolate_code,
         ST,
         irp2_locus,
         rmpA_locus,
         iro_locus,
         iuc_locus,
         peg344_locus,
         irp2,
         rmpA,
         iro,
         iuc,
         peg344,
         resistance_profile,
         genomic_hypervirulence,
         genomic_convergence) %>%
  pivot_longer(cols = c(irp2:peg344),
               names_to = "vir_locus",
               values_to = "vir_gene") %>%
  # tidying gene columns
  mutate(vir_gene=if_else(vir_locus == "irp2" &
                            !is.na(vir_gene), "*irp2*", vir_gene)) %>%
  mutate(vir_gene=if_else(vir_gene == "*rmpA2**", "*rmpA2*", vir_gene)) %>%
  distinct() %>%
  # filtering blank data records
  filter(!is.na(vir_gene)) %>%
  group_by(ST, isolate_code) %>%
  count() %>%
  ungroup() %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  group_by(ST) %>%
  mutate(label = paste0("n=",n()),
         yval=max(n)) %>%
  ungroup() %>%
  ggplot(aes(x=ST,
             y=n)) +
  geom_jitter(width = 0.4, size=0.1,colour="black") +
  geom_violin(alpha=0.9, width = 1,linewidth = 0.3,aes(fill = ST,colour=ST)) +
  #stat_summary(fun = median, geom = "point", shape = 23, size = 4, fill = "grey", color = "grey") +
  geom_text(aes(x = ST, y = yval+0.5, label = label),
            size = 3, inherit.aes = FALSE) +
  #scale_y_continuous(breaks = c(0,10,20,30)) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_text(vjust = 2)) +
  scale_fill_npg() +
  scale_colour_npg() +
  labs(x="Sequence Type",
       y="Number of HvKp Genes") +
  guides(fill=FALSE,colour=FALSE) +
  scale_fill_manual(values = c("ST15" = "#6376a0",
                               "ST37" =  "#a6dace",
                               "ST307" =  "#9da6c3",
                               "ST133" =  "#71c9dd",
                               "ST23" =  "#f5af98",
                               "ST13" =  "#ea705d",
                               "ST147" =  "#33b29f")) +
  scale_colour_manual(values = c("ST15" = "#6376a0",
                               "ST37" =  "#a6dace",
                               "ST307" =  "#9da6c3",
                               "ST133" =  "#71c9dd",
                               "ST23" =  "#f5af98",
                               "ST13" =  "#ea705d",
                               "ST147" =  "#33b29f")) +
  guides(fill=FALSE,colour=FALSE)

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       width=10,
       height=5)
```

*k-o locus serotype predictions*
====================================================================================================================================
# figure: cumulative proportions of k loci by source/ST
```{r}
isolates_of_top7STs_EDITED %>%
  # removing any 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341"))  %>%
  # removing duplicates
  distinct() %>%
  select(isolate_code,
         ST,
         source,
         K_locus) %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # counting per ST
  group_by(ST) %>%
  mutate(STlabel = paste0(ST," (n=",n(),")")) %>%
  ungroup() %>%
  # counting per source
  group_by(source) %>%
  mutate(sourcelabel = paste0(source," (n=",n(),")")) %>%
  ungroup() %>%
  # reordering labels to match columns
  mutate(STlabel = factor(STlabel, levels = unique(STlabel[match(levels(ST), ST)])),
         sourcelabel = factor(sourcelabel, levels = unique(sourcelabel[match(levels(source), source)]))) %>%
  group_by(STlabel,sourcelabel) %>%
  count(K_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  group_modify(~ bind_rows(tibble(K_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0), .x)) %>%
  arrange(STlabel,sourcelabel, rank) %>%
  ungroup() %>%
#View()
  ggplot(aes(x = rank, y = cum_prop,colour=sourcelabel)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "Number of K Loci") +
  guides(colour=guide_legend(title="Source",
                           ncol = 3)) +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.position = c(0.6,0.11),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  scale_colour_manual(values = c(
  "#D73027",
  "#FEE08B",
  "#4575B4",
  "#74ADD1",
  "#A6D96A",
  "#FDAE61",
  "#F46D43",
  "#66C2A5",
  "#E6AB02",
  "#9E0142",
  "#5E4FA2",
  "#ABD9E9",
  "#B0B0B0"
)) +
  facet_wrap(STlabel~.,)
  
ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       height=8,
       width=11.7)
```
# figure: cumulative proportions of o loci by source/ST
```{r}
isolates_of_top7STs_EDITED %>%
  # removing any 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341"))  %>%
  # removing duplicates
  distinct() %>%
  select(isolate_code,
         ST,
         source,
         O_locus) %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # counting per ST
  group_by(ST) %>%
  mutate(STlabel = paste0(ST," (n=",n(),")")) %>%
  ungroup() %>%
  # counting per source
  group_by(source) %>%
  mutate(sourcelabel = paste0(source," (n=",n(),")")) %>%
  ungroup() %>%
  # reordering labels to match columns
  mutate(STlabel = factor(STlabel, levels = unique(STlabel[match(levels(ST), ST)])),
         sourcelabel = factor(sourcelabel, levels = unique(sourcelabel[match(levels(source), source)]))) %>%
  group_by(STlabel,sourcelabel) %>%
  count(O_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  group_modify(~ bind_rows(tibble(K_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0), .x)) %>%
  arrange(STlabel,sourcelabel, rank) %>%
  ungroup() %>%
#View()
  ggplot(aes(x = rank, y = cum_prop,colour=sourcelabel)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "Number of K Loci") +
  guides(colour=guide_legend(title="Source",
                           ncol = 3)) +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        legend.position = c(0.6,0.11),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  scale_colour_manual(values = c(
  "#D73027",
  "#FEE08B",
  "#4575B4",
  "#74ADD1",
  "#A6D96A",
  "#FDAE61",
  "#F46D43",
  "#66C2A5",
  "#E6AB02",
  "#9E0142",
  "#5E4FA2",
  "#ABD9E9",
  "#B0B0B0"
)) +
  facet_wrap(STlabel~.,)
  
ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       height=8,
       width=11.7)
```
# figure: cumulative proportions of k loci by location
```{r}
isolates_of_top7STs_EDITED %>%
  # removing any 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         location,
         K_locus) %>%
  # counting per location
  group_by(location) %>%
  mutate(locationlabel = paste0(location," (n=",n(),")")) %>%
  ungroup() %>%
  # reordering labels to match columns
  mutate(locationlabel = factor(locationlabel, levels = unique(locationlabel[match(levels(location), location)]))) %>%
  group_by(locationlabel) %>%
  count(K_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  group_modify(~ bind_rows(tibble(K_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0), .x)) %>%
  arrange(locationlabel, rank) %>%
  ungroup() %>%
#View()
  ggplot(aes(x = rank, y = cum_prop,colour=locationlabel)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "Number of K Loci",
       colour = "Location") +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black")) +
  scale_colour_manual(
  values = c(
  "#3B4992",
  "#D3D3D3",
  "#EE0000",
  "#008B45",
  "#808180",
  "#631879",
  "#FFA500",
  "#FF7F50",
  "#00B2EE",
  "#FFD700",
  "#9370DB",
  "#A20056",
  "#D55E00",
  "#E69F00"
)
)
  
ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       height = 5,
       width = 10)
```
# figure: cumulative proportions of o loci by location
```{r}
isolates_of_top7STs_EDITED %>%
  # removing any 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         location,
         O_locus) %>%
  # counting per location
  group_by(location) %>%
  mutate(locationlabel = paste0(location," (n=",n(),")")) %>%
  ungroup() %>%
  # reordering labels to match columns
  mutate(locationlabel = factor(locationlabel, levels = unique(locationlabel[match(levels(location), location)]))) %>%
  group_by(locationlabel) %>%
  count(O_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  group_modify(~ bind_rows(tibble(O_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0), .x)) %>%
  arrange(locationlabel, rank) %>%
  ungroup() %>%
#View()
  ggplot(aes(x = rank, y = cum_prop,colour=locationlabel)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "Number of O Loci",
       colour = "Location") +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black")) +
  scale_colour_manual(
  values = c(
  "#3B4992",
  "#D3D3D3",
  "#EE0000",
  "#008B45",
  "#808180",
  "#631879",
  "#FFA500",
  "#FF7F50",
  "#00B2EE",
  "#FFD700",
  "#9370DB",
  "#A20056",
  "#D55E00",
  "#E69F00"
)
)
  
ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       height = 5,
       width = 10)
```
# figure: cumulative proportions of k loci by ST only
```{r}
isolates_of_top7STs_EDITED %>%
  # removing any 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         ST,
         K_locus)  %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # counting per ST
  group_by(ST) %>%
  mutate(STlabel = paste0(ST," (n=",n(),")")) %>%
  ungroup() %>%
  # reordering labels to match columns
  mutate(STlabel = factor(STlabel, levels = unique(STlabel[match(levels(ST), ST)]))) %>%
  group_by(STlabel) %>%
  count(K_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  group_modify(~ bind_rows(tibble(K_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0), .x)) %>%
  arrange(STlabel, rank) %>%
  ungroup() %>%
#View()
  ggplot(aes(x = rank, y = cum_prop,colour=STlabel)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "Number of K Loci",
       colour = "Location") +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.title = element_blank(),
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black")) +
  scale_colour_manual(values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f"))

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       height = 5,
       width = 10)
```
# figure: cumulative proportions of o loci by ST only
```{r}
isolates_of_top7STs_EDITED %>%
  # removing any 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  select(isolate_code,
         ST,
         O_locus)  %>%
  # reordering factors
  mutate(ST = factor(ST,
                     levels = c("ST15","ST37","ST307","ST133","ST23","ST13","ST147"))) %>%
  # counting per ST
  group_by(ST) %>%
  mutate(STlabel = paste0(ST," (n=",n(),")")) %>%
  ungroup() %>%
  # reordering labels to match columns
  mutate(STlabel = factor(STlabel, levels = unique(STlabel[match(levels(ST), ST)]))) %>%
  group_by(STlabel) %>%
  count(O_locus, name = "n") %>%
  arrange(desc(n)) %>%
  mutate(rank = row_number(),
         cum_n = cumsum(n),
         cum_prop = cum_n / sum(n)) %>%
  # adding origin row
  group_modify(~ bind_rows(tibble(O_locus = NA, n = 0, rank = 0, cum_n = 0, cum_prop = 0), .x)) %>%
  arrange(STlabel, rank) %>%
  ungroup() %>%
#View()
  ggplot(aes(x = rank, y = cum_prop,colour=STlabel)) +
  geom_step() +
  theme_bw() +
  labs(y = "Cumulative Proportion (%)",
       x = "Number of O Loci",
       colour = "Location") +
  scale_y_continuous(limits=c(0,1),labels = percent_format(accuracy = 1)) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # add legend box
        legend.title = element_blank(),
        legend.background=element_blank(), 
        # ensuring even legend border
        legend.margin=margin(4,4,4,4, unit = "mm"),
        legend.box.background=element_rect(colour = "black")) +
  scale_colour_manual(values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f"))

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       height = 5,
       width = 10)
```
# figure: k-o locus combinations across genomic resistance and hypervirulence profiles
```{r}
char_genomes_gl %>%
  # labelling unknown K loci
  mutate(K_locus = if_else(str_detect(K_locus,"unknown"), "Unknown", K_locus))  %>%
  # redifing genomic_hypervirulence to not include irp2 (coment out as appropriate)
  mutate(genomic_hypervirulence = if_else(
    if_any(c(iuc_locus, iro_locus, rmpA_locus, peg344_locus), ~ . == TRUE),
    # carries HvKp genes (except irp2)
    "HvKp+", 
    # does not carry HvKp genes
    "HvKp-"
  )) %>%
  # reordering levels
  mutate(genomic_hypervirulence = factor(genomic_hypervirulence, levels = c("HvKp-", "HvKp+"))) %>%
  # labelling top 20 K loci
  mutate(K_locus = if_else(K_locus %in% c("KL2",
                                          "KL102",
                                          "KL112",
                                          "KL24",
                                          "KL116",
                                          "KL38",
                                          "KL62",
                                          "KL25",
                                          "KL3",
                                          "KL15",
                                          "KL28",
                                          "KL1",
                                          "KL30",
                                          "KL48",
                                          "KL14",
                                          "KL54",
                                          "KL10",
                                          "KL114",
                                          "KL23",
                                          "KL27",
                                          "Unknown"
                                          ), K_locus, "Other"))  %>%
  # labelling unknown O loci
  mutate(O_locus = if_else(str_detect(O_locus,"unknown"), "Unknown", O_locus)) %>%
  # relevelling factors
  # ST15, ST37, ST307, ST133, ST23, ST13, and ST147
  mutate(ST=fct_relevel(ST,c("ST15",
                                       "ST37",
                                       "ST307",
                                       "ST133",
                                       "ST23",
                                       "ST13",
                                       "ST147"))) %>%
  # tallying loci
  group_by(ST,resistance_profile,genomic_hypervirulence,K_locus,O_locus) %>%
  # filtering by most commmon combinations
  #filter(n()>1) %>%
  tally() %>%
  ungroup() %>%
  # reordering y axis - need to be explicit
  mutate(K_locus = fct_relevel(K_locus,
  "Unknown", "Other", "KL62", "KL48", "KL38", "KL30",
  "KL3", "KL28", "KL24", "KL23", "KL2", "KL15",
  "KL14", "KL116", "KL112", "KL102", "KL10", "KL1")) %>%
  # relevelling factor
  ggplot(aes(x=O_locus,
             y=K_locus,
             size=n,
             colour=ST)) +
  geom_jitter(
  alpha = 0.5,
  position = position_jitter(width = 0.025)) +
  scale_size(range = c(2, 10)) +
  labs(colour= "Sequence Type",
  y="K Locus (Capsular Polysaccharide)",
  x="O Locus (Lipopolysaccharide)") +
  theme_bw() +
  guides(size=F,alpha=F) +
  theme(axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11),
        # add legend box
        legend.background=element_blank(), 
        # removing legend title
        legend.title = element_blank(),
        # ensuring even legend border
        legend.margin=margin(1,4,2,3, unit = "mm"),
        legend.box.background=element_rect(colour = "black"),
        #plot title for pannelled figure
        plot.title = element_text(hjust = 0.5),
        plot.margin = margin(0,0.5,0.5,0.5, "cm")) +
  scale_colour_manual(labels = c("ST15 (n=197)",
                               "ST37 (n=101)",
                               "ST307 (n=210)",
                               "ST133 (n=28)",
                               "ST23 (n=77)",
                               "ST13 (n=21)",
                               "ST147 (n=21)"),
                      values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f",
                               "#008080")) +
  facet_grid(resistance_profile~genomic_hypervirulence)

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/8_comparison_to_global_genomes/global_ko_locus_combinations.jpeg",
       height=11.69,
       width=8.27)
```

*plasmids*
====================================================================================================================================
# figure:  plasmid types - drug classes
```{r}
all_args_gl  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (Inc. Cephalosporins\n& Penicillins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             #str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
  # filtering "Other" genes
  filter(drug_class != "Other") %>%
      select(-drug) %>%
  filter(!is.na(plasmid_id) &
           # only interested in plasmids that can move
           predicted_mobility %in% c("conjugative",
                                     "mobilizable")) %>%
  mutate(predicted_mobility = str_to_title(predicted_mobility)) %>%
  # creating unknown replicon type
  mutate(`rep_type(s)` = replace(`rep_type(s)`, is.na(`rep_type(s)`), "Unknown")) %>%
  # separating relaxase column into the 3 distinct types + unknowns
  separate(`relaxase_type(s)`, c("relaxase1","relaxase2"), sep = ',') %>%
  # creating unknown relaxase type
  mutate(`relaxase_type(s)` = if_else(is.na(relaxase1), "Unknown", relaxase1)) %>%
  select(-c(relaxase1,
            relaxase2)) %>%
  # any instances where these two contradict?
  # CHECKED = no instances
  #filter(relaxase1 != relaxase2) %>%
#View()
  # can expand plasmid definitions as analysis progresses
  # creating repgroup for easier classification
  mutate(
    repgroup = case_when(
      str_detect(`rep_type(s)`, "IncFIA|IncFIB|IncFII") ~ "IncF (Hybrid)",
      str_detect(`rep_type(s)`, "IncC") ~ "IncC",
      str_detect(`rep_type(s)`, "IncHI") ~ "IncHI (Hybrid)",
      str_detect(`rep_type(s)`, "IncX") ~ "IncX",
      str_detect(`rep_type(s)`, "IncI") ~ "IncI",
      str_detect(`rep_type(s)`, "IncR") ~ "IncR",
      str_detect(`rep_type(s)`, "IncN") ~ "IncN",
      str_detect(`rep_type(s)`, "ColRNAI") ~ "ColRNAI",
      str_detect(`rep_type(s)`, "Unknown") ~ "Unknown",
      str_detect(`rep_type(s)`, "rep_cluster") ~ "Unclassified Cluster",
      TRUE ~ `rep_type(s)`
    )
  ) %>%
  mutate(plasmid_identity = paste(#plasmid_id,
                                  #size,
                                  repgroup,
                                  `relaxase_type(s)`,
                                  sep = "--")) %>%
  group_by(repgroup,`relaxase_type(s)`,drug_class,predicted_mobility) %>%
  tally() %>%  
  ungroup() %>%
  # ordering drug classes to match (as closely as possible) those from phenotypic resistance plot
  mutate(drug_class = fct_relevel(drug_class,
    "Aminoglycosides",
    "Carbapenems",
    "β-Lactams (Inc. Cephalosporins\n& Penicillins)",
    "Fluoroquinolones",
    #"Macrolides",
    "Sulfonamides")) %>%
#View()
  #arrange(desc(n))
  ggplot(aes(x=`relaxase_type(s)`,
             y=fct_rev(repgroup),
             size=n,
             colour=drug_class)) +
  geom_jitter(position = position_jitter(width = .3), alpha=0.7)  +
  scale_size(range = c(2, 10)) +
  theme_bw() +
  theme(# add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  labs(x="Relaxase Type",
       y="Replicon Type",
       colour="Drug Class")  +
  # legend spacing and outline (important)
  guides(fill=guide_legend(ncol = 1,
                           byrow = TRUE),
         size=F) +
  facet_grid(~predicted_mobility) +
  scale_colour_aaas()

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/4_mges/plasmids_by_drug_class_global.jpeg",
       width=10,
       height=4)
```
# figure: plasmid types - STs - ICHNT only
```{r}
all_args_gl  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341"))  %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (Inc. Cephalosporins\n& Penicillins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             #str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
  # filtering "Other" genes
  filter(drug_class != "Other") %>%
#View()
  filter(!is.na(plasmid_id) &
           # only interested in plasmids that can move
           predicted_mobility %in% c("conjugative",
                                     "mobilizable")) %>%
  mutate(predicted_mobility = str_to_title(predicted_mobility)) %>%
  # creating unknown replicon type
  mutate(`rep_type(s)` = replace(`rep_type(s)`, is.na(`rep_type(s)`), "Unknown")) %>%
  # separating relaxase column into the 3 distinct types + unknowns
  separate(`relaxase_type(s)`, c("relaxase1","relaxase2"), sep = ',') %>%
  # creating unknown relaxase type
  mutate(`relaxase_type(s)` = if_else(is.na(relaxase1), "Unknown", relaxase1)) %>%
  select(-c(relaxase1,
            relaxase2)) %>%
  # any instances where these two contradict?
  # CHECKED = no instances
  #filter(relaxase1 != relaxase2) %>%
#View()
  # can expand plasmid definitions as analysis progresses
  # creating repgroup for easier classification
  mutate(
    repgroup = case_when(
      str_detect(`rep_type(s)`, "IncFIA|IncFIB|IncFII") ~ "IncF (Hybrid)",
      str_detect(`rep_type(s)`, "IncC") ~ "IncC",
      str_detect(`rep_type(s)`, "IncHI") ~ "IncHI (Hybrid)",
      str_detect(`rep_type(s)`, "IncX") ~ "IncX",
      str_detect(`rep_type(s)`, "IncI") ~ "IncI",
      str_detect(`rep_type(s)`, "IncR") ~ "IncR",
      str_detect(`rep_type(s)`, "IncN") ~ "IncN",
      str_detect(`rep_type(s)`, "ColRNAI") ~ "ColRNAI",
      str_detect(`rep_type(s)`, "Unknown") ~ "Unknown",
      str_detect(`rep_type(s)`, "rep_cluster") ~ "Unclassified Cluster",
      TRUE ~ `rep_type(s)`
    )
  ) %>%
  mutate(plasmid_identity = paste(#plasmid_id,
                                  #size,
                                  repgroup,
                                  `relaxase_type(s)`,
                                  sep = "--")) %>%
#View()
  group_by(repgroup,`relaxase_type(s)`,ST,predicted_mobility) %>%
  tally() %>%
#View()
  #arrange(desc(n))
  ggplot(aes(x=`relaxase_type(s)`,
             y=fct_rev(repgroup),
             size=n,
             colour=ST)) +
  geom_jitter(position = position_jitter(width = .3), alpha=0.7)  +
  scale_size(range = c(1, 10)) +
  theme_bw() +
  theme(# add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  labs(x="Relaxase Type",
       y="Replicon Type",
       colour=NULL)  +
  # legend spacing and outline (important)
  guides(size=F) +
  facet_grid(~predicted_mobility) +
  scale_colour_manual(labels = c("ST15 (n=197)",
                               "ST37 (n=101)",
                               "ST307 (n=210)",
                               "ST133 (n=28)",
                               "ST23 (n=77)",
                               "ST13 (n=21)",
                               "ST147 (n=20)"),
                    values = c("#6376a0",
                               "#a6dace",
                               "#9da6c3",
                               "#71c9dd",
                               "#f5af98",
                               "#ea705d",
                               "#33b29f"))

ggsave(plot=last_plot(),
       #"/Users/jonahrodgus/Desktop/new.jpeg",
       "/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/4_mges/plasmids_by_st_global.jpeg",
       width=10,
       height=4)
```
# figure: plasmid sizes of plasmids carrying amr genes
```{r}
# preventing standard form
options(scipen = 999)

all_args_gl  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  # assigning "SHV_acquired" to only those SHV genes that can be acquired
  mutate(gene = if_else(gene %in% SHV_acquired, "blaSHV-Acquired",gene)) %>%
  mutate(gene = if_else(str_detect(gene, "SHV") & gene != "blaSHV-Acquired", "blaSHV-Chromosomal", gene)) %>%
  # defining drug classes as closely to drug classes used in 0_clinical_characterisation.Rmd as possible
  # β-Lactam classication is tricky as it is different in abricate data compared to drug classes used in 0_clinical_characterisation.Rmd 
  mutate(drug = str_to_title(as.character(drug)),
         drug_class = 
           case_when(
             # same order as in phenotypic profiles plot
             str_detect(drug, "Amikacin|Gentamicin|Kanamycin|Tobramycin|Aminoglycoside|Streptomycin") ~ "Aminoglycosides",
             str_detect(drug, "Carbapenem") ~ "Carbapenems",
             str_detect(drug, "Beta-Lactam|Cephalosporin") ~ "β-Lactams (inc. Cephalosporins)",
             str_detect(drug, "Quinolone") ~ "Fluoroquinolones",
             str_detect(drug, "Macrolide") ~ "Macrolides",
             str_detect(drug, "Sulfonamide") ~ "Sulfonamides",
             TRUE ~ "Other")) %>%
      select(-drug) %>%
  filter(!is.na(plasmid_id) &
           # only interested in plasmids that can move
           predicted_mobility %in% c("conjugative",
                                     "mobilizable")) %>%
  mutate(predicted_mobility = str_to_title(predicted_mobility)) %>%
  # creating unknown replicon type
  mutate(`rep_type(s)` = replace(`rep_type(s)`, is.na(`rep_type(s)`), "Unknown")) %>%
  # separating relaxase column into the 3 distinct types + unknowns
  separate(`relaxase_type(s)`, c("relaxase1","relaxase2"), sep = ',') %>%
  # creating unknown relaxase type
  mutate(`relaxase_type(s)` = if_else(is.na(relaxase1), "Unknown", relaxase1)) %>%
  select(-c(relaxase1,
            relaxase2)) %>%
  # any instances where these two contradict?
  # CHECKED = no instances
  #filter(relaxase1 != relaxase2) %>%
#View()
  # can expand plasmid definitions as analysis progresses
  # creating repgroup for easier classification
  mutate(
    repgroup = case_when(
      str_detect(`rep_type(s)`, "IncFIA|IncFIB|IncFII") ~ "IncF (Hybrid)",
      str_detect(`rep_type(s)`, "IncX") ~ "IncX",
      str_detect(`rep_type(s)`, "IncI") ~ "IncI",
      str_detect(`rep_type(s)`, "IncR") ~ "IncR",
      str_detect(`rep_type(s)`, "IncN") ~ "IncN",
      str_detect(`rep_type(s)`, "ColRNAI") ~ "ColRNAI",
      str_detect(`rep_type(s)`, "Unknown") ~ "Unknown",
      str_detect(`rep_type(s)`, "rep_cluster") ~ "Unclassified Cluster",
      TRUE ~ `rep_type(s)`
    )
  ) %>%
  mutate(plasmid_identity = paste(#plasmid_id,
                                  #size,
                                  repgroup,
                                  `relaxase_type(s)`,
                                  sep = "--")) %>%
  ggplot(aes(x = size,
            #fill = `relaxase_type(s)`
            fill = plasmid_identity
            )) +
  geom_histogram(aes(y = ..count..), 
                 position = "identity", 
                 alpha = 0.4, 
                 bins = 30) +
  theme_bw() +
  theme(# add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  # legend spacing and outline (important)
  guides(fill=guide_legend(ncol = 2,
                           byrow = TRUE),
         size=F) +
  scale_fill_igv() +
  # megaplasmid threshold
  geom_vline(xintercept = 250000,
             linetype = "dashed",
             colour = "grey")+
  labs(title = "Plasmids Carrying ARGs",
       x = "Plasmid Size",
       y = "Count",
       fill = "Plasmid Type")

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       width=20,
       height=8.5)
```
# figure: plasmid sizes of plasmids carrying hvkp markers
```{r}
# preventing standard form
options(scipen = 999)

all_hvkp_markers_gl %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  filter(!is.na(plasmid_id)
           # only interested in plasmids that can move
           #predicted_mobility %in% c("conjugative",
                                     #"mobilizable")
           ) %>%
  mutate(predicted_mobility = str_to_title(predicted_mobility)) %>%
  # creating unknown replicon type
  mutate(`rep_type(s)` = replace(`rep_type(s)`, is.na(`rep_type(s)`), "Unknown")) %>%
  # separating relaxase column into the 3 distinct types + unknowns
  separate(`relaxase_type(s)`, c("relaxase1","relaxase2"), sep = ',') %>%
  # creating unknown relaxase type
  mutate(`relaxase_type(s)` = if_else(is.na(relaxase1) | relaxase1 == "-", "Unknown", relaxase1)) %>%
  select(-c(relaxase1,
            relaxase2)) %>%
  # any instances where these two contradict?
  # CHECKED = no instances
  #filter(relaxase1 != relaxase2) %>%
#View()
  # can expand plasmid definitions as analysis progresses
  # creating repgroup for easier classification
  mutate(
    repgroup = case_when(
      str_detect(`rep_type(s)`, "IncFIA") ~ "IncFIA (Hybrid)",
      str_detect(`rep_type(s)`, "IncFIB") ~ "IncFIB",
      str_detect(`rep_type(s)`, "IncFIB,IncFII|IncFIB,IncHI1B") ~ "IncFIB (Hybrid)",
      str_detect(`rep_type(s)`, "rep_cluster") ~ "Unclassified Cluster",
      TRUE ~ `rep_type(s)`
    )
  ) %>%
  mutate(plasmid_identity = paste(#plasmid_id,
                                  #size,
                                  repgroup,
                                  `relaxase_type(s)`,
                                  sep = "--")) %>%
  ggplot(aes(x = size,
            #fill = `relaxase_type(s)`
            fill = plasmid_identity
            )) +
  geom_histogram(aes(y = ..count..), 
                 position = "identity", 
                 alpha = 0.4, 
                 bins = 30) +
  theme_bw() +
  theme(# add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  # legend spacing and outline (important)
  guides(fill=guide_legend(ncol = 1,
                           byrow = TRUE),
         size=F) +
  scale_fill_igv() +
  # megaplasmid threshold
  geom_vline(xintercept = 250000,
             linetype = "dashed",
             colour = "grey")+
  labs(title = "Plasmids Carrying HvKp Markers",
       x = "Plasmid Size",
       y = "Count",
       fill = "Plasmid Type")

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       width=20,
       height=8.5)
```
# figure: plasmid sizes of plasmids carrying both

  > it looks like big plasmids carrying AMR genes are nearly all exclusive to smaller plasmids carrying virulence genes

```{r}
all_args_gl %>%
  select(isolate_code,
         ST,
         plasmid_id,
         size:predicted_mobility,
         AMR_gene=gene,
         ) %>%
  distinct() %>%
  left_join(all_hvkp_markers_gl %>%
              filter(!is.na(plasmid_id)) %>%
              select(isolate_code,
                     plasmid_id,
                     size,
                     vir_plasmid,
                     variant),
            by = c("isolate_code","plasmid_id","size"))  %>%
  # removing 2022 isolates and duplicates
  filter(isolate_code %!in% c(# 2022 isolates
                              "KLEB389",
                              "KLEB391",
                              # duplicates
                              "KLEB38",
                              "KLEB98",
                              "KLEB341")) %>%
  filter(!is.na(plasmid_id)
           # only interested in plasmids that can move
           #predicted_mobility %in% c("conjugative",
                                     #"mobilizable")
           ) %>%
  mutate(predicted_mobility = str_to_title(predicted_mobility)) %>%
  # creating unknown replicon type
  mutate(`rep_type(s)` = replace(`rep_type(s)`, is.na(`rep_type(s)`), "Unknown")) %>%
  # separating relaxase column into the 3 distinct types + unknowns
  separate(`relaxase_type(s)`, c("relaxase1","relaxase2"), sep = ',') %>%
  # creating unknown relaxase type
  mutate(`relaxase_type(s)` = if_else(is.na(relaxase1) | relaxase1 == "-", "Unknown", relaxase1)) %>%
  select(-c(relaxase1,
            relaxase2)) %>%
  # any instances where these two contradict?
  # CHECKED = no instances
  #filter(relaxase1 != relaxase2) %>%
#View()
  # can expand plasmid definitions as analysis progresses
  # creating repgroup for easier classification
  mutate(
    repgroup = case_when(
      #args
      #str_detect(`rep_type(s)`, "IncFIA|IncFIB|IncFII") ~ "IncF (Hybrid)",
      str_detect(`rep_type(s)`, "IncX") ~ "IncX",
      str_detect(`rep_type(s)`, "IncI") ~ "IncI",
      str_detect(`rep_type(s)`, "IncR") ~ "IncR",
      str_detect(`rep_type(s)`, "IncN") ~ "IncN",
      str_detect(`rep_type(s)`, "ColRNAI") ~ "ColRNAI",
      str_detect(`rep_type(s)`, "Unknown") ~ "Unknown",
      str_detect(`rep_type(s)`, "rep_cluster") ~ "Unclassified Cluster",
      # hvkp markers
      str_detect(`rep_type(s)`, "IncFIA") ~ "IncFIA (Hybrid)",
      str_detect(`rep_type(s)`, "IncFIB") ~ "IncFIB",
      str_detect(`rep_type(s)`, "IncFIB,IncFII|IncFIB,IncHI1B") ~ "IncFIB (Hybrid)",
      str_detect(`rep_type(s)`, "rep_cluster") ~ "Unclassified Cluster",
      TRUE ~ `rep_type(s)`
    )
  ) %>%
  mutate(plasmid_identity = paste(#plasmid_id,
                                  #size,
                                  repgroup,
                                  `relaxase_type(s)`,
                                  sep = "--")) %>%
  ggplot(aes(x = size,
            #fill = `relaxase_type(s)`
            fill = plasmid_identity
            )) +
  geom_histogram(aes(y = ..count..), 
                 position = "identity", 
                 alpha = 0.4, 
                 bins = 30) +
  theme_bw() +
  theme(# add legend box
        legend.background=element_blank(), 
        legend.box.background=element_rect(colour = "black"),
        axis.title.x = element_text(vjust = -2),
        axis.title.y = element_text(vjust = 2),
        # formatting strips
        strip.background = element_rect(color="white",fill="white"),
        strip.text = element_text(size=11)) +
  # legend spacing and outline (important)
  guides(fill=guide_legend(ncol = 2,
                           byrow = TRUE),
         size=F) +
  scale_fill_igv() +
  # megaplasmid threshold
  geom_vline(xintercept = 250000,
             linetype = "dashed",
             colour = "grey")+
  labs(title = "Plasmids Carrying Both ARGs & HvKP Markers",
       x = "Plasmid Size",
       y = "Count",
       fill = "Plasmid Type") +
  facet_wrap(~vir_plasmid)

ggsave(plot=last_plot(),
       "/Users/jonahrodgus/Desktop/new.jpeg",
       #"/Users/jonahrodgus/Desktop/thesis_new/0_figures/3_results/3_genomics/Kp_genomics_Jonah_draft1/",
       width=20,
       height=8.5)
  
```
