query_clue <- function(endpoint, query) {
  paste0("https://api.clue.io/api/",
         endpoint,
         "?filter=",
         URLencode(toJSON(query), reserved=T), 
         "&user_key=da40f81d3ed42c963f1ef6b6ef1a3c23") %>%
  URLencode() %>%
  fromJSON()
}

pert_id_to_moa <- function(pert_id) {
  pert_iname <- 
    query_clue(
      endpoint = "pert_ids",
      query = list(where = list(pert_id = unbox(pert_id)), 
                    fields = list(pert_iname = unbox(TRUE)))
    )
  
  #TODO: Check dups
  pert_iname <- pert_iname$pert_iname[1]
  
  moa <- 
    query_clue(
      endpoint = "moas",
      query = list(where = list(pert_iname = unbox(pert_iname)), 
                    fields = list(name = unbox(TRUE)))
    )
    
  #TODO: Check dups
  moa <- moa$name[1]
  
  data_frame(pert_id, pert_iname, moa)  
}

pert_id_l <- 
  c("BRD-K25114078",
    "BRD-K25204779",
    "BRD-K25361343",
    "BRD-K25140590",
    "BRD-A25234499",
    "BRD-K25394294",
    "BRD-K25650355",
    "BRD-K25943794",
    "BRD-A26032986")

lapply(pert_id_l, pert_id_to_moa) %>%
  bind_rows() %>%
  arrange(pert_id) %>%
  knitr::kable()
pert_id pert_iname moa
BRD-A25234499 aminoglutethimide glucocorticoid receptor antagonist
BRD-A26032986 zaldaride calmodulin antagonist
BRD-K25114078 aminoguanidine nitric oxide synthase inhibitor
BRD-K25140590 CX516 glutamate receptor modulator
BRD-K25204779 pritelivir helicase primase inhibitor
BRD-K25361343 batimastat matrix metalloprotease inhibitor
BRD-K25394294 oxaprozin cyclooxygenase inhibitor
BRD-K25650355 physostigmine cholinesterase inhibitor
BRD-K25943794 blonanserin dopamine receptor antagonist
readr::read_tsv("../../metadata/2016_04_01_a549_48hr_batch1/cell_painting_dataset_compound_list_anot.tsv") %>%
  mutate(Metadata_pert_id = str_extract(Metadata_broad_sample, "(BRD-[A-Z0-9]+)")) %>%
  distinct(Metadata_pert_id, Metadata_pert_iname, Metadata_MoAs) %>%
  filter(Metadata_pert_id %in% pert_id_l) %>% 
  arrange(Metadata_pert_id) %>%
  knitr::kable()
## Parsed with column specification:
## cols(
##   Metadata_Compound_Plate_Map_Name = col_character(),
##   Metadata_broad_sample = col_character(),
##   Metadata_mmoles_per_liter = col_double(),
##   Metadata_pert_iname = col_character(),
##   Metadata_MoAs = col_character()
## )
Metadata_pert_id Metadata_pert_iname Metadata_MoAs
BRD-A25234499 aminoglutethimide glucocorticoid receptor antagonist
BRD-A26032986 zaldaride calmodulin antagonist
BRD-K25114078 aminoguanidine nitric oxide synthase inhibitor
BRD-K25140590 CX516 glutamate receptor modulator
BRD-K25204779 pritelivir helicase primase inhibitor
BRD-K25361343 batimastat matrix metalloprotease inhibitor
BRD-K25394294 oxaprozin cyclooxygenase inhibitor
BRD-K25650355 physostigmine cholinesterase inhibitor
BRD-K25943794 blonanserin dopamine receptor antagonist|serotonin receptor antagonist