### R code from vignette source 'STRINGdb.Rnw'

###################################################
### code chunk number 1: initialization
###################################################
library(STRINGdb)
string_db <- STRINGdb$new( version="12.5", species=9606, 
                           score_threshold=400, network_type="full", link_data="detailed", input_directory="")


###################################################
### code chunk number 2: help
###################################################
STRINGdb$methods()              # To list all the methods available.
STRINGdb$help("get_graph")      # To visualize their documentation.


###################################################
### code chunk number 3: load_data
###################################################
data(diff_exp_example1)
head(diff_exp_example1)


###################################################
### code chunk number 4: map
###################################################
example1_mapped <- string_db$map( diff_exp_example1, "gene", removeUnmappedRows = TRUE )


###################################################
### code chunk number 5: STRINGdb.Rnw:112-114
###################################################
options(SweaveHooks=list(fig=function()
par(mar=c(2.1, 0.1, 4.1, 2.1))))


###################################################
### code chunk number 6: get_hits
###################################################
example1_mapped_pval05 <- subset(example1_mapped, pvalue < 0.05)
example1_mapped_pval05 <- example1_mapped_pval05[order(example1_mapped_pval05$pvalue), ]
hits <- example1_mapped_pval05$STRING_id[1:200]


###################################################
### code chunk number 7: plot_network
###################################################
getOption("SweaveHooks")[["fig"]]()
string_db$plot_network( hits )


###################################################
### code chunk number 8: add_diff_exp_color
###################################################
# filter by p-value and add a color column
# (i.e. green for down-regulated genes and red for up-regulated genes)
example1_colored <- string_db$add_diff_exp_color( subset(example1_mapped, pvalue<0.05),
                                                  logFcColStr="logFC" )


###################################################
### code chunk number 9: post_payload
###################################################
# post payload information to the STRING server
payload_id <- string_db$post_payload( example1_colored$STRING_id,
                                        colors=example1_colored$color )


###################################################
### code chunk number 10: plot_halo_network
###################################################
getOption("SweaveHooks")[["fig"]]()
# display a STRING network png with the "halo"
string_db$plot_network( hits, payload_id=payload_id )


###################################################
### code chunk number 11: enrichment
###################################################
enrichment <- string_db$get_enrichment( hits )
head(enrichment, n=20)


###################################################
### code chunk number 12: enrichment_figure
###################################################
getOption("SweaveHooks")[["fig"]]()
enrichment_img <- string_db$get_enrichment_figure(
  hits,
  category = "Component",
  group_by_similarity = 0.8,
  color_palette = "yellow_pink",
  x_axis = "signal"
)
grid::grid.newpage()
grid::grid.raster(enrichment_img, interpolate = FALSE)


###################################################
### code chunk number 13: background
###################################################
backgroundV <- example1_mapped$STRING_id
string_db$set_background(backgroundV)


###################################################
### code chunk number 14: new_background_inst (eval = FALSE)
###################################################
## string_db <- STRINGdb$new( score_threshold=400, backgroundV = backgroundV )


###################################################
### code chunk number 15: enrichment_with_background
###################################################
enrichment_background_corrected <- string_db$get_enrichment( hits )
head(enrichment_background_corrected, n=20)


###################################################
### code chunk number 16: annotations
###################################################
annotations <- string_db$get_annotations( hits )
head(annotations, n=20)


###################################################
### code chunk number 17: values_ranks
###################################################
if (interactive()) {
  ranked_enrichment <- string_db$get_values_ranks_enrichment(
    example1_mapped$STRING_id, example1_mapped$logFC, max_fdr = 0.01 )
  # or, the same with a named vector:
  #   ranked <- setNames( example1_mapped$logFC, example1_mapped$STRING_id )
  #   ranked_enrichment <- string_db$get_values_ranks_enrichment(
  #     ranked, max_fdr = 0.01 )
  job_id <- attr(ranked_enrichment, "job_id")
  attr(ranked_enrichment, "page_url")
}


###################################################
### code chunk number 18: values_ranks_sample
###################################################
ranked_enrichment <- readRDS(system.file("extdata", "values_ranks_example.rds",
                                         package = "STRINGdb"))
ranked_enrichment[, c("category", "description", "direction",
                      "enrichment_score", "fdr", "number_of_genes")]
head(ranked_enrichment$inputValues[[1]])


###################################################
### code chunk number 19: values_ranks_results
###################################################
if (interactive()) {
  ranked_enrichment <- string_db$get_values_ranks_results( job_id )
}


###################################################
### code chunk number 20: values_ranks_several
###################################################
signed_p <- sign(example1_mapped$logFC) * -log10(example1_mapped$pvalue)
rankings <- data.frame(logFC = example1_mapped$logFC, signed_p = signed_p)
if (interactive()) {
  ranked_enrichments <- string_db$get_values_ranks_enrichment(
    example1_mapped$STRING_id, rankings )
  attr(ranked_enrichments, "status")
}


###################################################
### code chunk number 21: values_ranks_asynchronous
###################################################
if (interactive()) {
  job_ids <- string_db$submit_values_ranks_enrichment(
    example1_mapped$STRING_id, rankings )
  print( string_db$get_values_ranks_status( job_ids ) )
  ranked_enrichments <- string_db$get_values_ranks_results( job_ids )
}


###################################################
### code chunk number 22: clustering1
###################################################
# get clusters of the 600 most significant genes
clustersList <- string_db$get_clusters(example1_mapped_pval05$STRING_id[1:600])


###################################################
### code chunk number 23: clustering2
###################################################
getOption("SweaveHooks")[["fig"]]()
par(mfrow = c(2, 2))
par(mar = c(0, 0, 0.5, 0))
string_db$plot_network(clustersList[[1]], add_summary = FALSE)

par(mar = c(0, 0, 0.5, 0))
string_db$plot_network(clustersList[[2]], add_summary = FALSE)

par(mar = c(0, 0, 0.5, 0))
string_db$plot_network(clustersList[[3]], add_summary = FALSE)

par(mar = c(0, 0, 0.5, 0))
string_db$plot_network(clustersList[[4]], add_summary = FALSE)


###################################################
### code chunk number 24: proteins
###################################################
string_proteins <- string_db$get_proteins()
head(string_proteins)


###################################################
### code chunk number 25: atmtp
###################################################
tp53 = string_db$mp( "tp53" )
atm = string_db$mp( "atm" )
mdm2 = string_db$mp( "mdm2" )


###################################################
### code chunk number 26: network_types
###################################################
functional_db <- string_db
physical_db <- STRINGdb$new(
  version = "12.5", species = 9606, score_threshold = 400,
  network_type = "physical", link_data = "detailed",
  input_directory = functional_db$input_directory
)
regulatory_db <- STRINGdb$new(
  version = "12.5", species = 9606, score_threshold = 400,
  network_type = "regulatory", link_data = "detailed",
  input_directory = functional_db$input_directory
)


###################################################
### code chunk number 27: typed_network
###################################################
getOption("SweaveHooks")[["fig"]]()
functional_db$plot_network(
  c(tp53, mdm2),
  network_flavor = "typed",
  typed_physical_edges = TRUE,
  typed_regulatory_edges = TRUE,
  show_regulatory_signs = TRUE
)


###################################################
### code chunk number 28: regulatory_edges
###################################################
regulatory_edges <- regulatory_db$get_interactions(c(tp53, mdm2))
regulatory_edges$regulatory_edge <- paste(
  regulatory_edges$from_name, "->", regulatory_edges$to_name
)
regulatory_edges[, c("regulatory_edge", "combined_score")]


###################################################
### code chunk number 29: interactions
###################################################
string_db$get_interactions( c(tp53, atm) )


###################################################
### code chunk number 30: interaction_partners
###################################################
string_db$get_interaction_partners( c(tp53, atm), limit=5 )[, c("from", "to", "combined_score", "experimental", "from_name", "to_name")]


###################################################
### code chunk number 31: interaction_partners_experimental
###################################################
interaction_partners <- string_db$get_interaction_partners( c(tp53, atm), limit=5 )
interaction_partners_exp <- subset(interaction_partners, experimental > 0,
                                   select = c("from_name", "to_name", "experimental"))
interaction_partners_exp


###################################################
### code chunk number 32: paralogs
###################################################
# similarity among TP53, TP63 and TP73 in human
p53_family <- string_db$mp(c("TP53", "TP63", "TP73"))
string_db$get_paralogs(p53_family)


###################################################
### code chunk number 33: Closest homologs from other species
###################################################
# get the best hits of TP53 in all STRING species
tp53_besthits <- string_db$get_homologs_besthits(tp53)
tp53_besthits_100 <- subset(tp53_besthits, bitscore > 100)
nrow(tp53_besthits_100)
head(tp53_besthits_100, n=10)


###################################################
### code chunk number 34: homologs_besthits in target species
###################################################
# get the homologs of the following two proteins in the mouse (i.e. species_id=10090)
string_db$get_homologs_besthits(c(tp53, atm), target_species_id=10090)
