content
large_stringlengths
0
6.46M
path
large_stringlengths
3
331
license_type
large_stringclasses
2 values
repo_name
large_stringlengths
5
125
language
large_stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.46M
extension
large_stringclasses
75 values
text
stringlengths
0
6.46M
startTime <- Sys.time() cat(paste0("> Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile_otherFamFile.R\n")) options(scipen=100) buildTable <- TRUE printAndLog <- function(text, logFile = ""){ cat(text) cat(text, append =T , file = logFile) } suppressPackageStartupMessages(library(foreach, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(doMC, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(ggpubr, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(ggstatsplot, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(ggplot2, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(dplyr, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(flux, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) axisLabSize <- 12 legendSize <- 10 plotTitSize <- 14 mytheme <- theme( # top, right, bottom and left plot.margin = unit(c(1.5, 1.5, 1.5, 1.5), "lines"), plot.title = element_text(hjust = 0.5, face = "bold", size=plotTitSize, vjust=1), plot.subtitle = element_text(hjust = 0.5, face = "bold", size=plotTitSize-2, vjust=1), panel.background = element_rect(fill = "white", colour = NA), panel.border = element_rect(fill = NA, colour = "grey20"), panel.grid.major = element_line(colour = "grey92"), panel.grid.minor = element_line(colour = "grey92", size = 0.25), strip.background = element_rect(fill = "grey85", colour = "grey20"), #legend.key = element_rect(fill = "white", colour = NA), axis.line.x = element_line(size = .3, color = "black"), axis.line.y = element_line(size = .3, color = "black"), axis.text.y = element_text(color="black", hjust=1,vjust = 0.5, size=axisLabSize), axis.text.x = element_text(color="black", hjust=0.5,vjust = 1, size=axisLabSize), axis.title.y = element_text(color="black", size=axisLabSize+1), axis.title.x = element_text(color="black", size=axisLabSize+1), legend.text = element_text(size=legendSize), legend.key.height = unit(1.5,"cm"), legend.key = element_blank() ) SSHFS <- F setDir <- ifelse(SSHFS, "/media/electron", "") registerDoMC(ifelse(SSHFS, 2, 40)) ### HARD CODED corMethod <- "pearson" # for plotting: # look at coexpression ~ distance up to distLimit bp distLimit <- 500 * 10^3 fitMeth <- "loess" # nbr of points for loess fit to take the AUC nbrLoessPoints <- 1000 scatterFontSizeLabel <- 14 scatterFontSizeTitle <- 12 # UPDATE 30.06.2018: # -> check that always $gene1 < $gene2 before left_join !!! ### RETRIEVE FROM COMMAND LINE # Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile.R <TADlist> <dataset> # Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile.R <TADlist> <dataset> <family> # Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile_otherFamFile.R ENCSR079VIJ_G401_40kb TCGAkich_norm_kich #### !!! change for otherTADfile: <<< GENE DATA DO NOT CHANGE # retrieve the sameTAD data frame from: # file.path("CREATE_SAME_TAD_SORTNODUP", curr_TADlist, "all_TAD_pairs.Rdata") args <- commandArgs(trailingOnly = TRUE) stopifnot(length(args) == 2 | length(args) == 3) if(length(args) == 3) { txt <- paste0("> Parameters retrieved from command line:\n") stopifnot(length(args) == 2) curr_TADlist <- args[1] curr_dataset <- args[2] familyData <- args[3] } else if(length(args) == 2){ curr_TADlist <- args[1] curr_dataset <- args[2] txt <- paste0("> Default parameters:\n") familyData <- "hgnc" } outFold <- file.path("AUC_COEXPRDIST_WITHFAM_SORTNODUP", curr_TADlist, paste0(curr_dataset, "_", familyData)) dir.create(outFold, recursive = TRUE) logFile <- file.path(outFold, paste0("coexpr_dist_withFam_otherTADfile_logFile.txt")) file.remove(logFile) printAndLog(txt, logFile) txt <- paste0("... curr_TADlist = ", curr_TADlist, "\n") printAndLog(txt, logFile) txt <- paste0("... curr_dataset = ", curr_dataset, "\n") printAndLog(txt, logFile) txt <- paste0("... familyData = ", familyData, "\n") printAndLog(txt, logFile) txt <- paste0("> ! Hard-coded parameters:\n") printAndLog(txt, logFile) txt <- paste0("... corMethod = ", corMethod, "\n") printAndLog(txt, logFile) txt <- paste0("... buildTable = ", as.character(buildTable), "\n") printAndLog(txt, logFile) txt <- paste0("... distLimit = ", distLimit, "\n") printAndLog(txt, logFile) txt <- paste0("... fitMeth = ", fitMeth, "\n") printAndLog(txt, logFile) mycols <- c("same TAD" ="darkorange1" , "diff. TAD"="darkslateblue", "same Fam. + same TAD"="violetred1", "same Fam. + diff. TAD" = "lightskyblue") sameTADcol <- mycols["same TAD"] diffTADcol <- mycols["diff. TAD"] sameFamSameTADcol <- mycols["same Fam. + same TAD"] sameFamDiffTADcol <- mycols["same Fam. + diff. TAD"] plotType <- "png" # myHeight <- ifelse(plotType == "png", 400, 7) # myWidth <- ifelse(plotType == "png", 600, 10) myHeight <- ifelse(plotType == "png", 400, 5) myWidth <- ifelse(plotType == "png", 600, 6) pipScriptDir <- paste0(setDir, "/mnt/ed4/marie/scripts/TAD_DE_pipeline_v2") source(paste0(pipScriptDir, "/", "TAD_DE_utils.R")) utilsDir <- paste0(setDir, "/mnt/ed4/marie/scripts/TAD_DE_pipeline_v2_coreg") source(file.path(utilsDir, "coreg_utils_ggscatterhist.R")) ### UPDATE 08.01.19 => USE TAD LIST SPECIFIC FILES = TISSUE SPECIFIC FILES distFile <- file.path("CREATE_DIST_SORTNODUP", curr_TADlist, "all_dist_pairs.Rdata") stopifnot(file.exists(distFile)) # CHANGED 08.01.19 !!! coexprFile <- file.path("CREATE_COEXPR_SORTNODUP", curr_TADlist, paste0(curr_dataset), corMethod, "coexprDT.Rdata") stopifnot(file.exists(coexprFile)) sameTADfile <- file.path("CREATE_SAME_TAD_SORTNODUP", curr_TADlist, "all_TAD_pairs.Rdata") stopifnot(file.exists(sameTADfile)) # ADDED 08.01.19 to accommodate updated family file sameFamFolder <- file.path("CREATE_SAME_FAMILY_SORTNODUP", curr_TADlist) # checking the file comes after (iterating over family and family_short) stopifnot(dir.exists(sameFamFolder)) sameFamFile <- file.path(sameFamFolder, paste0(familyData, "_family_all_family_pairs.Rdata")) # at least this one should exist ! stopifnot(file.exists(sameFamFile)) dataset_pipDir <- file.path("PIPELINE", "OUTPUT_FOLDER", curr_TADlist, curr_dataset) # used to retrieve gene list stopifnot(dir.exists(dataset_pipDir)) txt <- paste0("... distFile = ", distFile, "\n") printAndLog(txt, logFile) txt <- paste0("... coexprFile = ", coexprFile, "\n") printAndLog(txt, logFile) txt <- paste0("... sameTADfile = ", sameTADfile, "\n") printAndLog(txt, logFile) txt <- paste0("... sameFamFile = ", sameFamFile, "\n") printAndLog(txt, logFile) ################################################ DATA PREPARATION if(buildTable) { cat(paste0("... load DIST data\t", distFile, "\t", Sys.time(), "\t")) load(distFile) cat(paste0(Sys.time(), "\n")) head(all_dist_pairs) nrow(all_dist_pairs) all_dist_pairs$gene1 <- as.character(all_dist_pairs$gene1) all_dist_pairs$gene2 <- as.character(all_dist_pairs$gene2) # UPDATE 30.06.2018 stopifnot(all_dist_pairs$gene1 < all_dist_pairs$gene2) cat(paste0("... load TAD data\t", sameTADfile, "\t", Sys.time(), "\t")) ### =>>> CHANGED HERE FOR OTHER TAD FILE !!! load(sameTADfile) cat(paste0(Sys.time(), "\n")) head(all_TAD_pairs) nrow(all_TAD_pairs) all_TAD_pairs$gene1 <- as.character(all_TAD_pairs$gene1) all_TAD_pairs$gene2 <- as.character(all_TAD_pairs$gene2) # UPDATE 30.06.2018 stopifnot(all_TAD_pairs$gene1 < all_TAD_pairs$gene2) cat(paste0("... load COEXPR data\t",coexprFile, "\t", Sys.time(), "\t")) load(coexprFile) cat(paste0(Sys.time(), "\n")) head(coexprDT) nrow(coexprDT) coexprDT$gene1 <- as.character(coexprDT$gene1) coexprDT$gene2 <- as.character(coexprDT$gene2) all_TAD_pairs$gene2 # UPDATE 30.06.2018 stopifnot(coexprDT$gene1 < coexprDT$gene2) #============================== RETRIEVE PIPELINE DATA FOR THIS DATASET - USED ONLY FOR GENE LIST script0_name <- "0_prepGeneData" geneFile <- file.path(dataset_pipDir, script0_name, "pipeline_geneList.Rdata") cat(paste0("... load GENELIST file\t",geneFile, "\t", Sys.time(), "\t")) pipeline_geneList <- eval(parse(text = load(geneFile))) pipeline_geneList <- as.character(pipeline_geneList) dataset_dist_pair <- all_dist_pairs[all_dist_pairs$gene1 %in% pipeline_geneList & all_dist_pairs$gene2 %in% pipeline_geneList,] dataset_dist_pairs_limit <- dataset_dist_pair[dataset_dist_pair$dist <= distLimit,] head(dataset_dist_pairs_limit) nrow(dataset_dist_pairs_limit) dataset_TAD_pairs <- all_TAD_pairs[all_TAD_pairs$gene1 %in% pipeline_geneList & all_TAD_pairs$gene2 %in% pipeline_geneList,] head(dataset_TAD_pairs) nrow(dataset_TAD_pairs) # START MERGING DATA cat(paste0("... merge DIST - TAD data\t", Sys.time(), "\t")) dataset_dist_TAD_DT <- left_join(dataset_dist_pairs_limit, dataset_TAD_pairs, by=c("gene1", "gene2")) cat(paste0(Sys.time(), "\n")) dataset_dist_TAD_DT$sameTAD <- ifelse(is.na(dataset_dist_TAD_DT$region), 0, 1) } # all_familyData <- paste0(familyData, c("_family", "_family_short")) all_familyData <- paste0(familyData, c( "_family_short")) outFold_save <- outFold for(i_fam in all_familyData) { outFold <- file.path(outFold_save, i_fam) dir.create(outFold, recursive = TRUE) if(buildTable){ # UPDATE HERE 08.01.19 TO HAVE DATA FROM TISSUE SPECIFIC TAD LIST sameFamFile <- file.path(sameFamFolder, paste0(i_fam, "_all_family_pairs.Rdata")) cat(paste0("... load FAMILY data\t", sameFamFile, "\n", Sys.time(), "\t")) stopifnot(file.exists(sameFamFile)) load(sameFamFile) cat(paste0(Sys.time(), "\n")) head(all_family_pairs) nrow(all_family_pairs) all_family_pairs$gene1 <- as.character(all_family_pairs$gene1) all_family_pairs$gene2 <- as.character(all_family_pairs$gene2) stopifnot(all_family_pairs$gene1 < all_family_pairs$gene2) dataset_family_pairs <- all_family_pairs[all_family_pairs$gene1 %in% pipeline_geneList & all_family_pairs$gene2 %in% pipeline_geneList,] head(dataset_family_pairs) cat(paste0("... merge FAMILY data\t", Sys.time(), "\t")) dataset_dist_TAD_fam_DT <- left_join(dataset_dist_TAD_DT, dataset_family_pairs, by=c("gene1", "gene2")) cat(paste0(Sys.time(), "\n")) dataset_dist_TAD_fam_DT$sameFamily <- ifelse(is.na(dataset_dist_TAD_fam_DT$family), 0, 1) cat(paste0("... merge COEXPR data\t", Sys.time(), "\t")) dataset_dist_TAD_fam_coexpr_DT <- left_join(dataset_dist_TAD_fam_DT, coexprDT, by=c("gene1", "gene2")) cat(paste0(Sys.time(), "\n")) allData_dt <- dataset_dist_TAD_fam_coexpr_DT allData_dt$region <- NULL allData_dt$family <- NULL allData_dt <- na.omit(allData_dt) # outFile <-file.path(outFold, paste0(i_fam, "_", "allData_dt.Rdata")) outFile <-file.path(outFold, paste0( "allData_dt.Rdata")) save(allData_dt, file = outFile) cat(paste0("... written: ", outFile, "\n")) } else{ # outFile <-file.path(outFold, paste0(i_fam, "_", "allData_dt.Rdata")) outFile <-file.path(outFold, paste0( "allData_dt.Rdata")) load(outFile) # load("/media/electron/mnt/ed4/marie/scripts/TAD_DE_pipeline_v2_TopDom/COEXPR_DIST_v3/TCGAcrc_msi_mss_hgnc/hgnc_family_allData_dt.Rdata") } nrow(allData_dt) allData_dt$dist_kb <- allData_dt$dist/1000 allData_dt$curve1 <- ifelse(allData_dt$sameTAD == "0", "diff. TAD", "same TAD") allData_dt$curve2 <- ifelse(allData_dt$sameFamily == "0", NA, ifelse(allData_dt$sameTAD == "0", "same Fam. + diff. TAD", "same Fam. + same TAD")) sameTAD_DT <- allData_dt[allData_dt$sameTAD == 1,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] sameTAD_DT <- na.omit(sameTAD_DT) sameTAD_DT <- sameTAD_DT[order(sameTAD_DT$dist_kb),] sameTAD_DT$nPair <- 1:nrow(sameTAD_DT) sameTAD_DT$label <- "same TAD" diffTAD_DT <- allData_dt[allData_dt$sameTAD == 0,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] diffTAD_DT <- na.omit(diffTAD_DT) diffTAD_DT <- diffTAD_DT[order(diffTAD_DT$dist_kb),] diffTAD_DT$nPair <- 1:nrow(diffTAD_DT) diffTAD_DT$label <- "diff. TAD" sameFam_sameTAD_DT <- allData_dt[allData_dt$sameFamily == 1 & allData_dt$sameTAD == 1 ,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] sameFam_sameTAD_DT <- na.omit(sameFam_sameTAD_DT) sameFam_sameTAD_DT <- sameFam_sameTAD_DT[order(sameFam_sameTAD_DT$dist_kb),] sameFam_sameTAD_DT$nPair <- 1:nrow(sameFam_sameTAD_DT) sameFam_sameTAD_DT$label <- "same Fam. + same TAD" sameFam_diffTAD_DT <- allData_dt[allData_dt$sameFamily == 1 & allData_dt$sameTAD == 0 ,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] sameFam_diffTAD_DT <- na.omit(sameFam_diffTAD_DT) sameFam_diffTAD_DT <- sameFam_diffTAD_DT[order(sameFam_diffTAD_DT$dist_kb),] sameFam_diffTAD_DT$nPair <- 1:nrow(sameFam_diffTAD_DT) sameFam_diffTAD_DT$label <- "same Fam. + diff. TAD" stopifnot(is.numeric(sameTAD_DT$dist[1])) stopifnot(is.numeric(sameTAD_DT$coexpr[1])) stopifnot(is.numeric(diffTAD_DT$dist[1])) stopifnot(is.numeric(diffTAD_DT$coexpr[1])) stopifnot(is.numeric(sameFam_sameTAD_DT$dist[1])) stopifnot(is.numeric(sameFam_sameTAD_DT$coexpr[1])) stopifnot(is.numeric(sameFam_diffTAD_DT$dist[1])) stopifnot(is.numeric(sameFam_diffTAD_DT$coexpr[1])) #*** if(fitMeth == "loess") { my_ylab <- paste0("Gene pair coexpression (", corMethod, ", qqnormDT)") my_xlab <- paste0("Distance between the 2 genes (kb)") my_sub <- paste0(curr_dataset) # PREDICT WITH ORIGINAL DISTANCE VALUES my_xlab <- paste0("Distance between the 2 genes (bp)") diffTAD_mod <- loess(coexpr ~ dist, data = diffTAD_DT) sameTAD_mod <- loess(coexpr ~ dist, data = sameTAD_DT) smooth_vals_sameTAD <- predict(sameTAD_mod, sort(sameTAD_DT$dist)) smooth_vals_diffTAD <- predict(diffTAD_mod, sort(diffTAD_DT$dist)) auc_diffTAD_obsDist <- auc(x = sort(diffTAD_DT$dist), y = smooth_vals_diffTAD) auc_sameTAD_obsDist <- auc(x = sort(sameTAD_DT$dist), y = smooth_vals_sameTAD) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameTAD_diffTAD_loessFit_originalDist", ".", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(allData_dt$dist), ylim = range(c(smooth_vals_sameTAD, smooth_vals_diffTAD)), xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = "observed distance values", side = 3) lines( x = sort(sameTAD_DT$dist), y = smooth_vals_sameTAD, col = sameTADcol) lines( x = sort(diffTAD_DT$dist), y = smooth_vals_diffTAD, col = diffTADcol) legend("topright", legend=c(paste0("sameTAD\n(AUC=", round(auc_sameTAD_obsDist, 2), ")"), paste0("diffTAD\n(AUC=", round(auc_diffTAD_obsDist, 2))), col = c(sameTADcol, diffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) # PREDICT WITH DISTANCE VECTOR distVect <- seq(from=0, to = distLimit, length.out = nbrLoessPoints) smooth_vals_sameTAD_distVect <- predict(sameTAD_mod, distVect) smooth_vals_diffTAD_distVect <- predict(diffTAD_mod, distVect) auc_diffTAD_distVect <- auc(x = distVect, y = smooth_vals_diffTAD_distVect) auc_sameTAD_distVect <- auc(x = distVect, y = smooth_vals_sameTAD_distVect) outFile <- file.path(outFold, "auc_diffTAD_distVect.Rdata") save(auc_diffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "auc_sameTAD_distVect.Rdata") save(auc_sameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_sameTAD_distVect.Rdata") save(smooth_vals_sameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_diffTAD_distVect.Rdata") save(smooth_vals_diffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "distVect.Rdata") save(distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameTAD_diffTAD_loessFit_vectDist.", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(distVect), ylim = range(c(na.omit(smooth_vals_sameTAD_distVect), na.omit(smooth_vals_diffTAD_distVect))), xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = paste0("distance values seq from 0 to ", distLimit, " (# points = ", nbrLoessPoints, ")"), side = 3) lines( x = distVect, y = smooth_vals_sameTAD_distVect, col = sameTADcol) lines( x = distVect, y = smooth_vals_diffTAD_distVect, col = diffTADcol) legend("topright", legend=c(paste0("sameTAD\n(AUC=", round(auc_sameTAD_distVect, 2), ")"), paste0("diffTAD\n(AUC=", round(auc_diffTAD_distVect, 2))), col = c(sameTADcol, diffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) ################################ DO THE SAME FOR SAME FAM SAME TAD VS. SAME FAM DIFF TAD sameFamDiffTAD_mod <- loess(coexpr ~ dist, data = sameFam_diffTAD_DT) sameFamSameTAD_mod <- loess(coexpr ~ dist, data = sameFam_sameTAD_DT) smooth_vals_sameFamSameTAD <- predict(sameFamSameTAD_mod, sort(sameFam_sameTAD_DT$dist)) smooth_vals_sameFamDiffTAD <- predict(sameFamDiffTAD_mod, sort(sameFam_diffTAD_DT$dist)) auc_sameFamDiffTAD_obsDist <- auc(x = sort(sameFam_diffTAD_DT$dist), y = smooth_vals_sameFamDiffTAD) auc_sameFamSameTAD_obsDist <- auc(x = sort(sameFam_sameTAD_DT$dist), y = smooth_vals_sameFamSameTAD) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameFamSameTAD_sameFamDiffTAD_loessFit_originalDist", ".", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(allData_dt$dist), ylim = range(c(smooth_vals_sameFamSameTAD, smooth_vals_sameFamDiffTAD)), xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = "observed distance values", side = 3) lines( x = sort(sameFam_sameTAD_DT$dist), y = smooth_vals_sameFamSameTAD, col = sameFamSameTADcol) lines( x = sort(sameFam_diffTAD_DT$dist), y = smooth_vals_sameFamDiffTAD, col = sameFamDiffTADcol) legend("topright", legend=c(paste0("sameFamSameTAD\n(AUC=", round(auc_sameFamSameTAD_obsDist, 2), ")"), paste0("sameFamDiffTAD\n(AUC=", round(auc_sameFamDiffTAD_obsDist, 2))), col = c(sameFamSameTADcol, sameFamDiffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) # PREDICT WITH DISTANCE VECTOR smooth_vals_sameFamSameTAD_distVect <- predict(sameFamSameTAD_mod, distVect) smooth_vals_sameFamDiffTAD_distVect <- predict(sameFamDiffTAD_mod, distVect) auc_sameFamDiffTAD_distVect <- auc(x = distVect, y = smooth_vals_sameFamDiffTAD_distVect) auc_sameFamSameTAD_distVect <- auc(x = distVect, y = smooth_vals_sameFamSameTAD_distVect) outFile <- file.path(outFold, "diffTAD_mod.Rdata") save(diffTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "sameFamDiffTAD_mod.Rdata") save(sameFamDiffTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "sameTAD_mod.Rdata") save(sameTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "sameFamSameTAD_mod.Rdata") save(sameFamSameTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) sameFamDiffTAD_obsDist <- sameFam_diffTAD_DT$dist outFile <- file.path(outFold, "sameFamDiffTAD_obsDist.Rdata") save(sameFamDiffTAD_obsDist, file = outFile) cat(paste0("... written: ", outFile, "\n")) sameFamSameTAD_obsDist <- sameFam_sameTAD_DT$dist outFile <- file.path(outFold, "sameFamSameTAD_obsDist.Rdata") save(sameFamSameTAD_obsDist, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "auc_sameFamDiffTAD_distVect.Rdata") save(auc_sameFamDiffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "auc_sameFamSameTAD_distVect.Rdata") save(auc_sameFamSameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_sameFamSameTAD_distVect.Rdata") save(smooth_vals_sameFamSameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_sameFamDiffTAD_distVect.Rdata") save(smooth_vals_sameFamDiffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameFamSameTAD_sameFamDiffTAD_loessFit_vectDist.", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(distVect), ylim = range(c(na.omit(smooth_vals_sameFamSameTAD_distVect), na.omit(smooth_vals_sameFamDiffTAD_distVect))), # xlab="", # ylab="", xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = paste0("distance values seq from 0 to ", distLimit, " (# points = ", nbrLoessPoints, ")"), side = 3) lines( x = distVect, y = smooth_vals_sameFamSameTAD_distVect, col = sameFamSameTADcol) lines( x = distVect, y = smooth_vals_sameFamDiffTAD_distVect, col = sameFamDiffTADcol) legend("topright", legend=c(paste0("sameFamSameTAD\n(AUC=", round(auc_sameFamSameTAD_distVect, 2), ")"), paste0("sameFamDiffTAD\n(AUC=", round(auc_sameFamDiffTAD_distVect, 2))), col = c(sameFamSameTADcol, sameFamDiffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) ################################################################ outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameTAD_diffTAD_sameFamSameTAD_sameFamDiffTAD_loessFit_vectDist.", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(distVect), ylim = range(c(na.omit(smooth_vals_sameTAD_distVect), na.omit(smooth_vals_sameFamSameTAD_distVect), na.omit(smooth_vals_diffTAD_distVect), na.omit(smooth_vals_sameFamDiffTAD_distVect))), # xlab="", # ylab="", xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = paste0("distance values seq from 0 to ", distLimit, " (# points = ", nbrLoessPoints, ")"), side = 3) lines( x = distVect, y = smooth_vals_sameFamSameTAD_distVect, col = sameFamSameTADcol) lines( x = distVect, y = smooth_vals_sameFamDiffTAD_distVect, col = sameFamDiffTADcol) lines( x = distVect, y = smooth_vals_sameTAD_distVect, col = sameTADcol) lines( x = distVect, y = smooth_vals_diffTAD_distVect, col = diffTADcol) legend("topright", legend=c(paste0("sameTAD\n(AUC=", round(auc_sameTAD_distVect, 2), ")"), paste0("diffTAD\n(AUC=", round(auc_diffTAD_distVect, 2)), paste0("sameFamSameTAD\n(AUC=", round(auc_sameFamSameTAD_distVect, 2), ")"), paste0("sameFamDiffTAD\n(AUC=", round(auc_sameFamDiffTAD_distVect, 2))), col = c(sameTADcol, diffTADcol, sameFamSameTADcol, sameFamDiffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) ################################################################ auc_values <- list( auc_diffTAD_distVect = auc_diffTAD_distVect, auc_sameTAD_distVect = auc_sameTAD_distVect, auc_ratio_same_over_diff_distVect = auc_sameTAD_distVect/auc_diffTAD_distVect, auc_diffTAD_obsDist = auc_diffTAD_obsDist, auc_sameTAD_obsDist = auc_sameTAD_obsDist, auc_ratio_same_over_diff_obsDist = auc_sameTAD_distVect/auc_diffTAD_obsDist, auc_sameFamDiffTAD_distVect = auc_sameFamDiffTAD_distVect, auc_sameFamSameTAD_distVect = auc_sameFamSameTAD_distVect, auc_ratio_sameFam_same_over_diff_distVect = auc_sameFamSameTAD_distVect/auc_sameFamDiffTAD_distVect, auc_sameFamDiffTAD_obsDist = auc_sameFamDiffTAD_obsDist, auc_sameFamSameTAD_obsDist = auc_sameFamSameTAD_obsDist, auc_ratio_sameFam_same_over_diff_obsDist = auc_sameFamSameTAD_distVect/auc_sameFamDiffTAD_obsDist ) outFile <- file.path(outFold, paste0("auc_values.Rdata")) save(auc_values, file = outFile) cat(paste0("... written: ", outFile, "\n")) } else{ stop("only loess implemented yet\n") } } # end iterating over family data ###################################################################################### ###################################################################################### ###################################################################################### cat(paste0("... written: ", logFile, "\n")) ###################################################################################### cat("*** DONE\n") cat(paste0(startTime, "\n", Sys.time(), "\n"))
/AUC_coexprDist_withFam_sortNoDup_otherTADfile_otherFamFile.R
no_license
marzuf/CORRECT_Yuanlong_Cancer_HiC_data_TAD_DA
R
false
false
26,452
r
startTime <- Sys.time() cat(paste0("> Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile_otherFamFile.R\n")) options(scipen=100) buildTable <- TRUE printAndLog <- function(text, logFile = ""){ cat(text) cat(text, append =T , file = logFile) } suppressPackageStartupMessages(library(foreach, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(doMC, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(ggpubr, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(ggstatsplot, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(ggplot2, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(dplyr, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) suppressPackageStartupMessages(library(flux, warn.conflicts = FALSE, quietly = TRUE, verbose = FALSE)) axisLabSize <- 12 legendSize <- 10 plotTitSize <- 14 mytheme <- theme( # top, right, bottom and left plot.margin = unit(c(1.5, 1.5, 1.5, 1.5), "lines"), plot.title = element_text(hjust = 0.5, face = "bold", size=plotTitSize, vjust=1), plot.subtitle = element_text(hjust = 0.5, face = "bold", size=plotTitSize-2, vjust=1), panel.background = element_rect(fill = "white", colour = NA), panel.border = element_rect(fill = NA, colour = "grey20"), panel.grid.major = element_line(colour = "grey92"), panel.grid.minor = element_line(colour = "grey92", size = 0.25), strip.background = element_rect(fill = "grey85", colour = "grey20"), #legend.key = element_rect(fill = "white", colour = NA), axis.line.x = element_line(size = .3, color = "black"), axis.line.y = element_line(size = .3, color = "black"), axis.text.y = element_text(color="black", hjust=1,vjust = 0.5, size=axisLabSize), axis.text.x = element_text(color="black", hjust=0.5,vjust = 1, size=axisLabSize), axis.title.y = element_text(color="black", size=axisLabSize+1), axis.title.x = element_text(color="black", size=axisLabSize+1), legend.text = element_text(size=legendSize), legend.key.height = unit(1.5,"cm"), legend.key = element_blank() ) SSHFS <- F setDir <- ifelse(SSHFS, "/media/electron", "") registerDoMC(ifelse(SSHFS, 2, 40)) ### HARD CODED corMethod <- "pearson" # for plotting: # look at coexpression ~ distance up to distLimit bp distLimit <- 500 * 10^3 fitMeth <- "loess" # nbr of points for loess fit to take the AUC nbrLoessPoints <- 1000 scatterFontSizeLabel <- 14 scatterFontSizeTitle <- 12 # UPDATE 30.06.2018: # -> check that always $gene1 < $gene2 before left_join !!! ### RETRIEVE FROM COMMAND LINE # Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile.R <TADlist> <dataset> # Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile.R <TADlist> <dataset> <family> # Rscript AUC_coexprDist_withFam_sortNoDup_otherTADfile_otherFamFile.R ENCSR079VIJ_G401_40kb TCGAkich_norm_kich #### !!! change for otherTADfile: <<< GENE DATA DO NOT CHANGE # retrieve the sameTAD data frame from: # file.path("CREATE_SAME_TAD_SORTNODUP", curr_TADlist, "all_TAD_pairs.Rdata") args <- commandArgs(trailingOnly = TRUE) stopifnot(length(args) == 2 | length(args) == 3) if(length(args) == 3) { txt <- paste0("> Parameters retrieved from command line:\n") stopifnot(length(args) == 2) curr_TADlist <- args[1] curr_dataset <- args[2] familyData <- args[3] } else if(length(args) == 2){ curr_TADlist <- args[1] curr_dataset <- args[2] txt <- paste0("> Default parameters:\n") familyData <- "hgnc" } outFold <- file.path("AUC_COEXPRDIST_WITHFAM_SORTNODUP", curr_TADlist, paste0(curr_dataset, "_", familyData)) dir.create(outFold, recursive = TRUE) logFile <- file.path(outFold, paste0("coexpr_dist_withFam_otherTADfile_logFile.txt")) file.remove(logFile) printAndLog(txt, logFile) txt <- paste0("... curr_TADlist = ", curr_TADlist, "\n") printAndLog(txt, logFile) txt <- paste0("... curr_dataset = ", curr_dataset, "\n") printAndLog(txt, logFile) txt <- paste0("... familyData = ", familyData, "\n") printAndLog(txt, logFile) txt <- paste0("> ! Hard-coded parameters:\n") printAndLog(txt, logFile) txt <- paste0("... corMethod = ", corMethod, "\n") printAndLog(txt, logFile) txt <- paste0("... buildTable = ", as.character(buildTable), "\n") printAndLog(txt, logFile) txt <- paste0("... distLimit = ", distLimit, "\n") printAndLog(txt, logFile) txt <- paste0("... fitMeth = ", fitMeth, "\n") printAndLog(txt, logFile) mycols <- c("same TAD" ="darkorange1" , "diff. TAD"="darkslateblue", "same Fam. + same TAD"="violetred1", "same Fam. + diff. TAD" = "lightskyblue") sameTADcol <- mycols["same TAD"] diffTADcol <- mycols["diff. TAD"] sameFamSameTADcol <- mycols["same Fam. + same TAD"] sameFamDiffTADcol <- mycols["same Fam. + diff. TAD"] plotType <- "png" # myHeight <- ifelse(plotType == "png", 400, 7) # myWidth <- ifelse(plotType == "png", 600, 10) myHeight <- ifelse(plotType == "png", 400, 5) myWidth <- ifelse(plotType == "png", 600, 6) pipScriptDir <- paste0(setDir, "/mnt/ed4/marie/scripts/TAD_DE_pipeline_v2") source(paste0(pipScriptDir, "/", "TAD_DE_utils.R")) utilsDir <- paste0(setDir, "/mnt/ed4/marie/scripts/TAD_DE_pipeline_v2_coreg") source(file.path(utilsDir, "coreg_utils_ggscatterhist.R")) ### UPDATE 08.01.19 => USE TAD LIST SPECIFIC FILES = TISSUE SPECIFIC FILES distFile <- file.path("CREATE_DIST_SORTNODUP", curr_TADlist, "all_dist_pairs.Rdata") stopifnot(file.exists(distFile)) # CHANGED 08.01.19 !!! coexprFile <- file.path("CREATE_COEXPR_SORTNODUP", curr_TADlist, paste0(curr_dataset), corMethod, "coexprDT.Rdata") stopifnot(file.exists(coexprFile)) sameTADfile <- file.path("CREATE_SAME_TAD_SORTNODUP", curr_TADlist, "all_TAD_pairs.Rdata") stopifnot(file.exists(sameTADfile)) # ADDED 08.01.19 to accommodate updated family file sameFamFolder <- file.path("CREATE_SAME_FAMILY_SORTNODUP", curr_TADlist) # checking the file comes after (iterating over family and family_short) stopifnot(dir.exists(sameFamFolder)) sameFamFile <- file.path(sameFamFolder, paste0(familyData, "_family_all_family_pairs.Rdata")) # at least this one should exist ! stopifnot(file.exists(sameFamFile)) dataset_pipDir <- file.path("PIPELINE", "OUTPUT_FOLDER", curr_TADlist, curr_dataset) # used to retrieve gene list stopifnot(dir.exists(dataset_pipDir)) txt <- paste0("... distFile = ", distFile, "\n") printAndLog(txt, logFile) txt <- paste0("... coexprFile = ", coexprFile, "\n") printAndLog(txt, logFile) txt <- paste0("... sameTADfile = ", sameTADfile, "\n") printAndLog(txt, logFile) txt <- paste0("... sameFamFile = ", sameFamFile, "\n") printAndLog(txt, logFile) ################################################ DATA PREPARATION if(buildTable) { cat(paste0("... load DIST data\t", distFile, "\t", Sys.time(), "\t")) load(distFile) cat(paste0(Sys.time(), "\n")) head(all_dist_pairs) nrow(all_dist_pairs) all_dist_pairs$gene1 <- as.character(all_dist_pairs$gene1) all_dist_pairs$gene2 <- as.character(all_dist_pairs$gene2) # UPDATE 30.06.2018 stopifnot(all_dist_pairs$gene1 < all_dist_pairs$gene2) cat(paste0("... load TAD data\t", sameTADfile, "\t", Sys.time(), "\t")) ### =>>> CHANGED HERE FOR OTHER TAD FILE !!! load(sameTADfile) cat(paste0(Sys.time(), "\n")) head(all_TAD_pairs) nrow(all_TAD_pairs) all_TAD_pairs$gene1 <- as.character(all_TAD_pairs$gene1) all_TAD_pairs$gene2 <- as.character(all_TAD_pairs$gene2) # UPDATE 30.06.2018 stopifnot(all_TAD_pairs$gene1 < all_TAD_pairs$gene2) cat(paste0("... load COEXPR data\t",coexprFile, "\t", Sys.time(), "\t")) load(coexprFile) cat(paste0(Sys.time(), "\n")) head(coexprDT) nrow(coexprDT) coexprDT$gene1 <- as.character(coexprDT$gene1) coexprDT$gene2 <- as.character(coexprDT$gene2) all_TAD_pairs$gene2 # UPDATE 30.06.2018 stopifnot(coexprDT$gene1 < coexprDT$gene2) #============================== RETRIEVE PIPELINE DATA FOR THIS DATASET - USED ONLY FOR GENE LIST script0_name <- "0_prepGeneData" geneFile <- file.path(dataset_pipDir, script0_name, "pipeline_geneList.Rdata") cat(paste0("... load GENELIST file\t",geneFile, "\t", Sys.time(), "\t")) pipeline_geneList <- eval(parse(text = load(geneFile))) pipeline_geneList <- as.character(pipeline_geneList) dataset_dist_pair <- all_dist_pairs[all_dist_pairs$gene1 %in% pipeline_geneList & all_dist_pairs$gene2 %in% pipeline_geneList,] dataset_dist_pairs_limit <- dataset_dist_pair[dataset_dist_pair$dist <= distLimit,] head(dataset_dist_pairs_limit) nrow(dataset_dist_pairs_limit) dataset_TAD_pairs <- all_TAD_pairs[all_TAD_pairs$gene1 %in% pipeline_geneList & all_TAD_pairs$gene2 %in% pipeline_geneList,] head(dataset_TAD_pairs) nrow(dataset_TAD_pairs) # START MERGING DATA cat(paste0("... merge DIST - TAD data\t", Sys.time(), "\t")) dataset_dist_TAD_DT <- left_join(dataset_dist_pairs_limit, dataset_TAD_pairs, by=c("gene1", "gene2")) cat(paste0(Sys.time(), "\n")) dataset_dist_TAD_DT$sameTAD <- ifelse(is.na(dataset_dist_TAD_DT$region), 0, 1) } # all_familyData <- paste0(familyData, c("_family", "_family_short")) all_familyData <- paste0(familyData, c( "_family_short")) outFold_save <- outFold for(i_fam in all_familyData) { outFold <- file.path(outFold_save, i_fam) dir.create(outFold, recursive = TRUE) if(buildTable){ # UPDATE HERE 08.01.19 TO HAVE DATA FROM TISSUE SPECIFIC TAD LIST sameFamFile <- file.path(sameFamFolder, paste0(i_fam, "_all_family_pairs.Rdata")) cat(paste0("... load FAMILY data\t", sameFamFile, "\n", Sys.time(), "\t")) stopifnot(file.exists(sameFamFile)) load(sameFamFile) cat(paste0(Sys.time(), "\n")) head(all_family_pairs) nrow(all_family_pairs) all_family_pairs$gene1 <- as.character(all_family_pairs$gene1) all_family_pairs$gene2 <- as.character(all_family_pairs$gene2) stopifnot(all_family_pairs$gene1 < all_family_pairs$gene2) dataset_family_pairs <- all_family_pairs[all_family_pairs$gene1 %in% pipeline_geneList & all_family_pairs$gene2 %in% pipeline_geneList,] head(dataset_family_pairs) cat(paste0("... merge FAMILY data\t", Sys.time(), "\t")) dataset_dist_TAD_fam_DT <- left_join(dataset_dist_TAD_DT, dataset_family_pairs, by=c("gene1", "gene2")) cat(paste0(Sys.time(), "\n")) dataset_dist_TAD_fam_DT$sameFamily <- ifelse(is.na(dataset_dist_TAD_fam_DT$family), 0, 1) cat(paste0("... merge COEXPR data\t", Sys.time(), "\t")) dataset_dist_TAD_fam_coexpr_DT <- left_join(dataset_dist_TAD_fam_DT, coexprDT, by=c("gene1", "gene2")) cat(paste0(Sys.time(), "\n")) allData_dt <- dataset_dist_TAD_fam_coexpr_DT allData_dt$region <- NULL allData_dt$family <- NULL allData_dt <- na.omit(allData_dt) # outFile <-file.path(outFold, paste0(i_fam, "_", "allData_dt.Rdata")) outFile <-file.path(outFold, paste0( "allData_dt.Rdata")) save(allData_dt, file = outFile) cat(paste0("... written: ", outFile, "\n")) } else{ # outFile <-file.path(outFold, paste0(i_fam, "_", "allData_dt.Rdata")) outFile <-file.path(outFold, paste0( "allData_dt.Rdata")) load(outFile) # load("/media/electron/mnt/ed4/marie/scripts/TAD_DE_pipeline_v2_TopDom/COEXPR_DIST_v3/TCGAcrc_msi_mss_hgnc/hgnc_family_allData_dt.Rdata") } nrow(allData_dt) allData_dt$dist_kb <- allData_dt$dist/1000 allData_dt$curve1 <- ifelse(allData_dt$sameTAD == "0", "diff. TAD", "same TAD") allData_dt$curve2 <- ifelse(allData_dt$sameFamily == "0", NA, ifelse(allData_dt$sameTAD == "0", "same Fam. + diff. TAD", "same Fam. + same TAD")) sameTAD_DT <- allData_dt[allData_dt$sameTAD == 1,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] sameTAD_DT <- na.omit(sameTAD_DT) sameTAD_DT <- sameTAD_DT[order(sameTAD_DT$dist_kb),] sameTAD_DT$nPair <- 1:nrow(sameTAD_DT) sameTAD_DT$label <- "same TAD" diffTAD_DT <- allData_dt[allData_dt$sameTAD == 0,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] diffTAD_DT <- na.omit(diffTAD_DT) diffTAD_DT <- diffTAD_DT[order(diffTAD_DT$dist_kb),] diffTAD_DT$nPair <- 1:nrow(diffTAD_DT) diffTAD_DT$label <- "diff. TAD" sameFam_sameTAD_DT <- allData_dt[allData_dt$sameFamily == 1 & allData_dt$sameTAD == 1 ,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] sameFam_sameTAD_DT <- na.omit(sameFam_sameTAD_DT) sameFam_sameTAD_DT <- sameFam_sameTAD_DT[order(sameFam_sameTAD_DT$dist_kb),] sameFam_sameTAD_DT$nPair <- 1:nrow(sameFam_sameTAD_DT) sameFam_sameTAD_DT$label <- "same Fam. + same TAD" sameFam_diffTAD_DT <- allData_dt[allData_dt$sameFamily == 1 & allData_dt$sameTAD == 0 ,c("gene1", "gene2", "coexpr", "dist", "dist_kb")] sameFam_diffTAD_DT <- na.omit(sameFam_diffTAD_DT) sameFam_diffTAD_DT <- sameFam_diffTAD_DT[order(sameFam_diffTAD_DT$dist_kb),] sameFam_diffTAD_DT$nPair <- 1:nrow(sameFam_diffTAD_DT) sameFam_diffTAD_DT$label <- "same Fam. + diff. TAD" stopifnot(is.numeric(sameTAD_DT$dist[1])) stopifnot(is.numeric(sameTAD_DT$coexpr[1])) stopifnot(is.numeric(diffTAD_DT$dist[1])) stopifnot(is.numeric(diffTAD_DT$coexpr[1])) stopifnot(is.numeric(sameFam_sameTAD_DT$dist[1])) stopifnot(is.numeric(sameFam_sameTAD_DT$coexpr[1])) stopifnot(is.numeric(sameFam_diffTAD_DT$dist[1])) stopifnot(is.numeric(sameFam_diffTAD_DT$coexpr[1])) #*** if(fitMeth == "loess") { my_ylab <- paste0("Gene pair coexpression (", corMethod, ", qqnormDT)") my_xlab <- paste0("Distance between the 2 genes (kb)") my_sub <- paste0(curr_dataset) # PREDICT WITH ORIGINAL DISTANCE VALUES my_xlab <- paste0("Distance between the 2 genes (bp)") diffTAD_mod <- loess(coexpr ~ dist, data = diffTAD_DT) sameTAD_mod <- loess(coexpr ~ dist, data = sameTAD_DT) smooth_vals_sameTAD <- predict(sameTAD_mod, sort(sameTAD_DT$dist)) smooth_vals_diffTAD <- predict(diffTAD_mod, sort(diffTAD_DT$dist)) auc_diffTAD_obsDist <- auc(x = sort(diffTAD_DT$dist), y = smooth_vals_diffTAD) auc_sameTAD_obsDist <- auc(x = sort(sameTAD_DT$dist), y = smooth_vals_sameTAD) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameTAD_diffTAD_loessFit_originalDist", ".", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(allData_dt$dist), ylim = range(c(smooth_vals_sameTAD, smooth_vals_diffTAD)), xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = "observed distance values", side = 3) lines( x = sort(sameTAD_DT$dist), y = smooth_vals_sameTAD, col = sameTADcol) lines( x = sort(diffTAD_DT$dist), y = smooth_vals_diffTAD, col = diffTADcol) legend("topright", legend=c(paste0("sameTAD\n(AUC=", round(auc_sameTAD_obsDist, 2), ")"), paste0("diffTAD\n(AUC=", round(auc_diffTAD_obsDist, 2))), col = c(sameTADcol, diffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) # PREDICT WITH DISTANCE VECTOR distVect <- seq(from=0, to = distLimit, length.out = nbrLoessPoints) smooth_vals_sameTAD_distVect <- predict(sameTAD_mod, distVect) smooth_vals_diffTAD_distVect <- predict(diffTAD_mod, distVect) auc_diffTAD_distVect <- auc(x = distVect, y = smooth_vals_diffTAD_distVect) auc_sameTAD_distVect <- auc(x = distVect, y = smooth_vals_sameTAD_distVect) outFile <- file.path(outFold, "auc_diffTAD_distVect.Rdata") save(auc_diffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "auc_sameTAD_distVect.Rdata") save(auc_sameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_sameTAD_distVect.Rdata") save(smooth_vals_sameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_diffTAD_distVect.Rdata") save(smooth_vals_diffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "distVect.Rdata") save(distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameTAD_diffTAD_loessFit_vectDist.", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(distVect), ylim = range(c(na.omit(smooth_vals_sameTAD_distVect), na.omit(smooth_vals_diffTAD_distVect))), xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = paste0("distance values seq from 0 to ", distLimit, " (# points = ", nbrLoessPoints, ")"), side = 3) lines( x = distVect, y = smooth_vals_sameTAD_distVect, col = sameTADcol) lines( x = distVect, y = smooth_vals_diffTAD_distVect, col = diffTADcol) legend("topright", legend=c(paste0("sameTAD\n(AUC=", round(auc_sameTAD_distVect, 2), ")"), paste0("diffTAD\n(AUC=", round(auc_diffTAD_distVect, 2))), col = c(sameTADcol, diffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) ################################ DO THE SAME FOR SAME FAM SAME TAD VS. SAME FAM DIFF TAD sameFamDiffTAD_mod <- loess(coexpr ~ dist, data = sameFam_diffTAD_DT) sameFamSameTAD_mod <- loess(coexpr ~ dist, data = sameFam_sameTAD_DT) smooth_vals_sameFamSameTAD <- predict(sameFamSameTAD_mod, sort(sameFam_sameTAD_DT$dist)) smooth_vals_sameFamDiffTAD <- predict(sameFamDiffTAD_mod, sort(sameFam_diffTAD_DT$dist)) auc_sameFamDiffTAD_obsDist <- auc(x = sort(sameFam_diffTAD_DT$dist), y = smooth_vals_sameFamDiffTAD) auc_sameFamSameTAD_obsDist <- auc(x = sort(sameFam_sameTAD_DT$dist), y = smooth_vals_sameFamSameTAD) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameFamSameTAD_sameFamDiffTAD_loessFit_originalDist", ".", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(allData_dt$dist), ylim = range(c(smooth_vals_sameFamSameTAD, smooth_vals_sameFamDiffTAD)), xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = "observed distance values", side = 3) lines( x = sort(sameFam_sameTAD_DT$dist), y = smooth_vals_sameFamSameTAD, col = sameFamSameTADcol) lines( x = sort(sameFam_diffTAD_DT$dist), y = smooth_vals_sameFamDiffTAD, col = sameFamDiffTADcol) legend("topright", legend=c(paste0("sameFamSameTAD\n(AUC=", round(auc_sameFamSameTAD_obsDist, 2), ")"), paste0("sameFamDiffTAD\n(AUC=", round(auc_sameFamDiffTAD_obsDist, 2))), col = c(sameFamSameTADcol, sameFamDiffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) # PREDICT WITH DISTANCE VECTOR smooth_vals_sameFamSameTAD_distVect <- predict(sameFamSameTAD_mod, distVect) smooth_vals_sameFamDiffTAD_distVect <- predict(sameFamDiffTAD_mod, distVect) auc_sameFamDiffTAD_distVect <- auc(x = distVect, y = smooth_vals_sameFamDiffTAD_distVect) auc_sameFamSameTAD_distVect <- auc(x = distVect, y = smooth_vals_sameFamSameTAD_distVect) outFile <- file.path(outFold, "diffTAD_mod.Rdata") save(diffTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "sameFamDiffTAD_mod.Rdata") save(sameFamDiffTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "sameTAD_mod.Rdata") save(sameTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "sameFamSameTAD_mod.Rdata") save(sameFamSameTAD_mod, file = outFile) cat(paste0("... written: ", outFile, "\n")) sameFamDiffTAD_obsDist <- sameFam_diffTAD_DT$dist outFile <- file.path(outFold, "sameFamDiffTAD_obsDist.Rdata") save(sameFamDiffTAD_obsDist, file = outFile) cat(paste0("... written: ", outFile, "\n")) sameFamSameTAD_obsDist <- sameFam_sameTAD_DT$dist outFile <- file.path(outFold, "sameFamSameTAD_obsDist.Rdata") save(sameFamSameTAD_obsDist, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "auc_sameFamDiffTAD_distVect.Rdata") save(auc_sameFamDiffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "auc_sameFamSameTAD_distVect.Rdata") save(auc_sameFamSameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_sameFamSameTAD_distVect.Rdata") save(smooth_vals_sameFamSameTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, "smooth_vals_sameFamDiffTAD_distVect.Rdata") save(smooth_vals_sameFamDiffTAD_distVect, file = outFile) cat(paste0("... written: ", outFile, "\n")) outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameFamSameTAD_sameFamDiffTAD_loessFit_vectDist.", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(distVect), ylim = range(c(na.omit(smooth_vals_sameFamSameTAD_distVect), na.omit(smooth_vals_sameFamDiffTAD_distVect))), # xlab="", # ylab="", xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = paste0("distance values seq from 0 to ", distLimit, " (# points = ", nbrLoessPoints, ")"), side = 3) lines( x = distVect, y = smooth_vals_sameFamSameTAD_distVect, col = sameFamSameTADcol) lines( x = distVect, y = smooth_vals_sameFamDiffTAD_distVect, col = sameFamDiffTADcol) legend("topright", legend=c(paste0("sameFamSameTAD\n(AUC=", round(auc_sameFamSameTAD_distVect, 2), ")"), paste0("sameFamDiffTAD\n(AUC=", round(auc_sameFamDiffTAD_distVect, 2))), col = c(sameFamSameTADcol, sameFamDiffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) ################################################################ outFile <- file.path(outFold, paste0(curr_TADlist, "_", curr_dataset, "_sameTAD_diffTAD_sameFamSameTAD_sameFamDiffTAD_loessFit_vectDist.", plotType)) do.call(plotType, list(outFile, height = myHeight, width = myWidth)) plot(NULL, xlim = range(distVect), ylim = range(c(na.omit(smooth_vals_sameTAD_distVect), na.omit(smooth_vals_sameFamSameTAD_distVect), na.omit(smooth_vals_diffTAD_distVect), na.omit(smooth_vals_sameFamDiffTAD_distVect))), # xlab="", # ylab="", xlab=my_xlab, ylab=my_ylab, main=paste0(curr_TADlist, " - ", curr_dataset, ": coexpr ~ dist loess fit")) mtext(text = paste0("distance values seq from 0 to ", distLimit, " (# points = ", nbrLoessPoints, ")"), side = 3) lines( x = distVect, y = smooth_vals_sameFamSameTAD_distVect, col = sameFamSameTADcol) lines( x = distVect, y = smooth_vals_sameFamDiffTAD_distVect, col = sameFamDiffTADcol) lines( x = distVect, y = smooth_vals_sameTAD_distVect, col = sameTADcol) lines( x = distVect, y = smooth_vals_diffTAD_distVect, col = diffTADcol) legend("topright", legend=c(paste0("sameTAD\n(AUC=", round(auc_sameTAD_distVect, 2), ")"), paste0("diffTAD\n(AUC=", round(auc_diffTAD_distVect, 2)), paste0("sameFamSameTAD\n(AUC=", round(auc_sameFamSameTAD_distVect, 2), ")"), paste0("sameFamDiffTAD\n(AUC=", round(auc_sameFamDiffTAD_distVect, 2))), col = c(sameTADcol, diffTADcol, sameFamSameTADcol, sameFamDiffTADcol), lty=1, bty = "n") foo <- dev.off() cat(paste0("... written: ", outFile, "\n")) ################################################################ auc_values <- list( auc_diffTAD_distVect = auc_diffTAD_distVect, auc_sameTAD_distVect = auc_sameTAD_distVect, auc_ratio_same_over_diff_distVect = auc_sameTAD_distVect/auc_diffTAD_distVect, auc_diffTAD_obsDist = auc_diffTAD_obsDist, auc_sameTAD_obsDist = auc_sameTAD_obsDist, auc_ratio_same_over_diff_obsDist = auc_sameTAD_distVect/auc_diffTAD_obsDist, auc_sameFamDiffTAD_distVect = auc_sameFamDiffTAD_distVect, auc_sameFamSameTAD_distVect = auc_sameFamSameTAD_distVect, auc_ratio_sameFam_same_over_diff_distVect = auc_sameFamSameTAD_distVect/auc_sameFamDiffTAD_distVect, auc_sameFamDiffTAD_obsDist = auc_sameFamDiffTAD_obsDist, auc_sameFamSameTAD_obsDist = auc_sameFamSameTAD_obsDist, auc_ratio_sameFam_same_over_diff_obsDist = auc_sameFamSameTAD_distVect/auc_sameFamDiffTAD_obsDist ) outFile <- file.path(outFold, paste0("auc_values.Rdata")) save(auc_values, file = outFile) cat(paste0("... written: ", outFile, "\n")) } else{ stop("only loess implemented yet\n") } } # end iterating over family data ###################################################################################### ###################################################################################### ###################################################################################### cat(paste0("... written: ", logFile, "\n")) ###################################################################################### cat("*** DONE\n") cat(paste0(startTime, "\n", Sys.time(), "\n"))
context("Screen flow data") test_that("creates a dataframe with the proper columns", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = "08NM116", include_symbols = FALSE) expect_true(is.data.frame(data) & ncol(data) == 22 & all(c("Year","n_days","n_Q","n_missing_Q","Minimum","Jan_missing_Q") %in% colnames(data))) }) test_that("outputs data for two stations", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = c("08NM116","08HB048"), include_symbols = FALSE) expect_true(length(unique(data$STATION_NUMBER)) == 2) }) test_that("data is filtered by years properly", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = "08NM116", start_year = 1981, end_year = 2010, include_symbols = FALSE) expect_identical(1981, min(data$Year)) expect_identical(2010, max(data$Year)) }) test_that("data is summarized by water years properly", { skip_on_cran() skip_on_ci() flow_data <- add_date_variables(station_number = "08NM116", water_year_start = 10) test_data <- dplyr::filter(flow_data, WaterYear == 1981) test_data <- dplyr::summarise(test_data, Mean = mean(Value), Median = median(Value), Maximum = max(Value), Minimum = min(Value)) data <- screen_flow_data(data = flow_data, start_year = 1981, water_year_start = 10, include_symbols = FALSE) data <- dplyr::filter(data, Year == 1981) data <- dplyr::select(data, Mean, Median, Maximum, Minimum) expect_equal(test_data, data) }) test_that("missing dates are calculated properly", { skip_on_cran() skip_on_ci() flow_data <- fill_missing_dates(station_number = "08NM116") flow_data <- add_date_variables(flow_data) test_data <- dplyr::summarise(dplyr::group_by(flow_data, WaterYear, MonthName), sum = sum(is.na(Value))) test_data <- tidyr::spread(test_data, MonthName, sum) data <- screen_flow_data(station_number = "08NM116", include_symbols = FALSE) expect_equal(test_data$Jan, data$Jan_missing_Q) }) test_that("data is filtered by months properly", { skip_on_cran() skip_on_ci() flow_data <- add_date_variables(station_number = "08NM116") test_data <- dplyr::filter(flow_data, WaterYear == 1981, Month %in% 7:9) test_data <- dplyr::summarise(test_data, Mean = mean(Value), Median = median(Value), Maximum = max(Value), Minimum = min(Value)) data <- screen_flow_data(data = flow_data, start_year = 1981, months = 7:9, include_symbols = FALSE) data_test <- dplyr::filter(data, Year == 1981) data_test <- dplyr::select(data_test, Mean, Median, Maximum, Minimum) expect_equal(test_data, data_test) expect_true(ncol(data) == 13) }) test_that("transpose properly transposed the results", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = "08NM116", transpose = TRUE, include_symbols = FALSE) expect_true(all(c("n_days","n_Q","n_missing_Q","Minimum","Jan_missing_Q") %in% data$Statistic)) })
/tests/testthat/test-screen_flow_data.R
no_license
cran/fasstr
R
false
false
3,714
r
context("Screen flow data") test_that("creates a dataframe with the proper columns", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = "08NM116", include_symbols = FALSE) expect_true(is.data.frame(data) & ncol(data) == 22 & all(c("Year","n_days","n_Q","n_missing_Q","Minimum","Jan_missing_Q") %in% colnames(data))) }) test_that("outputs data for two stations", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = c("08NM116","08HB048"), include_symbols = FALSE) expect_true(length(unique(data$STATION_NUMBER)) == 2) }) test_that("data is filtered by years properly", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = "08NM116", start_year = 1981, end_year = 2010, include_symbols = FALSE) expect_identical(1981, min(data$Year)) expect_identical(2010, max(data$Year)) }) test_that("data is summarized by water years properly", { skip_on_cran() skip_on_ci() flow_data <- add_date_variables(station_number = "08NM116", water_year_start = 10) test_data <- dplyr::filter(flow_data, WaterYear == 1981) test_data <- dplyr::summarise(test_data, Mean = mean(Value), Median = median(Value), Maximum = max(Value), Minimum = min(Value)) data <- screen_flow_data(data = flow_data, start_year = 1981, water_year_start = 10, include_symbols = FALSE) data <- dplyr::filter(data, Year == 1981) data <- dplyr::select(data, Mean, Median, Maximum, Minimum) expect_equal(test_data, data) }) test_that("missing dates are calculated properly", { skip_on_cran() skip_on_ci() flow_data <- fill_missing_dates(station_number = "08NM116") flow_data <- add_date_variables(flow_data) test_data <- dplyr::summarise(dplyr::group_by(flow_data, WaterYear, MonthName), sum = sum(is.na(Value))) test_data <- tidyr::spread(test_data, MonthName, sum) data <- screen_flow_data(station_number = "08NM116", include_symbols = FALSE) expect_equal(test_data$Jan, data$Jan_missing_Q) }) test_that("data is filtered by months properly", { skip_on_cran() skip_on_ci() flow_data <- add_date_variables(station_number = "08NM116") test_data <- dplyr::filter(flow_data, WaterYear == 1981, Month %in% 7:9) test_data <- dplyr::summarise(test_data, Mean = mean(Value), Median = median(Value), Maximum = max(Value), Minimum = min(Value)) data <- screen_flow_data(data = flow_data, start_year = 1981, months = 7:9, include_symbols = FALSE) data_test <- dplyr::filter(data, Year == 1981) data_test <- dplyr::select(data_test, Mean, Median, Maximum, Minimum) expect_equal(test_data, data_test) expect_true(ncol(data) == 13) }) test_that("transpose properly transposed the results", { skip_on_cran() skip_on_ci() data <- screen_flow_data(station_number = "08NM116", transpose = TRUE, include_symbols = FALSE) expect_true(all(c("n_days","n_Q","n_missing_Q","Minimum","Jan_missing_Q") %in% data$Statistic)) })
> ###Random Forest top 5 variables based on importance: strikeouts, wins, earned run average, at bats, and innings pitched > ###Find players who have same minimum amount of strikeouts, wins, earned run average, at bats, and innings pitched as award winners > Pitching_Stats_Full_Dataset <- read_csv("E:/Grad School/Practicum 2/Pitching Stats Full Dataset.csv", + col_types = cols(`2b ` = col_number(), + `3b ` = col_number(), Award = col_number(), + ConfStanding = col_number(), Year = col_number(), + `ab ` = col_number(), app = col_number(), + `bavg ` = col_number(), `bb ` = col_number(), + `bk ` = col_number(), `cg ` = col_number(), + csho = col_number(), `er ` = col_number(), + `era ` = col_number(), `gs ` = col_number(), + `h ` = col_number(), `hbp ` = col_number(), + `hr ` = col_number(), `ip ` = col_number(), + `isho ` = col_number(), `l ` = col_number(), + `r ` = col_number(), `so ` = col_number(), + `sv ` = col_number(), w = col_number(), + `wp ` = col_number()), locale = locale(encoding = "ASCII")) > psfd <- Pitching_Stats_Full_Dataset > library(dplyr) > first <- filter(psfd, psfd$Award == 1) > second <- filter(psfd, psfd$Award == 2) > noteam <- filter(psfd, psfd$Award == 0) > summary(psfd) > psfd$Award <- as.factor(psfd$Award) > summary(first) > ###Stat Requirements needed for 1st Team: strikeouts >= 45, wins >= 6, earned run average <= 4.287, at bats >= 228, innings pitched >= 60.83 > firstteamcandidates <- filter(psfd, psfd$Award == 0 | psfd$Award == 2) > ftc_stats <- filter(firstteamcandidates, firstteamcandidates$`so ` >= 45 & firstteamcandidates$w >= 6 & firstteamcandidates$`era ` <= 4.287 & firstteamcandidates$`ab ` >= 228 & firstteamcandidates$`ip ` >= 60.83) > View(ftc_stats) > write.csv(ftc_stats, "First Team Candidates.csv")
/Pitching Candidates.R
no_license
dlacomb/RMACPitchingVoting
R
false
false
2,717
r
> ###Random Forest top 5 variables based on importance: strikeouts, wins, earned run average, at bats, and innings pitched > ###Find players who have same minimum amount of strikeouts, wins, earned run average, at bats, and innings pitched as award winners > Pitching_Stats_Full_Dataset <- read_csv("E:/Grad School/Practicum 2/Pitching Stats Full Dataset.csv", + col_types = cols(`2b ` = col_number(), + `3b ` = col_number(), Award = col_number(), + ConfStanding = col_number(), Year = col_number(), + `ab ` = col_number(), app = col_number(), + `bavg ` = col_number(), `bb ` = col_number(), + `bk ` = col_number(), `cg ` = col_number(), + csho = col_number(), `er ` = col_number(), + `era ` = col_number(), `gs ` = col_number(), + `h ` = col_number(), `hbp ` = col_number(), + `hr ` = col_number(), `ip ` = col_number(), + `isho ` = col_number(), `l ` = col_number(), + `r ` = col_number(), `so ` = col_number(), + `sv ` = col_number(), w = col_number(), + `wp ` = col_number()), locale = locale(encoding = "ASCII")) > psfd <- Pitching_Stats_Full_Dataset > library(dplyr) > first <- filter(psfd, psfd$Award == 1) > second <- filter(psfd, psfd$Award == 2) > noteam <- filter(psfd, psfd$Award == 0) > summary(psfd) > psfd$Award <- as.factor(psfd$Award) > summary(first) > ###Stat Requirements needed for 1st Team: strikeouts >= 45, wins >= 6, earned run average <= 4.287, at bats >= 228, innings pitched >= 60.83 > firstteamcandidates <- filter(psfd, psfd$Award == 0 | psfd$Award == 2) > ftc_stats <- filter(firstteamcandidates, firstteamcandidates$`so ` >= 45 & firstteamcandidates$w >= 6 & firstteamcandidates$`era ` <= 4.287 & firstteamcandidates$`ab ` >= 228 & firstteamcandidates$`ip ` >= 60.83) > View(ftc_stats) > write.csv(ftc_stats, "First Team Candidates.csv")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/predict_mbsts.R \name{predict.mbsts} \alias{predict.mbsts} \title{Predictions for a given multivariate Bayesian structural time series model} \usage{ \method{predict}{mbsts}(object, steps.ahead, newdata = NULL, ...) } \arguments{ \item{object}{An object of class 'mbsts', a result of call to \code{\link{as.mbsts}}.} \item{steps.ahead}{An integer value (S) specifying the number of steps ahead to be forecasted. If 'object' contains a regression component, the argument is disregarded and a prediction is made with the same length of 'newdata'.} \item{newdata}{Optional matrix of new data. Only required when 'object' contains a regression component.} \item{...}{Arguments passed to other methods (currently unused).} } \value{ Returns a list with the following components \describe{ \item{post.pred.0}{t x d x ('niter'- 'burn') array of in-sample forecasts.} \item{post.pred.1}{S x d x ('niter'- 'burn') array out-of-sample forecasts, where S is the number of forecasted periods (set to the length of 'steps.ahead' or 'newdata').} \item{post.pred}{(t + S) x d x ('niter'- 'burn') array combining in- and out-of-sample forecasts.} } } \description{ Given an object of class 'mbsts' and the number of 'steps.ahead' in the future to be forecasted, this function provides in-sample forecasts and out-of-sample forecasts, both based on drawing from the posterior predictive distribution. If 'mbsts' contains a regression component, then the new matrix of predictors 'newdata' must be provided. Note that NA values are not allowed in the new regressor matrix. } \examples{ ## Note: The following are toy examples, for a proper analysis we recommend to run ## at least 1000 iterations and check the convergence of the Markov chain ## Example 1 : y <- cbind(seq(0.5,100,by=0.5)*0.1 + rnorm(200), seq(100.25,150,by=0.25)*0.05 + rnorm(200), rnorm(200, 5,1)) mbsts.1 <- as.mbsts(y = y, components = c("trend", "seasonal"), seas.period = 7, s0.r = diag(3), s0.eps = diag(3), niter = 50, burn = 5) pred.1 <- predict(mbsts.1, steps.ahead = 10) ## Example 2 y <- cbind(rnorm(100), rnorm(100, 2, 3)) X <- cbind(rnorm(100, 0.5, 1) + 5, rnorm(100, 0.2, 2) - 2) mbsts.2 <- as.mbsts(y = y, components = c("trend", "seasonal"), seas.period = 7, X = X, s0.r = diag(2), s0.eps = diag(2), niter = 100, burn = 10) newdata <- cbind(rnorm(30), rt(30, 2)) pred.2 <- predict(mbsts.2, newdata = newdata) }
/man/predict.mbsts.Rd
no_license
FMenchetti/CausalMBSTS
R
false
true
2,562
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/predict_mbsts.R \name{predict.mbsts} \alias{predict.mbsts} \title{Predictions for a given multivariate Bayesian structural time series model} \usage{ \method{predict}{mbsts}(object, steps.ahead, newdata = NULL, ...) } \arguments{ \item{object}{An object of class 'mbsts', a result of call to \code{\link{as.mbsts}}.} \item{steps.ahead}{An integer value (S) specifying the number of steps ahead to be forecasted. If 'object' contains a regression component, the argument is disregarded and a prediction is made with the same length of 'newdata'.} \item{newdata}{Optional matrix of new data. Only required when 'object' contains a regression component.} \item{...}{Arguments passed to other methods (currently unused).} } \value{ Returns a list with the following components \describe{ \item{post.pred.0}{t x d x ('niter'- 'burn') array of in-sample forecasts.} \item{post.pred.1}{S x d x ('niter'- 'burn') array out-of-sample forecasts, where S is the number of forecasted periods (set to the length of 'steps.ahead' or 'newdata').} \item{post.pred}{(t + S) x d x ('niter'- 'burn') array combining in- and out-of-sample forecasts.} } } \description{ Given an object of class 'mbsts' and the number of 'steps.ahead' in the future to be forecasted, this function provides in-sample forecasts and out-of-sample forecasts, both based on drawing from the posterior predictive distribution. If 'mbsts' contains a regression component, then the new matrix of predictors 'newdata' must be provided. Note that NA values are not allowed in the new regressor matrix. } \examples{ ## Note: The following are toy examples, for a proper analysis we recommend to run ## at least 1000 iterations and check the convergence of the Markov chain ## Example 1 : y <- cbind(seq(0.5,100,by=0.5)*0.1 + rnorm(200), seq(100.25,150,by=0.25)*0.05 + rnorm(200), rnorm(200, 5,1)) mbsts.1 <- as.mbsts(y = y, components = c("trend", "seasonal"), seas.period = 7, s0.r = diag(3), s0.eps = diag(3), niter = 50, burn = 5) pred.1 <- predict(mbsts.1, steps.ahead = 10) ## Example 2 y <- cbind(rnorm(100), rnorm(100, 2, 3)) X <- cbind(rnorm(100, 0.5, 1) + 5, rnorm(100, 0.2, 2) - 2) mbsts.2 <- as.mbsts(y = y, components = c("trend", "seasonal"), seas.period = 7, X = X, s0.r = diag(2), s0.eps = diag(2), niter = 100, burn = 10) newdata <- cbind(rnorm(30), rt(30, 2)) pred.2 <- predict(mbsts.2, newdata = newdata) }
#' timeFloor #' #' This function acts like a floor function execpt for time. #' #' @param timeValue typically a column of time Values to take the floor function #' @param timeIntervalValue the value of the time interval #' @param timeIntervalUnits the units of the time interval #' @keywords time #' @examples #' #' library(EmissionsHelper) #' mytime <- reformatTime(c("2018-1-1 12:01", "2018-1-1 12:02", #' "2018-1-1 12:16", "2018-1-1 12:17")) #' timeFloor(mytime, 15, "minutes") #' #' @export timeFloor <- function(timeValue, timeIntervalValue = 15, timeIntervalUnits = "minutes"){ timeIntervalInSeconds <- switch(timeIntervalUnits, "seconds" = 1, "second" = 1, "sec" = 1, "s" = 1, "minutes" = 60, "minute" = 60, "min" = 60, "m" = 60, "hours" = 3600, "hour" = 3600, "hr" = 3600, "h" = 3600) if(!is.null(timeValue)){ return(as.POSIXct(floor(as.numeric(as.POSIXct(timeValue)) / (timeIntervalValue * timeIntervalInSeconds)) * (timeIntervalValue * timeIntervalInSeconds), origin='1970-01-01')) }else{ warning("Check parameters in timeFloor function ... timeValue is NULL") } }
/R/timeFloor.R
permissive
JerryHMartin/EmissionsHelper
R
false
false
1,661
r
#' timeFloor #' #' This function acts like a floor function execpt for time. #' #' @param timeValue typically a column of time Values to take the floor function #' @param timeIntervalValue the value of the time interval #' @param timeIntervalUnits the units of the time interval #' @keywords time #' @examples #' #' library(EmissionsHelper) #' mytime <- reformatTime(c("2018-1-1 12:01", "2018-1-1 12:02", #' "2018-1-1 12:16", "2018-1-1 12:17")) #' timeFloor(mytime, 15, "minutes") #' #' @export timeFloor <- function(timeValue, timeIntervalValue = 15, timeIntervalUnits = "minutes"){ timeIntervalInSeconds <- switch(timeIntervalUnits, "seconds" = 1, "second" = 1, "sec" = 1, "s" = 1, "minutes" = 60, "minute" = 60, "min" = 60, "m" = 60, "hours" = 3600, "hour" = 3600, "hr" = 3600, "h" = 3600) if(!is.null(timeValue)){ return(as.POSIXct(floor(as.numeric(as.POSIXct(timeValue)) / (timeIntervalValue * timeIntervalInSeconds)) * (timeIntervalValue * timeIntervalInSeconds), origin='1970-01-01')) }else{ warning("Check parameters in timeFloor function ... timeValue is NULL") } }
AL.Batting=read.table("AL.Batting.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Pitching=read.table("AL.Pitching.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Fielding=read.table("AL.Fielding.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Batting=read.table("NL.Batting.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Pitching=read.table("NL.Pitching.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Fielding=read.table("NL.Fielding.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Batting.2014=read.table("AL.Batting.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Pitching.2014=read.table("AL.Pitching.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Fielding.2014=read.table("AL.Fielding.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Batting.2014=read.table("NL.Batting.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Pitching.2014=read.table("NL.Pitching.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Fielding.2014=read.table("NL.Fielding.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL=cbind(AL.Batting,AL.Pitching[,-1],AL.Fielding[,-1]) NL=cbind(NL.Batting,NL.Pitching[,-1],NL.Fielding[,-1]) AL.year=rep(c("09","10","11","12","13"),c(14,14,14,14,15)) NL.year=rep(c("09","10","11","12","13"),c(16,16,16,16,15)) AL$Tm=paste(AL.year,AL$Tm) NL$Tm=paste(NL.year,NL$Tm) AL.2014=cbind(AL.Batting.2014,AL.Pitching.2014[,-1],AL.Fielding.2014[,-1]) NL.2014=cbind(NL.Batting.2014,NL.Pitching.2014[,-1],NL.Fielding.2014[,-1]) AL.2014$Tm=paste(rep("14",15),AL.2014$Tm) NL.2014$Tm=paste(rep("14",15),NL.2014$Tm) AL.TOTAL=rbind(AL,AL.2014) NL.TOTAL=rbind(NL,NL.2014) ############################################################## AL.model=kmeans(AL.TOTAL[,-1],10,nstart=length(AL.TOTAL$Tm)) AL.cluster.team=data.frame(AL.TOTAL$Tm,AL.model$cluster) NL.model=kmeans(NL.TOTAL[,-1],10,nstart=length(NL.TOTAL$Tm)) NL.cluster.team=data.frame(NL.TOTAL$Tm,10+NL.model$cluster) ################################################################## library(XML) library(RCurl) webpage<-getURL("http://www.baseball-reference.com/teams/STL/2009-schedule-scores.shtml") webpage <- readLines(tc <- textConnection(webpage)); close(tc) pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE) tablelines <- xpathSApply(pagetree, "//tr[@class='']", xmlValue) n=length(tablelines) lines=strsplit(tablelines[2:n],"\n ",fixed=FALSE, useBytes = TRUE) datamatrix=matrix(0,length(lines),6) for(i in 1:length(lines)) { datamatrix[i,1:6]=(lines[[i]])[c(5:7,9:10,21)] } datamatrix[,1]=sub(" ",replacement="",datamatrix[,1]) datamatrix[,2]=ifelse(datamatrix[,2]==" @","Guest","Home") datamatrix[,3]=sub(" ",replacement="",datamatrix[,3]) datamatrix[,4]=sub(" ",replacement="",datamatrix[,4]) datamatrix[,4]=sub("Game Preview, Matchups, and Tickets",replacement="",datamatrix[,4]) datamatrix[,5]=sub(" ",replacement="",datamatrix[,5]) datamatrix[,5]=sub("\n",replacement="",datamatrix[,5]) datamatrix[,6]=sub("\n",replacement="",datamatrix[,6]) datamatrix[,6]=sub(" ",replacement="",datamatrix[,6]) datamatrix=datamatrix[!(datamatrix[,4]==""),] tidydata=matrix(0,length(datamatrix[,1]),5) for(i in 1:length(datamatrix[,1])) { tidydata[i,1]=ifelse(datamatrix[i,2]=="Guest",datamatrix[i,1],datamatrix[i,3]) tidydata[i,2]=ifelse(datamatrix[i,2]=="Home",datamatrix[i,1],datamatrix[i,3]) tidydata[i,3]=ifelse(datamatrix[i,2]=="Guest",datamatrix[i,4],datamatrix[i,5]) tidydata[i,4]=ifelse(datamatrix[i,2]=="Home",datamatrix[i,4],datamatrix[i,5]) }
/mlb.R
no_license
ShaneKao/SportsLottery
R
false
false
3,560
r
AL.Batting=read.table("AL.Batting.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Pitching=read.table("AL.Pitching.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Fielding=read.table("AL.Fielding.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Batting=read.table("NL.Batting.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Pitching=read.table("NL.Pitching.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Fielding=read.table("NL.Fielding.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Batting.2014=read.table("AL.Batting.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Pitching.2014=read.table("AL.Pitching.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL.Fielding.2014=read.table("AL.Fielding.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Batting.2014=read.table("NL.Batting.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Pitching.2014=read.table("NL.Pitching.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) NL.Fielding.2014=read.table("NL.Fielding.2014.txt",sep=",",header=TRUE,stringsAsFactors=FALSE) AL=cbind(AL.Batting,AL.Pitching[,-1],AL.Fielding[,-1]) NL=cbind(NL.Batting,NL.Pitching[,-1],NL.Fielding[,-1]) AL.year=rep(c("09","10","11","12","13"),c(14,14,14,14,15)) NL.year=rep(c("09","10","11","12","13"),c(16,16,16,16,15)) AL$Tm=paste(AL.year,AL$Tm) NL$Tm=paste(NL.year,NL$Tm) AL.2014=cbind(AL.Batting.2014,AL.Pitching.2014[,-1],AL.Fielding.2014[,-1]) NL.2014=cbind(NL.Batting.2014,NL.Pitching.2014[,-1],NL.Fielding.2014[,-1]) AL.2014$Tm=paste(rep("14",15),AL.2014$Tm) NL.2014$Tm=paste(rep("14",15),NL.2014$Tm) AL.TOTAL=rbind(AL,AL.2014) NL.TOTAL=rbind(NL,NL.2014) ############################################################## AL.model=kmeans(AL.TOTAL[,-1],10,nstart=length(AL.TOTAL$Tm)) AL.cluster.team=data.frame(AL.TOTAL$Tm,AL.model$cluster) NL.model=kmeans(NL.TOTAL[,-1],10,nstart=length(NL.TOTAL$Tm)) NL.cluster.team=data.frame(NL.TOTAL$Tm,10+NL.model$cluster) ################################################################## library(XML) library(RCurl) webpage<-getURL("http://www.baseball-reference.com/teams/STL/2009-schedule-scores.shtml") webpage <- readLines(tc <- textConnection(webpage)); close(tc) pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE) tablelines <- xpathSApply(pagetree, "//tr[@class='']", xmlValue) n=length(tablelines) lines=strsplit(tablelines[2:n],"\n ",fixed=FALSE, useBytes = TRUE) datamatrix=matrix(0,length(lines),6) for(i in 1:length(lines)) { datamatrix[i,1:6]=(lines[[i]])[c(5:7,9:10,21)] } datamatrix[,1]=sub(" ",replacement="",datamatrix[,1]) datamatrix[,2]=ifelse(datamatrix[,2]==" @","Guest","Home") datamatrix[,3]=sub(" ",replacement="",datamatrix[,3]) datamatrix[,4]=sub(" ",replacement="",datamatrix[,4]) datamatrix[,4]=sub("Game Preview, Matchups, and Tickets",replacement="",datamatrix[,4]) datamatrix[,5]=sub(" ",replacement="",datamatrix[,5]) datamatrix[,5]=sub("\n",replacement="",datamatrix[,5]) datamatrix[,6]=sub("\n",replacement="",datamatrix[,6]) datamatrix[,6]=sub(" ",replacement="",datamatrix[,6]) datamatrix=datamatrix[!(datamatrix[,4]==""),] tidydata=matrix(0,length(datamatrix[,1]),5) for(i in 1:length(datamatrix[,1])) { tidydata[i,1]=ifelse(datamatrix[i,2]=="Guest",datamatrix[i,1],datamatrix[i,3]) tidydata[i,2]=ifelse(datamatrix[i,2]=="Home",datamatrix[i,1],datamatrix[i,3]) tidydata[i,3]=ifelse(datamatrix[i,2]=="Guest",datamatrix[i,4],datamatrix[i,5]) tidydata[i,4]=ifelse(datamatrix[i,2]=="Home",datamatrix[i,4],datamatrix[i,5]) }
#' BUS #' #' The class BUS #' #' @field n total number of buses #' @field index bus indexes #' @field int internal nus number #' @field Pg active power injected in the network by generators #' @field Qg reactive power injected in the network by generators #' @field Pl active power absorbed from the network by loads #' @field Ql reactive power absorbed from the network by loads #' @field names bus names BUS <- setRefClass("BUS", contains = "powerr", fields = list(n = "numeric", index = "numeric", int = "numeric", a = "numeric", v = "numeric", Pg = "numeric", Qg = "numeric", Pl = "numeric", Ql = "numeric", names = "character"), methods = list( initialize = function(data, n, index, int, a, v, Pg, Qg, Pl, Ql, names, ncol){ n <<- numeric(); a <<- numeric(); v <<- numeric(); index <<- numeric(); int <<- numeric(); Pg <<- numeric(); Qg <<- numeric(); Pl <<- numeric(); Ql <<- numeric(); names <<- character(); ncol <<- 6; }, setup = function(){ if (nrow(data) == 0 && ncol(data) == 0){ print('The data file does not seem to be in a valid format: no bus found$') } n <<- nrow(data); a <<- 1:n; v <<- a + n; # setup internal bus number for second indexing of bus int[data[, 1]] <<- a; .GlobalEnv$DAE$m <- 2 * n; .GlobalEnv$DAE$y <- rep(0, .GlobalEnv$DAE$m); .GlobalEnv$DAE$g <- rep(0, .GlobalEnv$DAE$m); # .GlobalEnv$DAE$Gy <- Matrix(0, nrow = .GlobalEnv$DAE$m, ncol = .GlobalEnv$DAE$m, sparse = TRUE); .GlobalEnv$DAE$Gy <- matrix(0, nrow = .GlobalEnv$DAE$m, ncol = .GlobalEnv$DAE$m); if (ncol(data) >= 4){ # check voltage magnitudes if (sum(data[, 3] < 0.5) > 0){ warning('some initial guess voltage magnitudes are too low.'); } if (sum(data[, 3] > 1.5) > 0){ warning('some initial guess voltage magnitudes are too high.'); } .GlobalEnv$DAE$y[v] <- data[, 3]; # check voltage phases if (sum(data[, 4] < -1.5708) > 0){ warning('some initial guess voltage phases are too low.'); } if (sum(data[, 4] > 1.5708) > 0){ warning('some initial guess voltage phases are too high.'); } .GlobalEnv$DAE$y[a] <- data[, 4]; } else{ .GlobalEnv$DAE$y[a] <- rep(0, n); .GlobalEnv$DAE$y[v] <- rep(1, n); } Pl <<- rep(0, n); Ql <<- rep(0, n); Pg <<- rep(0, n); Qg <<- rep(0, n); }, getbus = function(idx){ uTemp <- int[round(idx)]; vTemp <- uTemp + n; return(list(uTemp, vTemp)); }, getzeros = function(){ uTemp <- rep(0, n); return(uTemp); }, getint = function(idx){ uTemp <- int[round(idx)]; return(uTemp); }, test = function(){ print(environment()) print(parent.env(environment())) print(parent.env(parent.env(environment()))) print(parent.env(parent.env(parent.env(environment())))) print(parent.env(parent.env(parent.env(parent.env(environment()))))) .GlobalEnv$DAE$m <- 1000; .GlobalEnv$DAE$n <- .GlobalEnv$DAE$m; print(.GlobalEnv$DAE$n) } ))
/R/class_BUS.R
no_license
Jingfan-Sun/powerr
R
false
false
5,440
r
#' BUS #' #' The class BUS #' #' @field n total number of buses #' @field index bus indexes #' @field int internal nus number #' @field Pg active power injected in the network by generators #' @field Qg reactive power injected in the network by generators #' @field Pl active power absorbed from the network by loads #' @field Ql reactive power absorbed from the network by loads #' @field names bus names BUS <- setRefClass("BUS", contains = "powerr", fields = list(n = "numeric", index = "numeric", int = "numeric", a = "numeric", v = "numeric", Pg = "numeric", Qg = "numeric", Pl = "numeric", Ql = "numeric", names = "character"), methods = list( initialize = function(data, n, index, int, a, v, Pg, Qg, Pl, Ql, names, ncol){ n <<- numeric(); a <<- numeric(); v <<- numeric(); index <<- numeric(); int <<- numeric(); Pg <<- numeric(); Qg <<- numeric(); Pl <<- numeric(); Ql <<- numeric(); names <<- character(); ncol <<- 6; }, setup = function(){ if (nrow(data) == 0 && ncol(data) == 0){ print('The data file does not seem to be in a valid format: no bus found$') } n <<- nrow(data); a <<- 1:n; v <<- a + n; # setup internal bus number for second indexing of bus int[data[, 1]] <<- a; .GlobalEnv$DAE$m <- 2 * n; .GlobalEnv$DAE$y <- rep(0, .GlobalEnv$DAE$m); .GlobalEnv$DAE$g <- rep(0, .GlobalEnv$DAE$m); # .GlobalEnv$DAE$Gy <- Matrix(0, nrow = .GlobalEnv$DAE$m, ncol = .GlobalEnv$DAE$m, sparse = TRUE); .GlobalEnv$DAE$Gy <- matrix(0, nrow = .GlobalEnv$DAE$m, ncol = .GlobalEnv$DAE$m); if (ncol(data) >= 4){ # check voltage magnitudes if (sum(data[, 3] < 0.5) > 0){ warning('some initial guess voltage magnitudes are too low.'); } if (sum(data[, 3] > 1.5) > 0){ warning('some initial guess voltage magnitudes are too high.'); } .GlobalEnv$DAE$y[v] <- data[, 3]; # check voltage phases if (sum(data[, 4] < -1.5708) > 0){ warning('some initial guess voltage phases are too low.'); } if (sum(data[, 4] > 1.5708) > 0){ warning('some initial guess voltage phases are too high.'); } .GlobalEnv$DAE$y[a] <- data[, 4]; } else{ .GlobalEnv$DAE$y[a] <- rep(0, n); .GlobalEnv$DAE$y[v] <- rep(1, n); } Pl <<- rep(0, n); Ql <<- rep(0, n); Pg <<- rep(0, n); Qg <<- rep(0, n); }, getbus = function(idx){ uTemp <- int[round(idx)]; vTemp <- uTemp + n; return(list(uTemp, vTemp)); }, getzeros = function(){ uTemp <- rep(0, n); return(uTemp); }, getint = function(idx){ uTemp <- int[round(idx)]; return(uTemp); }, test = function(){ print(environment()) print(parent.env(environment())) print(parent.env(parent.env(environment()))) print(parent.env(parent.env(parent.env(environment())))) print(parent.env(parent.env(parent.env(parent.env(environment()))))) .GlobalEnv$DAE$m <- 1000; .GlobalEnv$DAE$n <- .GlobalEnv$DAE$m; print(.GlobalEnv$DAE$n) } ))
dat <- sp500ret$sp500RET ts.plot(dt) acf(dat) # doesnt tell you to look at 2nd order acf(dat^2) McLeod.Li.test(y=dat) # want to reject the null hypothesis McLeod.Li.test(y=mod$residuals) # fGarch uses ljung box # https://quant.stackexchange.com/questions/11019/garch-model-and-prediction
/TimeSeries/Week8_Intervention_ARCH/McLeod_Li_test.R
no_license
jfnavarro21/MSCA_Python_R
R
false
false
291
r
dat <- sp500ret$sp500RET ts.plot(dt) acf(dat) # doesnt tell you to look at 2nd order acf(dat^2) McLeod.Li.test(y=dat) # want to reject the null hypothesis McLeod.Li.test(y=mod$residuals) # fGarch uses ljung box # https://quant.stackexchange.com/questions/11019/garch-model-and-prediction
kernelFun <- function(type=c('truncated','bartlett','daniell','QS','parzen'),z){ type <- match.arg(type) if (missing(type)) stop("Kernel type is missing. Type must be one of 'truncated','bartlett','daniell','QS','parzen'") if (type != "truncated" && type != "bartlett" && type != "daniell" && type != "QS" && type != "parzen") stop("Wrong type. Type must be one of 'truncated','bartlett','daniell','QS','parzen'") if (length(z)>1) stop("z must be of length 1") if (!is.numeric(z)) stop("'z' must be numeric") if (type=="truncated"){ k <- ifelse(abs(z)<=1,1,0) } else if (type=="bartlett"){ k <- ifelse(abs(z)<=1,1-abs(z),0) } else if (type=="daniell"){ if (z==0) stop("z cannot be zero") k <- sin(pi*z)/(pi*z) } else if (type=="QS"){ k <- (9/(5*pi^2*z^2))*(sin(sqrt(5/3)*pi*z)/(sqrt(5/3)*pi*z) - cos(sqrt(5/3)*pi*z)) } else if (type=="parzen"){ if (abs(z) <= (3/pi)){ k <- 1-6*((pi*z)/6)^2 + 6*abs((pi*z)/6)^3 } else if ((abs(z) >= (3/pi)) && (abs(z) <= (6/pi))){ k <- 2*(1-abs((pi*z)/6))^3 } else { k <- 0 } } return(k) }
/dCovTS/R/kernelFun.R
no_license
ingted/R-Examples
R
false
false
1,112
r
kernelFun <- function(type=c('truncated','bartlett','daniell','QS','parzen'),z){ type <- match.arg(type) if (missing(type)) stop("Kernel type is missing. Type must be one of 'truncated','bartlett','daniell','QS','parzen'") if (type != "truncated" && type != "bartlett" && type != "daniell" && type != "QS" && type != "parzen") stop("Wrong type. Type must be one of 'truncated','bartlett','daniell','QS','parzen'") if (length(z)>1) stop("z must be of length 1") if (!is.numeric(z)) stop("'z' must be numeric") if (type=="truncated"){ k <- ifelse(abs(z)<=1,1,0) } else if (type=="bartlett"){ k <- ifelse(abs(z)<=1,1-abs(z),0) } else if (type=="daniell"){ if (z==0) stop("z cannot be zero") k <- sin(pi*z)/(pi*z) } else if (type=="QS"){ k <- (9/(5*pi^2*z^2))*(sin(sqrt(5/3)*pi*z)/(sqrt(5/3)*pi*z) - cos(sqrt(5/3)*pi*z)) } else if (type=="parzen"){ if (abs(z) <= (3/pi)){ k <- 1-6*((pi*z)/6)^2 + 6*abs((pi*z)/6)^3 } else if ((abs(z) >= (3/pi)) && (abs(z) <= (6/pi))){ k <- 2*(1-abs((pi*z)/6))^3 } else { k <- 0 } } return(k) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/GraphFunctions.R \name{isConnected.adjMatrixGraph} \alias{isConnected.adjMatrixGraph} \title{A Graph Function} \usage{ \method{isConnected}{adjMatrixGraph}(graph) } \arguments{ \item{graph}{the graph obj} } \value{ a list containing the graph and whether the graph is connected } \description{ This functions checks if the graph is connected. }
/man/isConnected.adjMatrixGraph.Rd
no_license
TheBell/Graph
R
false
true
440
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/GraphFunctions.R \name{isConnected.adjMatrixGraph} \alias{isConnected.adjMatrixGraph} \title{A Graph Function} \usage{ \method{isConnected}{adjMatrixGraph}(graph) } \arguments{ \item{graph}{the graph obj} } \value{ a list containing the graph and whether the graph is connected } \description{ This functions checks if the graph is connected. }
source('simulation/sim_model.R') #install.packages(c("MFPCA","funData")) #install.packages("funData") source('nafpca.R') source('../../classification.R') library(MFPCA);library(funData) library(dplyr) library(ggplot2) scaling <- function(x,k) { #x = abs(x) out = (x - min(x)) / (max(x) - min(x)) / k return(out) } ################################################################## # Model I-1 : 1-d functional data - nonlinear relation in clustering ################################################################## n=200; nt=20 set.seed(1) dat = sim.model.11(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y # Original Data plot(tt,x[1,], type='l', ylim=c(-5,5), xlab="t", ylab="X(t)", main = "Model I", col=y+1) for(i in 1:n)lines(tt,x[i,], col=(y[i]+1)) # function estimation # 1. fda-based # bspline: most natural coef.bspline = get.fd(t(x),tt ,basisname='bspline') fd.bsp = fd(coef.bspline$coef, coef.bspline$basis) plot(fd.bsp, col=y+1) evals = t(eval.fd(tt,fd.bsp)) sum((evals - x)^2) / n /nt # fourier: tend to get x[0] = 0 , x[1] =0 coef.fourier = get.fd(t(x),tt ,basisname='fourier', nbasis=53) fd.fourier=fd(coef.fourier$coef, coef.fourier$basis) plot(fd.fourier, col=y+1) evals = t(eval.fd(tt,fd.fourier)) sum((evals - x)^2) / n /nt # 2. rkhs-based # gaussian: natural coef.gauss = get.fd.rkhs(x, tt, kern="gauss") evals = coef.gauss$coef %*% coef.gauss$kt plot(tt, evals[1,], col=y[1]+1, type='l', ylim=c(min(evals),max(evals))) for(j in 1:n){ lines(tt, evals[j,], col=y[j]+1) } sum((evals - x)^2) / n /nt # brownian: natural --- the best in this situation coef.brown = get.fd.rkhs(x, tt, kern="brown") evals = coef.brown$coef %*% coef.brown$kt plot(tt, evals[1,], col=y[1]+1, type='l', ylim=c(min(evals),max(evals))) for(j in 1:n){ lines(tt, evals[j,], col=y[j]+1) } sum((evals - x)^2) / n /nt # Nonlinear FPCA tmp=nafpca(x,tt, shx=11, nbasis=21,gamma.tune = TRUE, basisname='bspline') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='fourier') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=30, basisname='gauss') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='brown') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='bspline', kernel='poly', c=.1,d=2) tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='fourier', kernel='poly', c=.5,d=2) tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='gauss', kernel='poly', c=.5,d=2) tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='brown', kernel='poly', c=.5,d=2) tmp$eval gk = Gn(tmp$eval, n) plot(gk) which.max(gk) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") tmp$dim pairs(pred[,1:4],col=y+1) # 2ndRKHS: gauss plot(tmp$cv.shx) max(tmp$cv.shx) tmp$shx # 2ndRKHS: poly plot(tmp$cv.cd[-(139:140)]) max(tmp$cv.cd) tmp$c;tmp$d ########################## # Classification ########################## set.seed(0) train = sample(1:n, 100) c.methods=c("lda", "qda", "svm") d = tmp$dim d=1 imethod=3 pred.class = pred #pred.class = fpc.pred out = classify(x=pred.class[train,1:d], y=y, x.test=pred.class[-train,1:d], method=c.methods[imethod]) mean(y[-train] != out) # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred pred.class = fpc.pred out = classify(x=pred.class[train,1:d], y=y, x.test=pred.class[-train,1:d], method=c.methods[imethod]) mean(y[-train] != out) # Linear FPCA (my code) fpc = fpca(tmp$ftn) fpc.pred = fpc$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear/FPCA") ##################### # Visualization ##################### out=data.frame(PC1=pred[,1], PC2 = pred[,2], Y=as.factor(y)) pdf('nfpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('NAFPC')) dev.off() # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred out=data.frame(PC1=fpc.pred[,1], PC2 = fpc.pred[,2], Y=as.factor(y)) pdf('fpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('FPC')) dev.off() # curves - visualization of PC Scores curve_df <- data.frame(id=1, time=tt, x = x[1,], nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x = x[i,], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) require(ggplot2) p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=y)) pp <- p + geom_line() + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('Model I-1'), y='X(t)') pdf('mi_description.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=time, y=x,group=id)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Model I (Original)'), y= 'X(t)') #pdf('m1.pdf') pp #dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') # pdf('nfpc1.pdf') pp # dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd NAFPC'), y= 'X(t)') # pdf('nfpc2.pdf') pp # dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('1st FPC'), y= 'X(t)') pdf('fpc1.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd FPC'), y= 'X(t)') pdf('fpc2.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), 0)) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 NAFPC')) pdf('nfpc123.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 FPC')) pdf('fpc123.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=fpc1)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('1st (linear) FPC')) pp p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=fpc2)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd (linear) FPC')) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1), scaling(fpc2), scaling(fpc3))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp ####################################################### # Model I-2 true function: linear -- just sum of a few eigenfunctions for each group ####################################################### set.seed(0) nt=20 n=200 nbasis=21 dat = sim.model.12(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y # Original Data plot(tt,x[1,], type='l', ylim=c(-5,5), xlab="t", ylab="X(t)", main = "Model I", col=y) for(i in 1:n)lines(tt,x[i,], col=(y[i])) # Nonlinear FPCA nafpca.m2=nafpca(x,tt, basisname="bspline", ex=0,nbasis=nbasis, gamma.tune=TRUE,ncv1=50,ncv2=50) # shx works nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='bspline') nafpca.m2=nafpca(x,tt, nbasis=30,gamma.tune = TRUE, ncv1=30,ncv2=30, basisname='fourier') nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=30, basisname='gauss') nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='brown') nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='bspline', kernel='poly', c=.1,d=2) nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='fourier', kernel='poly', c=.5,d=2) nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='gauss', kernel='poly', c=.5,d=2) nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='brown', kernel='poly', c=.5,d=2) pred=nafpca.m2$pred pairs(pred[,1:4], col=y) vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ncv2=length(nafpca.m2$cv.shx) shx.grid = c(exp(seq(log(10^(-10)),log(10^(2)),len=ncv2))) plot(shx.grid, nafpca.m2$cv.shx) plot(Gn(nafpca.m2$eval,n)) which.max(Gn(nafpca.m2$eval,n)) cumsum(nafpca.m2$eval)/sum(nafpca.m2$eval) nafpca.m2$shx nafpca.m2$d nafpca.m2$cv.cd # Linear FPCA (my code) x.ftn = get.fd(xraw=t(x),tt=tt,basisname='bspline',nbasis=nbasis,ncv=10) fpc = fpca(x.ftn) fpc.pred = fpc$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear/FPCA") ##################### # Visualization ##################### #y=y-1 out=data.frame(PC1=pred[,1], PC2 = pred[,2], Y=as.factor(y)) pdf('mi2_nfpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("1"="black", "2"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('NAFPCA')) dev.off() # Linear FPCA out=data.frame(PC1=fpc.pred[,1], PC2 = fpc.pred[,2], Y=as.factor(y)) pdf('mi2_fpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("1"="black", "2"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('FPC')) dev.off() # curves - visualization of PC Scores curve_df <- data.frame(id=1, time=tt, x = x[1,], nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x = x[i,], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } require(ggplot2) curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=y)) pp <- p + geom_line() + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('Model I-2 with Y'), y='X(t)') pdf('mi2_description.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=time, y=x,group=id)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Model I (Original)'), y= 'X(t)') #pdf('mi2.pdf') pp #dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pdf('nfpc1.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd NAFPC'), y= 'X(t)') pdf('nfpc2.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('1st FPC'), y= 'X(t)') pdf('fpc1.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd FPC'), y= 'X(t)') pdf('fpc2.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) # hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), 0)) # hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 NAFPC')) pdf('nfpc123.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 FPC')) pdf('fpc123.pdf') pp dev.off() ###################### # Model II-1 (unbalanced) ###################### set.seed(1) n=200 nt=20 dat = sim.model.21(n=n, nt=nt, balanced = FALSE) x = dat$x; tt = dat$tt; y = dat$y i=which(y==0)[1] plot(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==0)[1:10]){ points(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==1)[1:10]){ points(x[[1]][[j]], x[[2]][[j]], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=21,unbalanced=TRUE, ncv1=10, ncv2=10) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plot(tmp$cv.shx) tmp$shx # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") # Linear FPCA (MFPCA/ PACE) out = convert.fd(fd=x,tt=tt, p=2,n=n) mfpc = MFPCA(out, M = 5, uniExpansions = list(list(type = "splines1D", k = 10), list(type = "splines1D", k = 10))) fpc.pred = mfpc$scores plotpred(fpc.pred, vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear/PACE") curve_df <- data.frame(id=1, time=tt, x1 = x[[1]][[1]], x2=x[[2]][[1]],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[[1]][[i]], x2=x[[2]][[i]], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) require(ggplot2) p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=y)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=fpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp ###################### # Model II-1 (balanced) ###################### n=100 nt=10 dat = sim.model.21(n=n, nt=nt, balanced = TRUE) x = dat$x; tt = dat$tt; y = dat$y y i=which(y==0)[1] plot(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==0)[1:10]){ points(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==1)[1:10]){ points(x[j,,1], x[j,,2], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='bspline') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='fourier') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='brown') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='gauss') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=1, basisname='bspline') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=3, basisname='fourier') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=3, basisname='brown') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=3, basisname='gauss') pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") #plot(tmp$cv.shx) max(tmp$cv.shx) gk = Gn(tmp$eval, n) #plot(gk) which.max(gk) plot(tmp$cv.cd) max(tmp$cv.cd) # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") # Linear FPCA (MFPCA/ PACE) # out = convert.fd(fd=x,tt=tt, p=2,n=n) # mfpc = MFPCA(out, M = 5, uniExpansions = list(list(type = "splines1D", k = 10), # list(type = "splines1D", k = 10))) # fpc.pred = mfpc$scores # # plotpred(fpc.pred, vec=vec,ind.inf=y, # xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), # main="Linear/PACE") curve_df <- data.frame(id=1, time=tt, x1 = x[[1]][[1]], x2=x[[2]][[1]],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[[1]][[i]], x2=x[[2]][[i]], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) require(ggplot2) p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=y)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=fpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp ###################### # Model II-2 (unbalanced) ###################### n=200 nt=20 set.seed(0) dat = sim.model.22(n=n, nt=nt, p=2, balanced=FALSE, m1=1, m2=2, r1=1, r2=0.7, sd1=.4, sd2=.2) x = dat$x; tt = dat$tt; y = dat$y i=which(y==0)[1] plot(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==0)[1:10]){ points(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==1)[1:10]){ points(x[[1]][[j]], x[[2]][[j]], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=8,unbalanced=TRUE,ncv1=20, ncv2=20, basisname='bspline', gamma.tune=TRUE,) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plot(tmp$cv.shx) # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") # Linear FPCA (MFPCA/ PACE) # out = convert.fd(fd=x,tt=tt, p=2,n=n) # mfpc = MFPCA(out, M = 5, uniExpansions = list(list(type = "splines1D", k = 10), # list(type = "splines1D", k = 10))) # fpc.pred = mfpc$scores # # plotpred(fpc.pred, vec=vec,ind.inf=y, # xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), # main="Linear/PACE") curve_df <- data.frame(id=1, time=tt, x1 = x[[1]][[1]], x2=x[[2]][[1]],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[[1]][[i]], x2=x[[2]][[i]], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) curve_df$ry = rgb(scaling(as.numeric(curve_df$y),1),0,0) require(ggplot2) p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=y)) pp <- p + geom_point(aes(colour=curve_df$y)) + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with Y'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=x1, y=x2,group=id)) pp <- p + geom_point() + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II (Original)'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2_original.pdf') pp dev.off() out = data.frame(PC1=pred[,1], PC2=pred[,2], Y=as.factor(y)) p <- ggplot(out, aes(x=PC1, y=PC2, colour=Y)) pp <- p + geom_point(aes(colour=Y)) + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('NAFPC')) pdf('m2nfpc2d.pdf') pp dev.off() out = data.frame(PC1=fpc.pred[,1], PC2=fpc.pred[,2], Y=as.factor(y)) p <- ggplot(out, aes(x=PC1, y=PC2, colour=Y)) pp <- p + geom_point(aes(colour=Y)) + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('FPC')) pdf('m2fpc2d.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc1)) pp <- p + geom_point(aes(colour=nfpc1)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2nfpc1.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=fpc1)) pp <- p + geom_point(aes(colour=fpc1)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with FPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2fpc1.pdf') pp dev.off() pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1),0,0)) p <- ggplot(hex.df, aes(x=x1, y=x2,group=id,colour=hex)) pp <- p + geom_point(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 linear FPC')) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0, 0)) p <- ggplot(hex.df, aes(x=x1, y=x2,group=id,colour=hex)) pp <- p + geom_point(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 linear FPC')) pp ############################################# # Model I-3 : classification ####################################################### set.seed(0) nt=20 n=200 nbasis=21 dat = sim.model.31(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y # Original Data plot(tt,x[1,], type='l', ylim=c(min(x),max(x)), xlab="t", ylab="X(t)", main = "Model I", col=y) for(i in 1:n)lines(tt,x[i,], col=(y[i])) # Nonlinear FPCA tmp=nafpca(x,tt, basisname="bspline",nbasis=nbasis, gamma.tune=TRUE,ncv1=20,ncv2=20) # shx works pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") tmp$dim aa=fpca(nafpca.m2$ftn) pairs(pred[,1:10],col=y) pairs(aa$pred[,1:10],col=y) ###################### # Model II-3 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.23(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt, n.point=100) i=which(y==1)[1] plot(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==1)[1:10]){ points(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==2)[1:10]){ points(x[j,,1], x[j,,2], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=nbasis, ncv1= 30, ncv2=30) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-2 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.32(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt) # Nonlinear FPCA tmp=nafpca(x,tt, p=1, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-3 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.33(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt) # Nonlinear FPCA tmp=nafpca(x,tt, p=1, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred vec=c(3,4) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:6], col=y) #pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-4 ###################### set.seed(0) n=200 nt=20 nbasis=31 dat = sim.model.34(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt) # Nonlinear FPCA tmp=nafpca(x,tt, p=1, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:6], col=y) #pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-5 ###################### set.seed(0) n=200 nt=20 nbasis=31 dat = sim.model.35(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y y=as.factor(y) # Nonlinear FPCA tmp=nafpca(x,tt, p=3, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred summary(glm(y~pred[,1:5], family = binomial(link="logit"))) summary(glm(y~fpc.pred[,1:5],family = binomial(link="logit"))) vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") i=1 curve_df <- data.frame(id=1, time=tt, x1 = x[1,,1], x2=x[1,,2], x3=x[1,,3],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[i,,1], x2=x[i,,2], x3=x[i,,3],nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } p <- ggplot(curve_df, aes(x=nfpc1, y=nfpc2,group=id,colour=y)) pp <- p + geom_point(aes(colour=y)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp p <- ggplot(curve_df, aes(x=fpc1, y=fpc2,group=id,colour=y)) pp <- p + geom_point(aes(colour=y)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc3,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st FPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1),scaling(nfpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1),scaling(fpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp ###################### # Model III-6 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.36(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y y=as.factor(y) # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=nbasis, ncv1= 10, ncv2=10) pred=tmp$pred plot(x[6,,1]) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred summary(glm(y~pred[,1:5], family = binomial(link="logit"))) summary(glm(y~fpc.pred[,1:5],family = binomial(link="logit"))) vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") i=1 curve_df <- data.frame(id=1, time=tt, x1 = x[1,,1], x2=x[1,,2], nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[i,,1], x2=x[i,,2],nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc3)) pp <- p + geom_point(aes(colour=nfpc3)) + theme_bw() +#scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp p <- ggplot(curve_df, aes(x=fpc1, y=fpc2,group=id,colour=y)) pp <- p + geom_point(aes(colour=y)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc3,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st FPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1),scaling(nfpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1),scaling(fpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp
/nafpca/simulation/sim_plots.R
no_license
CodeJSong/Functional-Dimension-Reduction
R
false
false
37,420
r
source('simulation/sim_model.R') #install.packages(c("MFPCA","funData")) #install.packages("funData") source('nafpca.R') source('../../classification.R') library(MFPCA);library(funData) library(dplyr) library(ggplot2) scaling <- function(x,k) { #x = abs(x) out = (x - min(x)) / (max(x) - min(x)) / k return(out) } ################################################################## # Model I-1 : 1-d functional data - nonlinear relation in clustering ################################################################## n=200; nt=20 set.seed(1) dat = sim.model.11(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y # Original Data plot(tt,x[1,], type='l', ylim=c(-5,5), xlab="t", ylab="X(t)", main = "Model I", col=y+1) for(i in 1:n)lines(tt,x[i,], col=(y[i]+1)) # function estimation # 1. fda-based # bspline: most natural coef.bspline = get.fd(t(x),tt ,basisname='bspline') fd.bsp = fd(coef.bspline$coef, coef.bspline$basis) plot(fd.bsp, col=y+1) evals = t(eval.fd(tt,fd.bsp)) sum((evals - x)^2) / n /nt # fourier: tend to get x[0] = 0 , x[1] =0 coef.fourier = get.fd(t(x),tt ,basisname='fourier', nbasis=53) fd.fourier=fd(coef.fourier$coef, coef.fourier$basis) plot(fd.fourier, col=y+1) evals = t(eval.fd(tt,fd.fourier)) sum((evals - x)^2) / n /nt # 2. rkhs-based # gaussian: natural coef.gauss = get.fd.rkhs(x, tt, kern="gauss") evals = coef.gauss$coef %*% coef.gauss$kt plot(tt, evals[1,], col=y[1]+1, type='l', ylim=c(min(evals),max(evals))) for(j in 1:n){ lines(tt, evals[j,], col=y[j]+1) } sum((evals - x)^2) / n /nt # brownian: natural --- the best in this situation coef.brown = get.fd.rkhs(x, tt, kern="brown") evals = coef.brown$coef %*% coef.brown$kt plot(tt, evals[1,], col=y[1]+1, type='l', ylim=c(min(evals),max(evals))) for(j in 1:n){ lines(tt, evals[j,], col=y[j]+1) } sum((evals - x)^2) / n /nt # Nonlinear FPCA tmp=nafpca(x,tt, shx=11, nbasis=21,gamma.tune = TRUE, basisname='bspline') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='fourier') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=30, basisname='gauss') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='brown') tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='bspline', kernel='poly', c=.1,d=2) tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='fourier', kernel='poly', c=.5,d=2) tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='gauss', kernel='poly', c=.5,d=2) tmp=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='brown', kernel='poly', c=.5,d=2) tmp$eval gk = Gn(tmp$eval, n) plot(gk) which.max(gk) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") tmp$dim pairs(pred[,1:4],col=y+1) # 2ndRKHS: gauss plot(tmp$cv.shx) max(tmp$cv.shx) tmp$shx # 2ndRKHS: poly plot(tmp$cv.cd[-(139:140)]) max(tmp$cv.cd) tmp$c;tmp$d ########################## # Classification ########################## set.seed(0) train = sample(1:n, 100) c.methods=c("lda", "qda", "svm") d = tmp$dim d=1 imethod=3 pred.class = pred #pred.class = fpc.pred out = classify(x=pred.class[train,1:d], y=y, x.test=pred.class[-train,1:d], method=c.methods[imethod]) mean(y[-train] != out) # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred pred.class = fpc.pred out = classify(x=pred.class[train,1:d], y=y, x.test=pred.class[-train,1:d], method=c.methods[imethod]) mean(y[-train] != out) # Linear FPCA (my code) fpc = fpca(tmp$ftn) fpc.pred = fpc$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear/FPCA") ##################### # Visualization ##################### out=data.frame(PC1=pred[,1], PC2 = pred[,2], Y=as.factor(y)) pdf('nfpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('NAFPC')) dev.off() # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred out=data.frame(PC1=fpc.pred[,1], PC2 = fpc.pred[,2], Y=as.factor(y)) pdf('fpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('FPC')) dev.off() # curves - visualization of PC Scores curve_df <- data.frame(id=1, time=tt, x = x[1,], nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x = x[i,], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) require(ggplot2) p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=y)) pp <- p + geom_line() + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('Model I-1'), y='X(t)') pdf('mi_description.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=time, y=x,group=id)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Model I (Original)'), y= 'X(t)') #pdf('m1.pdf') pp #dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') # pdf('nfpc1.pdf') pp # dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd NAFPC'), y= 'X(t)') # pdf('nfpc2.pdf') pp # dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('1st FPC'), y= 'X(t)') pdf('fpc1.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd FPC'), y= 'X(t)') pdf('fpc2.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), 0)) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 NAFPC')) pdf('nfpc123.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 FPC')) pdf('fpc123.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=fpc1)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('1st (linear) FPC')) pp p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=fpc2)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd (linear) FPC')) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1), scaling(fpc2), scaling(fpc3))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp ####################################################### # Model I-2 true function: linear -- just sum of a few eigenfunctions for each group ####################################################### set.seed(0) nt=20 n=200 nbasis=21 dat = sim.model.12(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y # Original Data plot(tt,x[1,], type='l', ylim=c(-5,5), xlab="t", ylab="X(t)", main = "Model I", col=y) for(i in 1:n)lines(tt,x[i,], col=(y[i])) # Nonlinear FPCA nafpca.m2=nafpca(x,tt, basisname="bspline", ex=0,nbasis=nbasis, gamma.tune=TRUE,ncv1=50,ncv2=50) # shx works nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='bspline') nafpca.m2=nafpca(x,tt, nbasis=30,gamma.tune = TRUE, ncv1=30,ncv2=30, basisname='fourier') nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=30, basisname='gauss') nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='brown') nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE,ncv1=30,ncv2=20, basisname='bspline', kernel='poly', c=.1,d=2) nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='fourier', kernel='poly', c=.5,d=2) nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='gauss', kernel='poly', c=.5,d=2) nafpca.m2=nafpca(x,tt, shx=11, nbasis=30,gamma.tune = TRUE, basisname='brown', kernel='poly', c=.5,d=2) pred=nafpca.m2$pred pairs(pred[,1:4], col=y) vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ncv2=length(nafpca.m2$cv.shx) shx.grid = c(exp(seq(log(10^(-10)),log(10^(2)),len=ncv2))) plot(shx.grid, nafpca.m2$cv.shx) plot(Gn(nafpca.m2$eval,n)) which.max(Gn(nafpca.m2$eval,n)) cumsum(nafpca.m2$eval)/sum(nafpca.m2$eval) nafpca.m2$shx nafpca.m2$d nafpca.m2$cv.cd # Linear FPCA (my code) x.ftn = get.fd(xraw=t(x),tt=tt,basisname='bspline',nbasis=nbasis,ncv=10) fpc = fpca(x.ftn) fpc.pred = fpc$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear/FPCA") ##################### # Visualization ##################### #y=y-1 out=data.frame(PC1=pred[,1], PC2 = pred[,2], Y=as.factor(y)) pdf('mi2_nfpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("1"="black", "2"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('NAFPCA')) dev.off() # Linear FPCA out=data.frame(PC1=fpc.pred[,1], PC2 = fpc.pred[,2], Y=as.factor(y)) pdf('mi2_fpc2d.pdf') ggplot(out,aes(x=PC1,y=PC2, colour=Y)) + geom_point()+theme_bw() + scale_colour_manual(name="Y", values = c("1"="black", "2"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('FPC')) dev.off() # curves - visualization of PC Scores curve_df <- data.frame(id=1, time=tt, x = x[1,], nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x = x[i,], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } require(ggplot2) curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) p <- ggplot(curve_df, aes(x=time, y=x,group=id,colour=y)) pp <- p + geom_line() + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=20), legend.position="right")+ theme(plot.title = element_text(hjust = 0.5,size=20))+ labs(title = paste0('Model I-2 with Y'), y='X(t)') pdf('mi2_description.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=time, y=x,group=id)) pp <- p + geom_line() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Model I (Original)'), y= 'X(t)') #pdf('mi2.pdf') pp #dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pdf('nfpc1.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd NAFPC'), y= 'X(t)') pdf('nfpc2.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('1st FPC'), y= 'X(t)') pdf('fpc1.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc2,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('2nd FPC'), y= 'X(t)') pdf('fpc2.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) # hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), 0)) # hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc2,1), 0,0)) hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1), scaling(nfpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 NAFPC')) pdf('nfpc123.pdf') pp dev.off() hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1), scaling(fpc3,1))) p <- ggplot(hex.df, aes(x=time, y=x,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 FPC')) pdf('fpc123.pdf') pp dev.off() ###################### # Model II-1 (unbalanced) ###################### set.seed(1) n=200 nt=20 dat = sim.model.21(n=n, nt=nt, balanced = FALSE) x = dat$x; tt = dat$tt; y = dat$y i=which(y==0)[1] plot(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==0)[1:10]){ points(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==1)[1:10]){ points(x[[1]][[j]], x[[2]][[j]], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=21,unbalanced=TRUE, ncv1=10, ncv2=10) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plot(tmp$cv.shx) tmp$shx # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") # Linear FPCA (MFPCA/ PACE) out = convert.fd(fd=x,tt=tt, p=2,n=n) mfpc = MFPCA(out, M = 5, uniExpansions = list(list(type = "splines1D", k = 10), list(type = "splines1D", k = 10))) fpc.pred = mfpc$scores plotpred(fpc.pred, vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear/PACE") curve_df <- data.frame(id=1, time=tt, x1 = x[[1]][[1]], x2=x[[2]][[1]],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[[1]][[i]], x2=x[[2]][[i]], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) require(ggplot2) p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=y)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=fpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp ###################### # Model II-1 (balanced) ###################### n=100 nt=10 dat = sim.model.21(n=n, nt=nt, balanced = TRUE) x = dat$x; tt = dat$tt; y = dat$y y i=which(y==0)[1] plot(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==0)[1:10]){ points(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==1)[1:10]){ points(x[j,,1], x[j,,2], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='bspline') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='fourier') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='brown') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, basisname='gauss') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=1, basisname='bspline') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=3, basisname='fourier') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=3, basisname='brown') tmp=nafpca(x,tt,nbasis=30,gamma.tune = TRUE, ncv2=100, kernel = 'poly', d=3, basisname='gauss') pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") #plot(tmp$cv.shx) max(tmp$cv.shx) gk = Gn(tmp$eval, n) #plot(gk) which.max(gk) plot(tmp$cv.cd) max(tmp$cv.cd) # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") # Linear FPCA (MFPCA/ PACE) # out = convert.fd(fd=x,tt=tt, p=2,n=n) # mfpc = MFPCA(out, M = 5, uniExpansions = list(list(type = "splines1D", k = 10), # list(type = "splines1D", k = 10))) # fpc.pred = mfpc$scores # # plotpred(fpc.pred, vec=vec,ind.inf=y, # xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), # main="Linear/PACE") curve_df <- data.frame(id=1, time=tt, x1 = x[[1]][[1]], x2=x[[2]][[1]],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[[1]][[i]], x2=x[[2]][[i]], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) require(ggplot2) p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=y)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=fpc1)) pp <- p + geom_point() + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('Sparsely observed')) pp ###################### # Model II-2 (unbalanced) ###################### n=200 nt=20 set.seed(0) dat = sim.model.22(n=n, nt=nt, p=2, balanced=FALSE, m1=1, m2=2, r1=1, r2=0.7, sd1=.4, sd2=.2) x = dat$x; tt = dat$tt; y = dat$y i=which(y==0)[1] plot(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==0)[1:10]){ points(x[[1]][[i]], x[[2]][[i]], xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==1)[1:10]){ points(x[[1]][[j]], x[[2]][[j]], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=8,unbalanced=TRUE,ncv1=20, ncv2=20, basisname='bspline', gamma.tune=TRUE,) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plot(tmp$cv.shx) # Linear FPCA fpc = fpca(tmp$ftn) fpc.pred = fpc$pred plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") # Linear FPCA (MFPCA/ PACE) # out = convert.fd(fd=x,tt=tt, p=2,n=n) # mfpc = MFPCA(out, M = 5, uniExpansions = list(list(type = "splines1D", k = 10), # list(type = "splines1D", k = 10))) # fpc.pred = mfpc$scores # # plotpred(fpc.pred, vec=vec,ind.inf=y, # xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), # main="Linear/PACE") curve_df <- data.frame(id=1, time=tt, x1 = x[[1]][[1]], x2=x[[2]][[1]],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[[1]][[i]], x2=x[[2]][[i]], nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } curve_df$id <- factor(curve_df$id) curve_df$y <- factor(curve_df$y) curve_df$ry = rgb(scaling(as.numeric(curve_df$y),1),0,0) require(ggplot2) p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=y)) pp <- p + geom_point(aes(colour=curve_df$y)) + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with Y'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=x1, y=x2,group=id)) pp <- p + geom_point() + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II (Original)'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2_original.pdf') pp dev.off() out = data.frame(PC1=pred[,1], PC2=pred[,2], Y=as.factor(y)) p <- ggplot(out, aes(x=PC1, y=PC2, colour=Y)) pp <- p + geom_point(aes(colour=Y)) + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('NAFPC')) pdf('m2nfpc2d.pdf') pp dev.off() out = data.frame(PC1=fpc.pred[,1], PC2=fpc.pred[,2], Y=as.factor(y)) p <- ggplot(out, aes(x=PC1, y=PC2, colour=Y)) pp <- p + geom_point(aes(colour=Y)) + theme_bw() + scale_colour_manual(name="Y", values = c("0"="black", "1"="red"))+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('FPC')) pdf('m2fpc2d.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc1)) pp <- p + geom_point(aes(colour=nfpc1)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2nfpc1.pdf') pp dev.off() p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=fpc1)) pp <- p + geom_point(aes(colour=fpc1)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with FPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pdf('m2fpc1.pdf') pp dev.off() pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1),0,0)) p <- ggplot(hex.df, aes(x=x1, y=x2,group=id,colour=hex)) pp <- p + geom_point(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 linear FPC')) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0, 0)) p <- ggplot(hex.df, aes(x=x1, y=x2,group=id,colour=hex)) pp <- p + geom_point(colour=hex.df$hex) + theme_bw() + theme(legend.position="none") + theme(plot.title = element_text(hjust = 0.5,size=22))+ labs(title = paste0('First 3 linear FPC')) pp ############################################# # Model I-3 : classification ####################################################### set.seed(0) nt=20 n=200 nbasis=21 dat = sim.model.31(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y # Original Data plot(tt,x[1,], type='l', ylim=c(min(x),max(x)), xlab="t", ylab="X(t)", main = "Model I", col=y) for(i in 1:n)lines(tt,x[i,], col=(y[i])) # Nonlinear FPCA tmp=nafpca(x,tt, basisname="bspline",nbasis=nbasis, gamma.tune=TRUE,ncv1=20,ncv2=20) # shx works pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") tmp$dim aa=fpca(nafpca.m2$ftn) pairs(pred[,1:10],col=y) pairs(aa$pred[,1:10],col=y) ###################### # Model II-3 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.23(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt, n.point=100) i=which(y==1)[1] plot(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) for(i in which(y==1)[1:10]){ points(x[i,,1], x[i,,2], col=1, xlim=c(-5,5),ylim=c(-5,5), pch=16) } for(j in which(y==2)[1:10]){ points(x[j,,1], x[j,,2], col=2, pch=16) } # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=nbasis, ncv1= 30, ncv2=30) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-2 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.32(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt) # Nonlinear FPCA tmp=nafpca(x,tt, p=1, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-3 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.33(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt) # Nonlinear FPCA tmp=nafpca(x,tt, p=1, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred vec=c(3,4) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:6], col=y) #pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-4 ###################### set.seed(0) n=200 nt=20 nbasis=31 dat = sim.model.34(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y fdplot(x,y,tt) # Nonlinear FPCA tmp=nafpca(x,tt, p=1, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") pairs(pred[,1:6], col=y) #pairs(pred[,1:4], col=y) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred vec=c(1,2) plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") ###################### # Model III-5 ###################### set.seed(0) n=200 nt=20 nbasis=31 dat = sim.model.35(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y y=as.factor(y) # Nonlinear FPCA tmp=nafpca(x,tt, p=3, nbasis=nbasis, ncv1= 50, ncv2=50) pred=tmp$pred fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred summary(glm(y~pred[,1:5], family = binomial(link="logit"))) summary(glm(y~fpc.pred[,1:5],family = binomial(link="logit"))) vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") i=1 curve_df <- data.frame(id=1, time=tt, x1 = x[1,,1], x2=x[1,,2], x3=x[1,,3],nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[i,,1], x2=x[i,,2], x3=x[i,,3],nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } p <- ggplot(curve_df, aes(x=nfpc1, y=nfpc2,group=id,colour=y)) pp <- p + geom_point(aes(colour=y)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp p <- ggplot(curve_df, aes(x=fpc1, y=fpc2,group=id,colour=y)) pp <- p + geom_point(aes(colour=y)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc3,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st FPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1),scaling(nfpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1),scaling(fpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp ###################### # Model III-6 ###################### set.seed(0) n=200 nt=20 nbasis=21 dat = sim.model.36(n=n, nt=nt) x = dat$x; tt = dat$tt; y = dat$y y=as.factor(y) # Nonlinear FPCA tmp=nafpca(x,tt, p=2, nbasis=nbasis, ncv1= 10, ncv2=10) pred=tmp$pred plot(x[6,,1]) fpca.out = fpca(tmp$ftn) fpc.pred = fpca.out$pred summary(glm(y~pred[,1:5], family = binomial(link="logit"))) summary(glm(y~fpc.pred[,1:5],family = binomial(link="logit"))) vec=c(1,2) plotpred(pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Nonlinear") plotpred(fpc.pred,vec=vec,ind.inf=y, xlab=paste("PC ",vec[1]), ylab=paste("PC ",vec[2]), main="Linear") i=1 curve_df <- data.frame(id=1, time=tt, x1 = x[1,,1], x2=x[1,,2], nfpc1=pred[1,1], nfpc2=pred[1,2], nfpc3=pred[1,3], fpc1=fpc.pred[1,1], fpc2=fpc.pred[1,2], fpc3=fpc.pred[1,3], y=y[i]) for(i in 2:n){ curve_df <- rbind.data.frame(curve_df, data.frame(id=i, time=tt, x1 = x[i,,1], x2=x[i,,2],nfpc1=pred[i,1], nfpc2=pred[i,2], nfpc3=pred[i,3], fpc1=fpc.pred[i,1], fpc2=fpc.pred[i,2], fpc3=fpc.pred[i,3], y=y[i])) } p <- ggplot(curve_df, aes(x=x1, y=x2,group=id,colour=nfpc3)) pp <- p + geom_point(aes(colour=nfpc3)) + theme_bw() +#scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp p <- ggplot(curve_df, aes(x=fpc1, y=fpc2,group=id,colour=y)) pp <- p + geom_point(aes(colour=y)) + theme_bw() +scale_colour_gradient(low="black",high="red")+ theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="right")+ labs(title = paste0('Model II with NAFPC'), x = expression({X^{1}}(t)), y = expression({X^{2}}(t))) pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc3,1), 0,0)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st FPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(nfpc1,1), scaling(nfpc2,1),scaling(nfpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp hex.df <- curve_df %>% mutate(hex = rgb(scaling(fpc1,1), scaling(fpc2,1),scaling(fpc3,1),)) p <- ggplot(hex.df, aes(x=time, y=x3,group=id,colour=hex)) pp <- p + geom_line(colour=hex.df$hex) + theme_bw() + theme(plot.title = element_text(hjust = 0.5,size=22), legend.position="none") + labs(title = paste0('1st NAFPC'), y= 'X(t)') pp
require(readr) require(plyr) require(igraph) require(rgexf) # set working directory getwd() setwd("../query_results/merge_scripts/complete_merge/") # read node and edges into dataframe with the name expected by igraph nodes <- read.csv("time_slice_1536_complete_merge_budΓ©_and_era_correspondents.csv", fileEncoding="UTF-8") links <- read.csv("time_slice_1536_complete_merge_budΓ©_and_era_letters_corr_as_nodes.csv", fileEncoding="UTF-8")[ ,c('Source', 'Target')] setwd("../../") getwd() mutcorr <- read.csv("./intersection_overview/id_and_names_of_mut_corr_era_budΓ©.csv", fileEncoding="UTF-8") # add colour for all correspondents nodes$colour <- "#525252" # add colour column for mutual correspondents t nodes$colour <- ifelse(nodes$Id %in% mutcorr$correspondents_id, as.character("#C3161F"), nodes$colour) #assign specific colour for erasmus nodes$colour <- ifelse(nodes$Id == "17c580aa-3ba7-4851-8f26-9b3a0ebeadbf", as.character("#3C93AF"), nodes$colour) #assign specific colour for budΓ© nodes$colour <- ifelse(nodes$Id == "c0b89c75-45b8-4b04-bfd7-25bfe9ed040b", as.character("#D5AB5B"), nodes$colour) #assign edge weight links$weight <- 1 # create igraph object net <- graph_from_data_frame(d=links, vertices=nodes, directed=T) # conduct edge bundling (sum edge weights) net2 <- simplify(net, remove.multiple = TRUE, edge.attr.comb=list(weight="sum","ignore")) # calculate degree for all nodes degAll <- degree(net2, v = V(net2), mode = "all") # calculate weighted degree for all nodes weightDegAll <- strength(net2, vids = V(net2), mode = "all", loops = TRUE) # add new node and edge attributes based on the calculated properties, add net2 <- set.vertex.attribute(net2, "weightDegAll", index = V(net2), value = weightDegAll) net2 <- set.vertex.attribute(net2, "degree", index = V(net2), value = degAll) net2 <- set.vertex.attribute(net2, "colour", index = V(net2), value = nodes$colour) net2 <- set.edge.attribute(net2, "weight", index = E(net2), value = E(net2)$weight) #assign edge colour according to source node edge.start <- ends(net2, es=E(net2), names=F)[,1] edge.col <- V(net2)$colour[edge.start] # layout with FR l <- layout_with_fr(net2, weights=E(net2)$weight)*3.5 # plot graph plot(net2, layout=l*5, vertex.color=nodes$colour, vertex.size=2, vertex.label=V(net2)$Label, vertex.label.font=2, vertex.label.color="gray40", vertex.label.cex=.3, edge.arrow.size=.2, edge.width=E(net2)$weight*0.5, edge.color=edge.col, vertex.label.family="sans") ################# # calculate node coordinates nodes_coord <- as.data.frame(layout.fruchterman.reingold(net2, weights=E(net2)$weight)*50) nodes_coord <- cbind(nodes_coord, rep(0, times = nrow(nodes_coord))) # assign a colour for each node nodes_col <- V(net2)$colour # transform nodes into a data frame nodes_col_df <- as.data.frame(t(col2rgb(nodes_col, alpha = FALSE))) nodes_col_df <- cbind(nodes_col_df, alpha = rep(1, times = nrow(nodes_col_df))) # assign visual attributes to nodes (RGBA) nodes_att_viz <- list(color = nodes_col_df, position = nodes_coord) # assign a colour for each edge edges_col <- edge.col # Transform it into a data frame (we have to transpose it first) edges_col_df <- as.data.frame(t(col2rgb(edges_col, alpha = FALSE))) edges_col_df <- cbind(edges_col_df, alpha = rep(1, times = nrow(edges_col_df))) # assign visual attributes to edges (RGBA) edges_att_viz <- list(color = edges_col_df) # create data frames for gexf export nodes_df <- data.frame(ID = c(1:vcount(net2)), NAME = V(net2)$Label) edges_df <- as.data.frame(get.edges(net2, c(1:ecount(net2)))) #create a dataframe with node attributes nodes_att <- data.frame(Degree = V(net2)$degree, colour = as.character(nodes$colour), "Weighted Degree" = V(net2)$weightDegAll) setwd("../") getwd() setwd("./network_data/complete_merge_time_slices_gexf_created_by_r") # write gexf era_budΓ©_cmerge_1536 <- write.gexf(nodes = nodes_df, edges = edges_df, edgesWeight = E(net2)$weight, nodesAtt = nodes_att, nodesVizAtt = nodes_att_viz, edgesVizAtt = edges_att_viz, defaultedgetype = "directed", meta = list( creator="Christoph Kudella", description="A graph representing the intersection between Erasmus's and BudΓ©'s networks of correspondence in the year 1536"), output="era_budΓ©_cmerge_1536.gexf")
/intersections_budΓ©_erasmus/r_scripts/complete_merge_time_slices_gexf_created_by_r/create_gexf_complete_merge_budΓ©_era_1536.R
no_license
CKudella/corr_data
R
false
false
4,292
r
require(readr) require(plyr) require(igraph) require(rgexf) # set working directory getwd() setwd("../query_results/merge_scripts/complete_merge/") # read node and edges into dataframe with the name expected by igraph nodes <- read.csv("time_slice_1536_complete_merge_budΓ©_and_era_correspondents.csv", fileEncoding="UTF-8") links <- read.csv("time_slice_1536_complete_merge_budΓ©_and_era_letters_corr_as_nodes.csv", fileEncoding="UTF-8")[ ,c('Source', 'Target')] setwd("../../") getwd() mutcorr <- read.csv("./intersection_overview/id_and_names_of_mut_corr_era_budΓ©.csv", fileEncoding="UTF-8") # add colour for all correspondents nodes$colour <- "#525252" # add colour column for mutual correspondents t nodes$colour <- ifelse(nodes$Id %in% mutcorr$correspondents_id, as.character("#C3161F"), nodes$colour) #assign specific colour for erasmus nodes$colour <- ifelse(nodes$Id == "17c580aa-3ba7-4851-8f26-9b3a0ebeadbf", as.character("#3C93AF"), nodes$colour) #assign specific colour for budΓ© nodes$colour <- ifelse(nodes$Id == "c0b89c75-45b8-4b04-bfd7-25bfe9ed040b", as.character("#D5AB5B"), nodes$colour) #assign edge weight links$weight <- 1 # create igraph object net <- graph_from_data_frame(d=links, vertices=nodes, directed=T) # conduct edge bundling (sum edge weights) net2 <- simplify(net, remove.multiple = TRUE, edge.attr.comb=list(weight="sum","ignore")) # calculate degree for all nodes degAll <- degree(net2, v = V(net2), mode = "all") # calculate weighted degree for all nodes weightDegAll <- strength(net2, vids = V(net2), mode = "all", loops = TRUE) # add new node and edge attributes based on the calculated properties, add net2 <- set.vertex.attribute(net2, "weightDegAll", index = V(net2), value = weightDegAll) net2 <- set.vertex.attribute(net2, "degree", index = V(net2), value = degAll) net2 <- set.vertex.attribute(net2, "colour", index = V(net2), value = nodes$colour) net2 <- set.edge.attribute(net2, "weight", index = E(net2), value = E(net2)$weight) #assign edge colour according to source node edge.start <- ends(net2, es=E(net2), names=F)[,1] edge.col <- V(net2)$colour[edge.start] # layout with FR l <- layout_with_fr(net2, weights=E(net2)$weight)*3.5 # plot graph plot(net2, layout=l*5, vertex.color=nodes$colour, vertex.size=2, vertex.label=V(net2)$Label, vertex.label.font=2, vertex.label.color="gray40", vertex.label.cex=.3, edge.arrow.size=.2, edge.width=E(net2)$weight*0.5, edge.color=edge.col, vertex.label.family="sans") ################# # calculate node coordinates nodes_coord <- as.data.frame(layout.fruchterman.reingold(net2, weights=E(net2)$weight)*50) nodes_coord <- cbind(nodes_coord, rep(0, times = nrow(nodes_coord))) # assign a colour for each node nodes_col <- V(net2)$colour # transform nodes into a data frame nodes_col_df <- as.data.frame(t(col2rgb(nodes_col, alpha = FALSE))) nodes_col_df <- cbind(nodes_col_df, alpha = rep(1, times = nrow(nodes_col_df))) # assign visual attributes to nodes (RGBA) nodes_att_viz <- list(color = nodes_col_df, position = nodes_coord) # assign a colour for each edge edges_col <- edge.col # Transform it into a data frame (we have to transpose it first) edges_col_df <- as.data.frame(t(col2rgb(edges_col, alpha = FALSE))) edges_col_df <- cbind(edges_col_df, alpha = rep(1, times = nrow(edges_col_df))) # assign visual attributes to edges (RGBA) edges_att_viz <- list(color = edges_col_df) # create data frames for gexf export nodes_df <- data.frame(ID = c(1:vcount(net2)), NAME = V(net2)$Label) edges_df <- as.data.frame(get.edges(net2, c(1:ecount(net2)))) #create a dataframe with node attributes nodes_att <- data.frame(Degree = V(net2)$degree, colour = as.character(nodes$colour), "Weighted Degree" = V(net2)$weightDegAll) setwd("../") getwd() setwd("./network_data/complete_merge_time_slices_gexf_created_by_r") # write gexf era_budΓ©_cmerge_1536 <- write.gexf(nodes = nodes_df, edges = edges_df, edgesWeight = E(net2)$weight, nodesAtt = nodes_att, nodesVizAtt = nodes_att_viz, edgesVizAtt = edges_att_viz, defaultedgetype = "directed", meta = list( creator="Christoph Kudella", description="A graph representing the intersection between Erasmus's and BudΓ©'s networks of correspondence in the year 1536"), output="era_budΓ©_cmerge_1536.gexf")
#' Spark ML -- Survival Regression #' #' Perform survival regression on a Spark DataFrame, using an Accelerated #' failure time (AFT) model with potentially right-censored data. #' #' @template roxlate-ml-x #' @template roxlate-ml-response #' @template roxlate-ml-features #' @template roxlate-ml-intercept #' @param censor The name of the vector that provides censoring information. #' This should be a numeric vector, with 0 marking uncensored data, and #' 1 marking right-censored data. #' @template roxlate-ml-max-iter #' @template roxlate-ml-dots #' #' @family Spark ML routines #' #' @export ml_survival_regression <- function(x, response, features, intercept = TRUE, censor = "censor", max.iter = 100L, ...) { df <- spark_dataframe(x) sc <- spark_connection(df) df <- ml_prepare_response_features_intercept(df, response, features, intercept) censor <- ensure_scalar_character(censor) max.iter <- ensure_scalar_integer(max.iter) only_model <- ensure_scalar_boolean(list(...)$only_model, default = FALSE) envir <- new.env(parent = emptyenv()) tdf <- ml_prepare_dataframe(df, features, response, envir = envir) envir$model <- "org.apache.spark.ml.regression.AFTSurvivalRegression" rf <- invoke_new(sc, envir$model) model <- rf %>% invoke("setMaxIter", max.iter) %>% invoke("setFeaturesCol", envir$features) %>% invoke("setLabelCol", envir$response) %>% invoke("setFitIntercept", as.logical(intercept)) %>% invoke("setCensorCol", censor) if (only_model) return(model) fit <- model %>% invoke("fit", tdf) coefficients <- fit %>% invoke("coefficients") %>% invoke("toArray") names(coefficients) <- features hasIntercept <- invoke(fit, "getFitIntercept") if (hasIntercept) { intercept <- invoke(fit, "intercept") coefficients <- c(coefficients, intercept) names(coefficients) <- c(features, "(Intercept)") } coefficients <- intercept_first(coefficients) scale <- invoke(fit, "scale") ml_model("survival_regression", fit, features = features, response = response, intercept = intercept, coefficients = coefficients, intercept = intercept, scale = scale, model.parameters = as.list(envir) ) } #' @export print.ml_model_survival_regression <- function(x, ...) { ml_model_print_call(x) }
/R/ml_survival_regression.R
permissive
irichgreen/sparklyr
R
false
false
2,528
r
#' Spark ML -- Survival Regression #' #' Perform survival regression on a Spark DataFrame, using an Accelerated #' failure time (AFT) model with potentially right-censored data. #' #' @template roxlate-ml-x #' @template roxlate-ml-response #' @template roxlate-ml-features #' @template roxlate-ml-intercept #' @param censor The name of the vector that provides censoring information. #' This should be a numeric vector, with 0 marking uncensored data, and #' 1 marking right-censored data. #' @template roxlate-ml-max-iter #' @template roxlate-ml-dots #' #' @family Spark ML routines #' #' @export ml_survival_regression <- function(x, response, features, intercept = TRUE, censor = "censor", max.iter = 100L, ...) { df <- spark_dataframe(x) sc <- spark_connection(df) df <- ml_prepare_response_features_intercept(df, response, features, intercept) censor <- ensure_scalar_character(censor) max.iter <- ensure_scalar_integer(max.iter) only_model <- ensure_scalar_boolean(list(...)$only_model, default = FALSE) envir <- new.env(parent = emptyenv()) tdf <- ml_prepare_dataframe(df, features, response, envir = envir) envir$model <- "org.apache.spark.ml.regression.AFTSurvivalRegression" rf <- invoke_new(sc, envir$model) model <- rf %>% invoke("setMaxIter", max.iter) %>% invoke("setFeaturesCol", envir$features) %>% invoke("setLabelCol", envir$response) %>% invoke("setFitIntercept", as.logical(intercept)) %>% invoke("setCensorCol", censor) if (only_model) return(model) fit <- model %>% invoke("fit", tdf) coefficients <- fit %>% invoke("coefficients") %>% invoke("toArray") names(coefficients) <- features hasIntercept <- invoke(fit, "getFitIntercept") if (hasIntercept) { intercept <- invoke(fit, "intercept") coefficients <- c(coefficients, intercept) names(coefficients) <- c(features, "(Intercept)") } coefficients <- intercept_first(coefficients) scale <- invoke(fit, "scale") ml_model("survival_regression", fit, features = features, response = response, intercept = intercept, coefficients = coefficients, intercept = intercept, scale = scale, model.parameters = as.list(envir) ) } #' @export print.ml_model_survival_regression <- function(x, ...) { ml_model_print_call(x) }
# # antlrpdg.R, 17 Jan 20 # # Data from: # Hussain Abdullah A. Al-Mutawa # On the Classification of Cyclic Dependencies in Java Programs # # Example from: # Evidence-based Software Engineering: based on the publicly available data # Derek M. Jones # # TAG Java dependency-cycles source("ESEUR_config.r") library("igraph") library("plyr") library("jsonlite") # Increasing default_width does not seem to have any/much effect plot_layout(3, 2, max_width=ESEUR_default_width+2) par(oma=OMA_default+c(-1.5, -1.0, -0.2, -0.5)) par(mar=MAR_default+c(-1.5, -3, -0.1, -0.5)) # Remove last name on path (which is assumed to be method name) remove_last=function(name_str) { sub("\\.[a-zA-Z0-9$_]+$", "", name_str) } get_src_tgt=function(df) { t=c(remove_last(df$src), remove_last(df$tar)) # remove self references if (t[1] == t[2]) return(NULL) return(t) } plot_PDG=function(file_str) { ant=fromJSON(paste0(dir_str, file_str)) from_to=adply(ant$edges, 1, get_src_tgt) f_t=data.frame(from=from_to$V1, to=from_to$V2) ant_g=graph.data.frame(unique(f_t), directed=TRUE) V(ant_g)$label=NA E(ant_g)$arrow.size=0.3 plot(ant_g, # main=sub("\\.json.xz", "", file_str), # cex.main=2 has no effect! vertex.frame.color="white") title(sub("\\.json.xz", "", file_str), cex.main=1.6) } dir_str=paste0(ESEUR_dir, "ecosystems/") top_files=list.files(dir_str) top_files=top_files[grep("antlr-.*\\.json.xz$", top_files)] dummy=sapply(top_files, plot_PDG)
/ecosystems/antlrpdg.R
no_license
sebastianBIanalytics/ESEUR-code-data
R
false
false
1,445
r
# # antlrpdg.R, 17 Jan 20 # # Data from: # Hussain Abdullah A. Al-Mutawa # On the Classification of Cyclic Dependencies in Java Programs # # Example from: # Evidence-based Software Engineering: based on the publicly available data # Derek M. Jones # # TAG Java dependency-cycles source("ESEUR_config.r") library("igraph") library("plyr") library("jsonlite") # Increasing default_width does not seem to have any/much effect plot_layout(3, 2, max_width=ESEUR_default_width+2) par(oma=OMA_default+c(-1.5, -1.0, -0.2, -0.5)) par(mar=MAR_default+c(-1.5, -3, -0.1, -0.5)) # Remove last name on path (which is assumed to be method name) remove_last=function(name_str) { sub("\\.[a-zA-Z0-9$_]+$", "", name_str) } get_src_tgt=function(df) { t=c(remove_last(df$src), remove_last(df$tar)) # remove self references if (t[1] == t[2]) return(NULL) return(t) } plot_PDG=function(file_str) { ant=fromJSON(paste0(dir_str, file_str)) from_to=adply(ant$edges, 1, get_src_tgt) f_t=data.frame(from=from_to$V1, to=from_to$V2) ant_g=graph.data.frame(unique(f_t), directed=TRUE) V(ant_g)$label=NA E(ant_g)$arrow.size=0.3 plot(ant_g, # main=sub("\\.json.xz", "", file_str), # cex.main=2 has no effect! vertex.frame.color="white") title(sub("\\.json.xz", "", file_str), cex.main=1.6) } dir_str=paste0(ESEUR_dir, "ecosystems/") top_files=list.files(dir_str) top_files=top_files[grep("antlr-.*\\.json.xz$", top_files)] dummy=sapply(top_files, plot_PDG)
library(tidyverse) library(R.utils) library(DiagrammeR) library(igraph) getUnobservedInts <- function(df, desiredResponsesMask, boolLen, str4true) { # This function first turns the dataframe of parameter-sweep results # (i.e. observed responses), written in 'pos' and 'neg' format, into # a vector of binary values (each row is represented by a binary value), # and then convert the binary values into a list of integers # which represents the observed integers. After discarding observed integers # from all possible integers, the funciton returns a list of unobserved integers. observedInts <- df %>% select(., desiredResponsesMask) %>% # select desired responses apply(., 2, function(x) ifelse(x == str4true, "1", "0")) %>% # pos as 1 & neg as 0 as.data.frame() %>% apply(., 1, paste0, collapse="") %>% # binary strings representing responses strtoi(., base = 2L) # convert the binary string into integers unobservedInts <- c(0: (2**boolLen-1)) %>% # all possible responses as integers discard(., . %in% observedInts) # discard observed return(unobservedInts) } getUnobservedInts2 <- function(df, desiredResponsesMask, boolLen) { # This function is similar to getUnobservedInts, but takes the dataframe # of parameter-sweep results written in '0' and '1' format. observedInts <- df %>% select(., desiredResponsesMask) %>% # select desired responses as.data.frame() %>% apply(., 1, paste0, collapse="") %>% # binary strings representing responses strtoi(., base = 2L) # convert the binary string into integers unobservedInts <- c(0: (2**boolLen-1)) %>% # all possible responses as integers discard(., . %in% observedInts) # discard observed return(unobservedInts) } getUnobservedBooldf <- function(unobservedInts, desiredResponses){ # The purpose of this function is to turn a list of integers into a # dataframe in Boolean formats (species responses written as 0s and 1s) # with an additional output column that meets the requirements of logicopt() # for Boolean minimization. unobservedBooldf <- append((2**length(desiredResponses))-1, unobservedInts) %>% intToBin(.) %>% # convert the integer back into binary strings str_split(., "") %>% # chop strings to 0s and 1s do.call(rbind, .) %>% as.data.frame() %>% setNames(., desiredResponses) %>% slice(., -1) %>% mutate(., unob = "1") # add an output column to meet the requirements of logicopt() return(unobservedBooldf) } getPCUList <- function(optEqn, str4true, str4flase, desiredResponses){ # This function converts the optimized equations (i.e. results of Boolean minimization) # into a list of PCUs. # split the string of equation and get PCUs as a list. unobservedList <- str_split(optEqn, " [=] ", simplify = TRUE)[2] %>% str_split(., " [+] ") %>% unlist(.) %>% str_split(., "[*]") # convert the binary variabe into descriptive strings, e.g. # RABBITS_ALBATROSSES->"posrabbits_albatrosses" and # rabbits_albatrosses->"negrabbits_albatrosses" dictionary <- setNames( append(paste0(str4true, desiredResponses), paste0(str4flase, desiredResponses)), append(str_to_upper(desiredResponses), str_to_lower(desiredResponses)) ) # create a named vector as dictionary PCUList_unordered <- unobservedList %>% lapply(., function(i) dictionary[i]) %>% # match and replace use dictionary lapply(., function(i) unname(i)) # unname each list PCUList <- PCUList_unordered[order(sapply(PCUList_unordered,length))] # sort PCUs return(PCUList) # show the PCUList } get_edgelist_singleAnte <- function(PCUList) { # Get the edgelist for the simplest kind of implication network, # where every logical implication statement in its single-antecedent form is included. andCounter = 0 orCounter = 0 edgesList = list() for (PCU in PCUList[]){ for (p in PCU[]){ if (length(PCU) == 1) { ante = 'True' notpp = ifelse(grepl('pos', p), str_replace(p, 'pos', 'neg'), str_replace(p, 'neg', 'pos')) cons = notpp } else { ante = p cons = NULL qs = PCU[!PCU %in% p] for (q in qs) { notqq = ifelse(grepl('pos', q), str_replace(q, 'pos', 'neg'), str_replace(q, 'neg', 'pos')) cons = append(cons, notqq) } } # Create the edges list if (length(cons) == 1) { edgesList[[length(edgesList)+1]] = append(ante, cons) } else { orNode = paste('or', as.character(orCounter), sep = "") edgesList[[length(edgesList)+1]] = append(ante, orNode) orCounter = orCounter + 1 for (c in cons) { edgesList[[length(edgesList)+1]] = append(orNode, c) } } } } return(edgesList) } get_edgelist_certainAnte <- function(PCUList, alwaysAnteList) { # Get the edgelist for the implication network where certain responses are # always treated as the antecedent (alwaysAnteList) andCounter = 0 orCounter = 0 edgesList = list() for (PCU in PCUList[]){ # split into a list of antecedents and consequents anteList = list() consList_raw = list() for(p in PCU[]) { ifelse(p %in% alwaysAnteList, anteList[[length(anteList)+1]] <- p, consList_raw[[length(consList_raw)+1]] <- p) } # The consequents need to be negated consList = list() for (q in consList_raw) { notqq = ifelse(grepl('pos', q), str_replace(q, 'pos', 'neg'), str_replace(q, 'neg', 'pos')) consList = append(consList, notqq) } # if there are no antecedents, the consequents will be attached to the True node if (length(anteList) == 0) {anteList = append(anteList, 'True')} # if there are no consequents, the antecedents will be attached to the False node if (length(consList) == 0) {consList = append(consList, 'False')} # identify the upper and lower node, which depends on how many antecedents and consequents # do upper and antecedents if (length(anteList) < 2) { upperNode <- anteList[[1]] } else { # the upper node is an And node andCounter = andCounter + 1 upperNode <- paste('and', as.character(andCounter), sep = "") # and every antecedent has an edge with this And node for (p in anteList) { edgesList[[length(edgesList)+1]] = append(p, upperNode) } } # do lower and consequents if (length(consList) < 2) { lowerNode = consList[[1]] } else { # the lower node is an Or node orCounter = orCounter + 1 lowerNode <- paste('or', as.character(orCounter), sep = "") # and every consequent has an edge with this Or node for (q in consList) { edgesList[[length(edgesList)+1]] = append(lowerNode, q) } } # link the upper and lower node edgesList[[length(edgesList)+1]] = append(upperNode, lowerNode) } return(edgesList) } draw_implication_network <- function(edgesList, niceNames){ # Draw the implication nework from the edgelist get from the funtion # get_edgelist_singleAnte() or get_edgelist_certainAnte(). controlSymbol = '&darr; '; # Use edgelist to create an igraph object and get the nodelist from the igraph object edges_list <- do.call(rbind, edgesList) nodes_list <- edges_list %>% graph_from_edgelist(., directed = TRUE) %>% get.vertex.attribute(.) %>% get("name", .) # set attributes for response nodes nodes_df_resp <- # get response nodes data.frame(names = nodes_list) %>% mutate_if(is.factor, as.character) %>% filter(grepl('pos|neg', names)) %>% # set sign, fillcolor and node shape mutate(respSign = case_when(grepl('pos', names) ~ "+", TRUE ~ "&#8210;"), fillcolor = case_when(grepl('pos', names) ~ "white", TRUE ~ "gray"), shape = "box") %>% # separate the strings into two parts: control and response species mutate(dropSign = substring(names, 4)) %>% separate(dropSign, c("contSpp", "respSpp"), "_") # check if niceNames are defined if (hasArg(niceNames)){ contSppNiceName = unname(niceNames[nodes_df_resp$contSpp]) respSppNiceName = unname(niceNames[nodes_df_resp$respSpp]) } else { contSppNiceName = nodes_df_resp$contSpp respSppNiceName = nodes_df_resp$respSpp } # set labels for response nodes nodes_df_resp <- nodes_df_resp %>% mutate(contSppNiceName = contSppNiceName, respSppNiceName = respSppNiceName) %>% mutate(label = paste0('< <font point-size="10">', controlSymbol, contSppNiceName, '</font>', '<br align="left"/> &nbsp; &nbsp; ', respSppNiceName, ' ', respSign, ' >')) %>% # select node attribute columns select(names, shape, fillcolor, label) # set attributes for Boolean nodes and # combine response node dataframe and Boolean node dataframe into one dataframe nodes_df <- # get Boolean nodes data.frame(names = nodes_list) %>% mutate_if(is.factor, as.character) %>% filter(!grepl('pos|neg', names)) %>% # set attributes for Boolean nodes mutate(shape = "circle", fillcolor = "white", label = case_when(grepl('or', names) ~ "or", grepl('and', names) ~ "\"&\"", #NOTE!!!!!!!!! grepl('False', names) ~ "False", TRUE ~ "True")) %>% # combine the two dataframe bind_rows(., nodes_df_resp) ## construct NDF and EDF for DiagrammeR ndf <- create_node_df( n = nrow(nodes_df), names = nodes_df[, "names"], label = nodes_df[ , "label"], shape = nodes_df[, "shape"], fillcolor = nodes_df[, "fillcolor"]) edges_df <- edges_list %>% as.data.frame() %>% setNames(., c("labelfrom", "labelto")) %>% mutate_if(is.factor, as.character) %>% left_join(., ndf[, c("id", "names")], by = c("labelfrom"="names")) %>% rename(from = id) %>% left_join(., ndf[, c("id", "names")], by = c("labelto"="names")) %>% rename(to = id) edf <- create_edge_df( from = edges_df[ , "from"], to = edges_df[ , "to"]) G <- create_graph( nodes_df = ndf, edges_df = edf, directed = TRUE, attr_theme = NULL) %>% add_global_graph_attrs( attr = "style", value = '\"rounded, filled\"', attr_type = "node") %>% add_global_graph_attrs( attr = "width", value = 0, attr_type = "node") %>% add_global_graph_attrs( attr = "margin", value = 0, attr_type = "node") dot <- gsub("\\'","",generate_dot(G)) DiagrammeR(diagram = dot, type = "grViz") }
/qualmodfunc/findPCU.R
no_license
yhan178/qualitative-modeling-r
R
false
false
12,226
r
library(tidyverse) library(R.utils) library(DiagrammeR) library(igraph) getUnobservedInts <- function(df, desiredResponsesMask, boolLen, str4true) { # This function first turns the dataframe of parameter-sweep results # (i.e. observed responses), written in 'pos' and 'neg' format, into # a vector of binary values (each row is represented by a binary value), # and then convert the binary values into a list of integers # which represents the observed integers. After discarding observed integers # from all possible integers, the funciton returns a list of unobserved integers. observedInts <- df %>% select(., desiredResponsesMask) %>% # select desired responses apply(., 2, function(x) ifelse(x == str4true, "1", "0")) %>% # pos as 1 & neg as 0 as.data.frame() %>% apply(., 1, paste0, collapse="") %>% # binary strings representing responses strtoi(., base = 2L) # convert the binary string into integers unobservedInts <- c(0: (2**boolLen-1)) %>% # all possible responses as integers discard(., . %in% observedInts) # discard observed return(unobservedInts) } getUnobservedInts2 <- function(df, desiredResponsesMask, boolLen) { # This function is similar to getUnobservedInts, but takes the dataframe # of parameter-sweep results written in '0' and '1' format. observedInts <- df %>% select(., desiredResponsesMask) %>% # select desired responses as.data.frame() %>% apply(., 1, paste0, collapse="") %>% # binary strings representing responses strtoi(., base = 2L) # convert the binary string into integers unobservedInts <- c(0: (2**boolLen-1)) %>% # all possible responses as integers discard(., . %in% observedInts) # discard observed return(unobservedInts) } getUnobservedBooldf <- function(unobservedInts, desiredResponses){ # The purpose of this function is to turn a list of integers into a # dataframe in Boolean formats (species responses written as 0s and 1s) # with an additional output column that meets the requirements of logicopt() # for Boolean minimization. unobservedBooldf <- append((2**length(desiredResponses))-1, unobservedInts) %>% intToBin(.) %>% # convert the integer back into binary strings str_split(., "") %>% # chop strings to 0s and 1s do.call(rbind, .) %>% as.data.frame() %>% setNames(., desiredResponses) %>% slice(., -1) %>% mutate(., unob = "1") # add an output column to meet the requirements of logicopt() return(unobservedBooldf) } getPCUList <- function(optEqn, str4true, str4flase, desiredResponses){ # This function converts the optimized equations (i.e. results of Boolean minimization) # into a list of PCUs. # split the string of equation and get PCUs as a list. unobservedList <- str_split(optEqn, " [=] ", simplify = TRUE)[2] %>% str_split(., " [+] ") %>% unlist(.) %>% str_split(., "[*]") # convert the binary variabe into descriptive strings, e.g. # RABBITS_ALBATROSSES->"posrabbits_albatrosses" and # rabbits_albatrosses->"negrabbits_albatrosses" dictionary <- setNames( append(paste0(str4true, desiredResponses), paste0(str4flase, desiredResponses)), append(str_to_upper(desiredResponses), str_to_lower(desiredResponses)) ) # create a named vector as dictionary PCUList_unordered <- unobservedList %>% lapply(., function(i) dictionary[i]) %>% # match and replace use dictionary lapply(., function(i) unname(i)) # unname each list PCUList <- PCUList_unordered[order(sapply(PCUList_unordered,length))] # sort PCUs return(PCUList) # show the PCUList } get_edgelist_singleAnte <- function(PCUList) { # Get the edgelist for the simplest kind of implication network, # where every logical implication statement in its single-antecedent form is included. andCounter = 0 orCounter = 0 edgesList = list() for (PCU in PCUList[]){ for (p in PCU[]){ if (length(PCU) == 1) { ante = 'True' notpp = ifelse(grepl('pos', p), str_replace(p, 'pos', 'neg'), str_replace(p, 'neg', 'pos')) cons = notpp } else { ante = p cons = NULL qs = PCU[!PCU %in% p] for (q in qs) { notqq = ifelse(grepl('pos', q), str_replace(q, 'pos', 'neg'), str_replace(q, 'neg', 'pos')) cons = append(cons, notqq) } } # Create the edges list if (length(cons) == 1) { edgesList[[length(edgesList)+1]] = append(ante, cons) } else { orNode = paste('or', as.character(orCounter), sep = "") edgesList[[length(edgesList)+1]] = append(ante, orNode) orCounter = orCounter + 1 for (c in cons) { edgesList[[length(edgesList)+1]] = append(orNode, c) } } } } return(edgesList) } get_edgelist_certainAnte <- function(PCUList, alwaysAnteList) { # Get the edgelist for the implication network where certain responses are # always treated as the antecedent (alwaysAnteList) andCounter = 0 orCounter = 0 edgesList = list() for (PCU in PCUList[]){ # split into a list of antecedents and consequents anteList = list() consList_raw = list() for(p in PCU[]) { ifelse(p %in% alwaysAnteList, anteList[[length(anteList)+1]] <- p, consList_raw[[length(consList_raw)+1]] <- p) } # The consequents need to be negated consList = list() for (q in consList_raw) { notqq = ifelse(grepl('pos', q), str_replace(q, 'pos', 'neg'), str_replace(q, 'neg', 'pos')) consList = append(consList, notqq) } # if there are no antecedents, the consequents will be attached to the True node if (length(anteList) == 0) {anteList = append(anteList, 'True')} # if there are no consequents, the antecedents will be attached to the False node if (length(consList) == 0) {consList = append(consList, 'False')} # identify the upper and lower node, which depends on how many antecedents and consequents # do upper and antecedents if (length(anteList) < 2) { upperNode <- anteList[[1]] } else { # the upper node is an And node andCounter = andCounter + 1 upperNode <- paste('and', as.character(andCounter), sep = "") # and every antecedent has an edge with this And node for (p in anteList) { edgesList[[length(edgesList)+1]] = append(p, upperNode) } } # do lower and consequents if (length(consList) < 2) { lowerNode = consList[[1]] } else { # the lower node is an Or node orCounter = orCounter + 1 lowerNode <- paste('or', as.character(orCounter), sep = "") # and every consequent has an edge with this Or node for (q in consList) { edgesList[[length(edgesList)+1]] = append(lowerNode, q) } } # link the upper and lower node edgesList[[length(edgesList)+1]] = append(upperNode, lowerNode) } return(edgesList) } draw_implication_network <- function(edgesList, niceNames){ # Draw the implication nework from the edgelist get from the funtion # get_edgelist_singleAnte() or get_edgelist_certainAnte(). controlSymbol = '&darr; '; # Use edgelist to create an igraph object and get the nodelist from the igraph object edges_list <- do.call(rbind, edgesList) nodes_list <- edges_list %>% graph_from_edgelist(., directed = TRUE) %>% get.vertex.attribute(.) %>% get("name", .) # set attributes for response nodes nodes_df_resp <- # get response nodes data.frame(names = nodes_list) %>% mutate_if(is.factor, as.character) %>% filter(grepl('pos|neg', names)) %>% # set sign, fillcolor and node shape mutate(respSign = case_when(grepl('pos', names) ~ "+", TRUE ~ "&#8210;"), fillcolor = case_when(grepl('pos', names) ~ "white", TRUE ~ "gray"), shape = "box") %>% # separate the strings into two parts: control and response species mutate(dropSign = substring(names, 4)) %>% separate(dropSign, c("contSpp", "respSpp"), "_") # check if niceNames are defined if (hasArg(niceNames)){ contSppNiceName = unname(niceNames[nodes_df_resp$contSpp]) respSppNiceName = unname(niceNames[nodes_df_resp$respSpp]) } else { contSppNiceName = nodes_df_resp$contSpp respSppNiceName = nodes_df_resp$respSpp } # set labels for response nodes nodes_df_resp <- nodes_df_resp %>% mutate(contSppNiceName = contSppNiceName, respSppNiceName = respSppNiceName) %>% mutate(label = paste0('< <font point-size="10">', controlSymbol, contSppNiceName, '</font>', '<br align="left"/> &nbsp; &nbsp; ', respSppNiceName, ' ', respSign, ' >')) %>% # select node attribute columns select(names, shape, fillcolor, label) # set attributes for Boolean nodes and # combine response node dataframe and Boolean node dataframe into one dataframe nodes_df <- # get Boolean nodes data.frame(names = nodes_list) %>% mutate_if(is.factor, as.character) %>% filter(!grepl('pos|neg', names)) %>% # set attributes for Boolean nodes mutate(shape = "circle", fillcolor = "white", label = case_when(grepl('or', names) ~ "or", grepl('and', names) ~ "\"&\"", #NOTE!!!!!!!!! grepl('False', names) ~ "False", TRUE ~ "True")) %>% # combine the two dataframe bind_rows(., nodes_df_resp) ## construct NDF and EDF for DiagrammeR ndf <- create_node_df( n = nrow(nodes_df), names = nodes_df[, "names"], label = nodes_df[ , "label"], shape = nodes_df[, "shape"], fillcolor = nodes_df[, "fillcolor"]) edges_df <- edges_list %>% as.data.frame() %>% setNames(., c("labelfrom", "labelto")) %>% mutate_if(is.factor, as.character) %>% left_join(., ndf[, c("id", "names")], by = c("labelfrom"="names")) %>% rename(from = id) %>% left_join(., ndf[, c("id", "names")], by = c("labelto"="names")) %>% rename(to = id) edf <- create_edge_df( from = edges_df[ , "from"], to = edges_df[ , "to"]) G <- create_graph( nodes_df = ndf, edges_df = edf, directed = TRUE, attr_theme = NULL) %>% add_global_graph_attrs( attr = "style", value = '\"rounded, filled\"', attr_type = "node") %>% add_global_graph_attrs( attr = "width", value = 0, attr_type = "node") %>% add_global_graph_attrs( attr = "margin", value = 0, attr_type = "node") dot <- gsub("\\'","",generate_dot(G)) DiagrammeR(diagram = dot, type = "grViz") }
#' @name osrmTable #' @title Get Travel Time Matrices Between Points #' @description Build and send OSRM API queries to get travel time matrices #' between points. This function interfaces the \emph{table} OSRM service. #' @param loc a data frame containing 3 fields: points identifiers, longitudes #' and latitudes (WGS84). It can also be a SpatialPointsDataFrame, a #' SpatialPolygonsDataFrame or an sf object. If so, row names are used as identifiers. #' If loc parameter is used, all pair-wise distances are computed. #' @param src a data frame containing origin points identifiers, longitudes #' and latitudes (WGS84). It can also be a SpatialPointsDataFrame, a #' SpatialPolygonsDataFrame or an sf object. If so, row names are used as identifiers. #' If dst and src parameters are used, only pairs between scr/dst are computed. #' @param dst a data frame containing destination points identifiers, longitudes #' and latitudes (WGS84). It can also be a SpatialPointsDataFrame a #' SpatialPolygonsDataFrame or an sf object. If so, row names are used as identifiers. #' @param measure a character indicating what measures are calculated. It can #' be "duration" (in minutes), "distance" (meters), or both c('duration', #' 'distance'). The demo server only allows "duration". #' @param exclude pass an optional "exclude" request option to the OSRM API. #' @param gepaf a boolean indicating if coordinates are sent encoded with the #' google encoded algorithm format (TRUE) or not (FALSE). Must be FALSE if using #' the public OSRM API. #' @param osrm.server the base URL of the routing server. #' getOption("osrm.server") by default. #' @param osrm.profile the routing profile to use, e.g. "car", "bike" or "foot" #' (when using the routing.openstreetmap.de test server). #' getOption("osrm.profile") by default. #' @return A list containing 3 data frames is returned. #' durations is the matrix of travel times (in minutes), #' sources and destinations are the coordinates of #' the origin and destination points actually used to compute the travel #' times (WGS84). #' @details If loc, src or dst are data frames we assume that the 3 first #' columns of the data frame are: identifiers, longitudes and latitudes. #' @note #' If you want to get a large number of distances make sure to set the #' "max-table-size" argument (Max. locations supported in table) of the OSRM #' server accordingly. #' @seealso \link{osrmIsochrone} #' @importFrom sf st_as_sf #' @examples #' \dontrun{ #' # Load data #' data("berlin") #' #' # Inputs are data frames #' # Travel time matrix #' distA <- osrmTable(loc = apotheke.df[1:50, c("id","lon","lat")]) #' # First 5 rows and columns #' distA$durations[1:5,1:5] #' #' # Travel time matrix with different sets of origins and destinations #' distA2 <- osrmTable(src = apotheke.df[1:10,c("id","lon","lat")], #' dst = apotheke.df[11:20,c("id","lon","lat")]) #' # First 5 rows and columns #' distA2$durations[1:5,1:5] #' #' # Inputs are sf points #' distA3 <- osrmTable(loc = apotheke.sf[1:10,]) #' # First 5 rows and columns #' distA3$durations[1:5,1:5] #' #' # Travel time matrix with different sets of origins and destinations #' distA4 <- osrmTable(src = apotheke.sf[1:10,], dst = apotheke.sf[11:20,]) #' # First 5 rows and columns #' distA4$durations[1:5,1:5] #' } #' @export osrmTable <- function(loc, src = NULL, dst = NULL, exclude = NULL, gepaf = FALSE, measure="duration", osrm.server = getOption("osrm.server"), osrm.profile = getOption("osrm.profile")){ if(osrm.server == "https://routing.openstreetmap.de/") { osrm.server = paste0(osrm.server, "routed-", osrm.profile, "/") osrm.profile = "driving" } tryCatch({ # input mgmt if (is.null(src)){ if(methods::is(loc,"Spatial")){ loc <- st_as_sf(x = loc) } if(testSf(loc)){ loc <- sfToDf(x = loc) } names(loc) <- c("id", "lon", "lat") src <- loc dst <- loc sep <- "?" req <- tableLoc(loc = loc, gepaf = gepaf, osrm.server = osrm.server, osrm.profile = osrm.profile) }else{ if(methods::is(src,"Spatial")){ src <- st_as_sf(x = src) } if(testSf(src)){ src <- sfToDf(x = src) } if(methods::is(dst,"Spatial")){ dst <- st_as_sf(x = dst) } if(testSf(dst)){ dst <- sfToDf(x = dst) } names(src) <- c("id", "lon", "lat") names(dst) <- c("id", "lon", "lat") # Build the query loc <- rbind(src, dst) sep = "&" req <- paste(tableLoc(loc = loc, gepaf = gepaf, osrm.server = osrm.server, osrm.profile = osrm.profile), "?sources=", paste(0:(nrow(src)-1), collapse = ";"), "&destinations=", paste(nrow(src):(nrow(loc)-1), collapse = ";"), sep="") } # exclude mngmnt if (!is.null(exclude)) { exclude_str <- paste0(sep,"exclude=", exclude, sep = "") sep="&" }else{ exclude_str <- "" } # annotation mngmnt annotations <- paste0(sep, "annotations=", paste0(measure, collapse=',')) # if(getOption("osrm.server") == "http://router.project-osrm.org/"){ # annotations <- "" # } # final req req <- paste0(req, exclude_str, annotations) # print(req) req <- utils::URLencode(req) osrmLimit(nSrc = nrow(src), nDst = nrow(dst), nreq = nchar(req)) # print(req) # Get the result bo=0 while(bo!=10){ x = try({ req_handle <- curl::new_handle(verbose = FALSE) curl::handle_setopt(req_handle, useragent = "osrm_R_package") resRaw <- curl::curl(req, handle = req_handle) res <- jsonlite::fromJSON(resRaw) }, silent = TRUE) if (class(x)=="try-error") { Sys.sleep(1) bo <- bo+1 } else break } # Check results if(is.null(res$code)){ e <- simpleError(res$message) stop(e) }else{ e <- simpleError(paste0(res$code,"\n",res$message)) if(res$code != "Ok"){stop(e)} } output <- list() if(!is.null(res$durations)){ # get the duration table output$durations <- durTableFormat(res = res, src = src, dst = dst) } if(!is.null(res$distances)){ # get the distance table output$distances <- distTableFormat(res = res, src = src, dst = dst) } # get the coordinates coords <- coordFormat(res = res, src = src, dst = dst) output$sources <- coords$sources output$destinations = coords$destinations return(output) }, error=function(e) {message("The OSRM server returned an error:\n", e)}) return(NULL) }
/R/osrmTable.R
permissive
IsmailTan35/osrm-backend
R
false
false
6,869
r
#' @name osrmTable #' @title Get Travel Time Matrices Between Points #' @description Build and send OSRM API queries to get travel time matrices #' between points. This function interfaces the \emph{table} OSRM service. #' @param loc a data frame containing 3 fields: points identifiers, longitudes #' and latitudes (WGS84). It can also be a SpatialPointsDataFrame, a #' SpatialPolygonsDataFrame or an sf object. If so, row names are used as identifiers. #' If loc parameter is used, all pair-wise distances are computed. #' @param src a data frame containing origin points identifiers, longitudes #' and latitudes (WGS84). It can also be a SpatialPointsDataFrame, a #' SpatialPolygonsDataFrame or an sf object. If so, row names are used as identifiers. #' If dst and src parameters are used, only pairs between scr/dst are computed. #' @param dst a data frame containing destination points identifiers, longitudes #' and latitudes (WGS84). It can also be a SpatialPointsDataFrame a #' SpatialPolygonsDataFrame or an sf object. If so, row names are used as identifiers. #' @param measure a character indicating what measures are calculated. It can #' be "duration" (in minutes), "distance" (meters), or both c('duration', #' 'distance'). The demo server only allows "duration". #' @param exclude pass an optional "exclude" request option to the OSRM API. #' @param gepaf a boolean indicating if coordinates are sent encoded with the #' google encoded algorithm format (TRUE) or not (FALSE). Must be FALSE if using #' the public OSRM API. #' @param osrm.server the base URL of the routing server. #' getOption("osrm.server") by default. #' @param osrm.profile the routing profile to use, e.g. "car", "bike" or "foot" #' (when using the routing.openstreetmap.de test server). #' getOption("osrm.profile") by default. #' @return A list containing 3 data frames is returned. #' durations is the matrix of travel times (in minutes), #' sources and destinations are the coordinates of #' the origin and destination points actually used to compute the travel #' times (WGS84). #' @details If loc, src or dst are data frames we assume that the 3 first #' columns of the data frame are: identifiers, longitudes and latitudes. #' @note #' If you want to get a large number of distances make sure to set the #' "max-table-size" argument (Max. locations supported in table) of the OSRM #' server accordingly. #' @seealso \link{osrmIsochrone} #' @importFrom sf st_as_sf #' @examples #' \dontrun{ #' # Load data #' data("berlin") #' #' # Inputs are data frames #' # Travel time matrix #' distA <- osrmTable(loc = apotheke.df[1:50, c("id","lon","lat")]) #' # First 5 rows and columns #' distA$durations[1:5,1:5] #' #' # Travel time matrix with different sets of origins and destinations #' distA2 <- osrmTable(src = apotheke.df[1:10,c("id","lon","lat")], #' dst = apotheke.df[11:20,c("id","lon","lat")]) #' # First 5 rows and columns #' distA2$durations[1:5,1:5] #' #' # Inputs are sf points #' distA3 <- osrmTable(loc = apotheke.sf[1:10,]) #' # First 5 rows and columns #' distA3$durations[1:5,1:5] #' #' # Travel time matrix with different sets of origins and destinations #' distA4 <- osrmTable(src = apotheke.sf[1:10,], dst = apotheke.sf[11:20,]) #' # First 5 rows and columns #' distA4$durations[1:5,1:5] #' } #' @export osrmTable <- function(loc, src = NULL, dst = NULL, exclude = NULL, gepaf = FALSE, measure="duration", osrm.server = getOption("osrm.server"), osrm.profile = getOption("osrm.profile")){ if(osrm.server == "https://routing.openstreetmap.de/") { osrm.server = paste0(osrm.server, "routed-", osrm.profile, "/") osrm.profile = "driving" } tryCatch({ # input mgmt if (is.null(src)){ if(methods::is(loc,"Spatial")){ loc <- st_as_sf(x = loc) } if(testSf(loc)){ loc <- sfToDf(x = loc) } names(loc) <- c("id", "lon", "lat") src <- loc dst <- loc sep <- "?" req <- tableLoc(loc = loc, gepaf = gepaf, osrm.server = osrm.server, osrm.profile = osrm.profile) }else{ if(methods::is(src,"Spatial")){ src <- st_as_sf(x = src) } if(testSf(src)){ src <- sfToDf(x = src) } if(methods::is(dst,"Spatial")){ dst <- st_as_sf(x = dst) } if(testSf(dst)){ dst <- sfToDf(x = dst) } names(src) <- c("id", "lon", "lat") names(dst) <- c("id", "lon", "lat") # Build the query loc <- rbind(src, dst) sep = "&" req <- paste(tableLoc(loc = loc, gepaf = gepaf, osrm.server = osrm.server, osrm.profile = osrm.profile), "?sources=", paste(0:(nrow(src)-1), collapse = ";"), "&destinations=", paste(nrow(src):(nrow(loc)-1), collapse = ";"), sep="") } # exclude mngmnt if (!is.null(exclude)) { exclude_str <- paste0(sep,"exclude=", exclude, sep = "") sep="&" }else{ exclude_str <- "" } # annotation mngmnt annotations <- paste0(sep, "annotations=", paste0(measure, collapse=',')) # if(getOption("osrm.server") == "http://router.project-osrm.org/"){ # annotations <- "" # } # final req req <- paste0(req, exclude_str, annotations) # print(req) req <- utils::URLencode(req) osrmLimit(nSrc = nrow(src), nDst = nrow(dst), nreq = nchar(req)) # print(req) # Get the result bo=0 while(bo!=10){ x = try({ req_handle <- curl::new_handle(verbose = FALSE) curl::handle_setopt(req_handle, useragent = "osrm_R_package") resRaw <- curl::curl(req, handle = req_handle) res <- jsonlite::fromJSON(resRaw) }, silent = TRUE) if (class(x)=="try-error") { Sys.sleep(1) bo <- bo+1 } else break } # Check results if(is.null(res$code)){ e <- simpleError(res$message) stop(e) }else{ e <- simpleError(paste0(res$code,"\n",res$message)) if(res$code != "Ok"){stop(e)} } output <- list() if(!is.null(res$durations)){ # get the duration table output$durations <- durTableFormat(res = res, src = src, dst = dst) } if(!is.null(res$distances)){ # get the distance table output$distances <- distTableFormat(res = res, src = src, dst = dst) } # get the coordinates coords <- coordFormat(res = res, src = src, dst = dst) output$sources <- coords$sources output$destinations = coords$destinations return(output) }, error=function(e) {message("The OSRM server returned an error:\n", e)}) return(NULL) }
% Generated by roxygen2 (4.0.1): do not edit by hand \name{extract_ILDIS} \alias{extract_ILDIS} \title{Extract geographical records data from ILDIS species page html} \usage{ extract_ILDIS(html_file) } \arguments{ \item{html_file}{The path of the html file to process} } \description{ Extract geographical records data from ILDIS species page html } \details{ The name of the species is extracted from the filename, as generated by \code{\link{download_ILDIS}}. }
/man/extract_ILDIS.Rd
permissive
rdinnager/GlobalNfix
R
false
false
465
rd
% Generated by roxygen2 (4.0.1): do not edit by hand \name{extract_ILDIS} \alias{extract_ILDIS} \title{Extract geographical records data from ILDIS species page html} \usage{ extract_ILDIS(html_file) } \arguments{ \item{html_file}{The path of the html file to process} } \description{ Extract geographical records data from ILDIS species page html } \details{ The name of the species is extracted from the filename, as generated by \code{\link{download_ILDIS}}. }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sim_bessel_layers.R \name{simulate_layered_brownian_bridge_bessel} \alias{simulate_layered_brownian_bridge_bessel} \title{Layered Brownian Bridge sampler} \usage{ simulate_layered_brownian_bridge_bessel(x, y, s, t, a, l, sim_times) } \arguments{ \item{x}{start value of Brownian bridge} \item{y}{end value of Brownian bridge} \item{s}{start value of Brownian bridge} \item{t}{end value of Brownian bridge} \item{a}{vector/sequence of numbers} \item{l}{integer number denoting Bessel layer, i.e. Brownian bridge is contained in [min(x,y)-a[l], max(x,y)+a[l]]} \item{sim_times}{vector of real numbers to simulate Bessel bridge} } \value{ matrix of the simulated layered Brownian bridge path, first row is points X, second row are corresponding times } \description{ This function simulates a layered Brownian Bridge given a Bessel layer, at given times } \examples{ # simulate Bessel layer bes_layer <- simulate_bessel_layer(x = 0, y = 0, s = 0, t = 1, a = seq(0.1, 1.0, 0.1)) # simulate layered Brownian bridge simulate_layered_brownian_bridge_bessel(x = 0, y = 0, s = 0, t = 1, a = bes_layer$a, l = bes_layer$l, sim_times = seq(0.2, 0.8, 0.2)) }
/man/simulate_layered_brownian_bridge_bessel.Rd
no_license
rchan26/RlayeredBB
R
false
true
1,231
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sim_bessel_layers.R \name{simulate_layered_brownian_bridge_bessel} \alias{simulate_layered_brownian_bridge_bessel} \title{Layered Brownian Bridge sampler} \usage{ simulate_layered_brownian_bridge_bessel(x, y, s, t, a, l, sim_times) } \arguments{ \item{x}{start value of Brownian bridge} \item{y}{end value of Brownian bridge} \item{s}{start value of Brownian bridge} \item{t}{end value of Brownian bridge} \item{a}{vector/sequence of numbers} \item{l}{integer number denoting Bessel layer, i.e. Brownian bridge is contained in [min(x,y)-a[l], max(x,y)+a[l]]} \item{sim_times}{vector of real numbers to simulate Bessel bridge} } \value{ matrix of the simulated layered Brownian bridge path, first row is points X, second row are corresponding times } \description{ This function simulates a layered Brownian Bridge given a Bessel layer, at given times } \examples{ # simulate Bessel layer bes_layer <- simulate_bessel_layer(x = 0, y = 0, s = 0, t = 1, a = seq(0.1, 1.0, 0.1)) # simulate layered Brownian bridge simulate_layered_brownian_bridge_bessel(x = 0, y = 0, s = 0, t = 1, a = bes_layer$a, l = bes_layer$l, sim_times = seq(0.2, 0.8, 0.2)) }
source("knnPerformanceNoCV.R") DPI_list = c(100,200,300); k_list = seq(1,40,1); GroupNumber = 2; MemberNumber = 2; sigma_list = c(1.5,2.5,3.5); n_list = seq(500,4000,500); DPI_tests <- list() i=1 DPI=DPI_list[i] sigma=sigma_list[i] DataList = loadSinglePersonsData(DPI,GroupNumber,MemberNumber,sigma) for(j in 1:10) { if(j == 1) { data = DataList[[j]]; dataClass = rep(j-1,nrow(DataList[[j]])); } else { data = rbind(data, DataList[[j]]); dataClass = append(dataClass, rep(j-1, nrow(DataList[[j]]) ) ); } } dataClassF = factor(dataClass) remove(DataList); gc(); knnTest=knnPerformanceOnTrainingSetNoCV(data,dataClassF,k_list) knnTestFilenamePF=paste(c("../data/knnTrainingSetPerformance-",GroupNumber,"-",MemberNumber,"-",DPI,"-",sigma),collapse="") save(knnTest,file=paste(c(knnTestFilenamePF,".RData"),collapse="")) load(paste(c(knnTestFilenamePF,".RData"),collapse="")) acc = vector(mode="double",length=length(k_list)) acclow = vector(mode="double",length=length(k_list)) acchigh = vector(mode="double",length=length(k_list)) for(i in 1:(length(k_list))) { acc[i]=knnTest$knnConfusionMatrix[[i]]$overall[["Accuracy"]] acclow[i]=knnTest$knnConfusionMatrix[[i]]$overall[["AccuracyLower"]] acchigh[i]=knnTest$knnConfusionMatrix[[i]]$overall[["AccuracyUpper"]] } knnTestResults=data.frame(k=k_list,Accuracy=acc,Accuracy95Low=acclow,Accuracy95High=acchigh) write.csv(x=knnTestResults,file=paste(c(knnTestFilenamePF,".csv"),collapse=""),row.names = FALSE)
/Rcode/test-k-NN-trainingSetPerformance.R
no_license
madsherlock/SML-F16
R
false
false
1,530
r
source("knnPerformanceNoCV.R") DPI_list = c(100,200,300); k_list = seq(1,40,1); GroupNumber = 2; MemberNumber = 2; sigma_list = c(1.5,2.5,3.5); n_list = seq(500,4000,500); DPI_tests <- list() i=1 DPI=DPI_list[i] sigma=sigma_list[i] DataList = loadSinglePersonsData(DPI,GroupNumber,MemberNumber,sigma) for(j in 1:10) { if(j == 1) { data = DataList[[j]]; dataClass = rep(j-1,nrow(DataList[[j]])); } else { data = rbind(data, DataList[[j]]); dataClass = append(dataClass, rep(j-1, nrow(DataList[[j]]) ) ); } } dataClassF = factor(dataClass) remove(DataList); gc(); knnTest=knnPerformanceOnTrainingSetNoCV(data,dataClassF,k_list) knnTestFilenamePF=paste(c("../data/knnTrainingSetPerformance-",GroupNumber,"-",MemberNumber,"-",DPI,"-",sigma),collapse="") save(knnTest,file=paste(c(knnTestFilenamePF,".RData"),collapse="")) load(paste(c(knnTestFilenamePF,".RData"),collapse="")) acc = vector(mode="double",length=length(k_list)) acclow = vector(mode="double",length=length(k_list)) acchigh = vector(mode="double",length=length(k_list)) for(i in 1:(length(k_list))) { acc[i]=knnTest$knnConfusionMatrix[[i]]$overall[["Accuracy"]] acclow[i]=knnTest$knnConfusionMatrix[[i]]$overall[["AccuracyLower"]] acchigh[i]=knnTest$knnConfusionMatrix[[i]]$overall[["AccuracyUpper"]] } knnTestResults=data.frame(k=k_list,Accuracy=acc,Accuracy95Low=acclow,Accuracy95High=acchigh) write.csv(x=knnTestResults,file=paste(c(knnTestFilenamePF,".csv"),collapse=""),row.names = FALSE)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ordinal_ridge.R \name{evaluateRanking} \alias{evaluateRanking} \title{Evaluate rank prediction performance} \usage{ evaluateRanking(scores, labels) } \arguments{ \item{scores}{Numeric vector of a score ranking the observations in the predicted order} \item{labels}{Ordered factor vector of true labels for each observation} } \value{ A score between 0 and 1. Higher scores mean better prediction performance } \description{ Evaluate rank prediction performance }
/man/evaluateRanking.Rd
permissive
ArtemSokolov/ordinalRidge
R
false
true
542
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ordinal_ridge.R \name{evaluateRanking} \alias{evaluateRanking} \title{Evaluate rank prediction performance} \usage{ evaluateRanking(scores, labels) } \arguments{ \item{scores}{Numeric vector of a score ranking the observations in the predicted order} \item{labels}{Ordered factor vector of true labels for each observation} } \value{ A score between 0 and 1. Higher scores mean better prediction performance } \description{ Evaluate rank prediction performance }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/pkg_version.R \name{pkg_version} \alias{pkg_version} \title{Retrieve Package version} \usage{ pkg_version(pkgs_col) } \arguments{ \item{pkgs_col}{Package name.} } \value{ A character vector with the package version. } \description{ Internal helper function. }
/man/pkg_version.Rd
permissive
luisDVA/annotater
R
false
true
338
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/pkg_version.R \name{pkg_version} \alias{pkg_version} \title{Retrieve Package version} \usage{ pkg_version(pkgs_col) } \arguments{ \item{pkgs_col}{Package name.} } \value{ A character vector with the package version. } \description{ Internal helper function. }
options( show.error.messages=F, error = function () { cat( geterrmessage(), file=stderr() ); q( "no", 1, F ) } ) # we need that to not crash galaxy with an UTF8 error on German LC settings. loc <- Sys.setlocale("LC_MESSAGES", "en_US.UTF-8") suppressPackageStartupMessages({ library(ChIPseeker) library(GenomicFeatures) library(rtracklayer) library(optparse) }) option_list <- list( make_option(c("-i","--infile"), type="character", help="Peaks file to be annotated"), make_option(c("-G","--gtf"), type="character", help="GTF to create TxDb."), make_option(c("-u","--upstream"), type="integer", help="TSS upstream region"), make_option(c("-d","--downstream"), type="integer", help="TSS downstream region"), make_option(c("-F","--flankgeneinfo"), type="logical", help="Add flanking gene info"), make_option(c("-D","--flankgenedist"), type="integer", help="Flanking gene distance"), make_option(c("-f","--format"), type="character", help="Output format (interval or tabular)."), make_option(c("-p","--plots"), type="logical", help="PDF of plots."), make_option(c("-r","--rdata"), type="logical", help="Output RData file.") ) parser <- OptionParser(usage = "%prog [options] file", option_list=option_list) args = parse_args(parser) peaks = args$infile gtf = args$gtf up = args$upstream down = args$downstream format = args$format peaks <- readPeakFile(peaks) # Make TxDb from GTF txdb <- makeTxDbFromGFF(gtf, format="gtf") if (!is.null(args$flankgeneinfo)) { peakAnno <- annotatePeak(peaks, TxDb=txdb, tssRegion=c(-up, down), addFlankGeneInfo=args$flankgeneinfo, flankDistance=args$flankgenedist) } else { peakAnno <- annotatePeak(peaks, TxDb=txdb, tssRegion=c(-up, down)) } # Add gene name features <- import(gtf, format="gtf") ann <- unique(mcols(features)[, c("gene_id", "gene_name")]) res <- as.data.frame(peakAnno) res <- merge(res, ann, by.x="geneId", by.y="gene_id") names(res)[names(res) == "gene_name"] <- "geneName" #Extract metadata cols, 1st is geneId, rest should be from col 7 to end metacols <- res[, c(7:ncol(res), 1)] # Convert from 1-based to 0-based format if (format == "interval") { metacols <- apply(as.data.frame(metacols), 1, function(col) paste(col, collapse="|")) resout <- data.frame(Chrom=res$seqnames, Start=res$start - 1, End=res$end, Comment=metacols) } else { resout <- data.frame(Chrom=res$seqnames, Start=res$start - 1, End=res$end, metacols) } write.table(resout, file="out.tab", sep="\t", row.names=FALSE, quote=FALSE) if (!is.null(args$plots)) { pdf("out.pdf", width=14) plotAnnoPie(peakAnno) plotAnnoBar(peakAnno) vennpie(peakAnno) upsetplot(peakAnno) plotDistToTSS(peakAnno, title="Distribution of transcription factor-binding loci\nrelative to TSS") dev.off() } ## Output RData file if (!is.null(args$rdata)) { save.image(file = "ChIPseeker_analysis.RData") }
/tools/chipseeker/chipseeker.R
no_license
wm75/galaxytools
R
false
false
3,034
r
options( show.error.messages=F, error = function () { cat( geterrmessage(), file=stderr() ); q( "no", 1, F ) } ) # we need that to not crash galaxy with an UTF8 error on German LC settings. loc <- Sys.setlocale("LC_MESSAGES", "en_US.UTF-8") suppressPackageStartupMessages({ library(ChIPseeker) library(GenomicFeatures) library(rtracklayer) library(optparse) }) option_list <- list( make_option(c("-i","--infile"), type="character", help="Peaks file to be annotated"), make_option(c("-G","--gtf"), type="character", help="GTF to create TxDb."), make_option(c("-u","--upstream"), type="integer", help="TSS upstream region"), make_option(c("-d","--downstream"), type="integer", help="TSS downstream region"), make_option(c("-F","--flankgeneinfo"), type="logical", help="Add flanking gene info"), make_option(c("-D","--flankgenedist"), type="integer", help="Flanking gene distance"), make_option(c("-f","--format"), type="character", help="Output format (interval or tabular)."), make_option(c("-p","--plots"), type="logical", help="PDF of plots."), make_option(c("-r","--rdata"), type="logical", help="Output RData file.") ) parser <- OptionParser(usage = "%prog [options] file", option_list=option_list) args = parse_args(parser) peaks = args$infile gtf = args$gtf up = args$upstream down = args$downstream format = args$format peaks <- readPeakFile(peaks) # Make TxDb from GTF txdb <- makeTxDbFromGFF(gtf, format="gtf") if (!is.null(args$flankgeneinfo)) { peakAnno <- annotatePeak(peaks, TxDb=txdb, tssRegion=c(-up, down), addFlankGeneInfo=args$flankgeneinfo, flankDistance=args$flankgenedist) } else { peakAnno <- annotatePeak(peaks, TxDb=txdb, tssRegion=c(-up, down)) } # Add gene name features <- import(gtf, format="gtf") ann <- unique(mcols(features)[, c("gene_id", "gene_name")]) res <- as.data.frame(peakAnno) res <- merge(res, ann, by.x="geneId", by.y="gene_id") names(res)[names(res) == "gene_name"] <- "geneName" #Extract metadata cols, 1st is geneId, rest should be from col 7 to end metacols <- res[, c(7:ncol(res), 1)] # Convert from 1-based to 0-based format if (format == "interval") { metacols <- apply(as.data.frame(metacols), 1, function(col) paste(col, collapse="|")) resout <- data.frame(Chrom=res$seqnames, Start=res$start - 1, End=res$end, Comment=metacols) } else { resout <- data.frame(Chrom=res$seqnames, Start=res$start - 1, End=res$end, metacols) } write.table(resout, file="out.tab", sep="\t", row.names=FALSE, quote=FALSE) if (!is.null(args$plots)) { pdf("out.pdf", width=14) plotAnnoPie(peakAnno) plotAnnoBar(peakAnno) vennpie(peakAnno) upsetplot(peakAnno) plotDistToTSS(peakAnno, title="Distribution of transcription factor-binding loci\nrelative to TSS") dev.off() } ## Output RData file if (!is.null(args$rdata)) { save.image(file = "ChIPseeker_analysis.RData") }
## Kaggle - NIPS 2015 Papers # Packages library(readr) library(dplyr) # Read input data authors = read_csv("input/Authors.csv") paperAuthors = read_csv("input/PaperAuthors.csv") papers = read_csv("input/Papers.csv") #Look at type of events at NIPS table(papers$EventType) #Function to find last name for each row findLastName = function(fullname){ return(fullname[length(fullname)]) } ## ## Check last names for authors ## #Check last names authorNames = strsplit(authors$Name, " ") lastNames = lapply(authorNames, findLastName) lastNames = as.character(lastNames) #Count number of each last name lastNamesCount = as.data.frame(table(lastNames)) lastNamesCount = lastNamesCount[order(lastNamesCount$Freq),] ## ## Check last name counts for authors linked to papers ## #Find who wrote papers publishers = merge(authors, paperAuthors, by.x = "Id", by.y="AuthorId") #Check last names authorNames = strsplit(publishers$Name, " ") lastNamesPub = lapply(authorNames, findLastName) lastNamesPub = as.character(lastNamesPub) #Count number of each last name lastNamesPubCount = as.data.frame(table(lastNamesPub)) lastNamesPubCount = lastNamesPubCount[order(lastNamesPubCount$Freq),]
/NIPS 2015 Papers/exploratory.R
no_license
Anithaponnuru/Kaggle
R
false
false
1,188
r
## Kaggle - NIPS 2015 Papers # Packages library(readr) library(dplyr) # Read input data authors = read_csv("input/Authors.csv") paperAuthors = read_csv("input/PaperAuthors.csv") papers = read_csv("input/Papers.csv") #Look at type of events at NIPS table(papers$EventType) #Function to find last name for each row findLastName = function(fullname){ return(fullname[length(fullname)]) } ## ## Check last names for authors ## #Check last names authorNames = strsplit(authors$Name, " ") lastNames = lapply(authorNames, findLastName) lastNames = as.character(lastNames) #Count number of each last name lastNamesCount = as.data.frame(table(lastNames)) lastNamesCount = lastNamesCount[order(lastNamesCount$Freq),] ## ## Check last name counts for authors linked to papers ## #Find who wrote papers publishers = merge(authors, paperAuthors, by.x = "Id", by.y="AuthorId") #Check last names authorNames = strsplit(publishers$Name, " ") lastNamesPub = lapply(authorNames, findLastName) lastNamesPub = as.character(lastNamesPub) #Count number of each last name lastNamesPubCount = as.data.frame(table(lastNamesPub)) lastNamesPubCount = lastNamesPubCount[order(lastNamesPubCount$Freq),]
source("2__scripts/1__R/3__Release/RTools.R") Instal_Required("data.table") Instal_Required("ade4") Instal_Required("tree") Instal_Required("lda") Instal_Required("ggplot2") Instal_Required("randomForest") #setwd(dir = "C:/Users/felix.rougier/Documents/Challenge/DataScienceNet/maif/") maif_train <- fread("1__data/1__input/Brut_Train.csv", header=T) maif_test <- fread("1__data/1__input/Brut_Test.csv", header=T) # analyse de la donn?es crm # peut-on l'utiliser pour obtenir facilement le prix d'achat de base : # distribution de CRM: d <- density(maif_train$crm) plot(d, col='red') lines(density(maif_test$crm), col='blue') hist(maif_train$crm, freq=F, ylim=c(0,0.09), main="R?partition de CRM") lines(density(maif_train$crm), col='red') t <- round(100*table(maif_train$crm)/nrow(maif_train),2) t summary(maif_train$crm) # va jusqu'? 270 mais cas tr?s particuliers : # moins de 0.01% de valeurs au dessus de 195 # comparaison des prix bruts et des prix finaux # prime totale d <- maif_train[,.(crm,prime_tot_ttc)] d plot(d$crm,d$prime_tot_ttc) # prime brute avant crm d[,prime_brute:=100*prime_tot_ttc/crm] plot(d$crm,d$prime_brute) # calcul des moyennes d[,mean_prime_tot:=mean(prime_tot_ttc), by='crm'] d[,mean_prime_brute:=mean(prime_brute), by='crm'] # repr?sentation graphique d2 <- unique(d[,.(crm,mean_prime_tot,mean_prime_brute)]) setkey(d2,crm) plot(d2$crm, d2$mean_prime_tot , type='b', col='blue', ylim=c(0,1300)) points(d2$crm, d2$mean_prime_brute , type='b', col='red') # test d2[,prime_mean:=crm*mean_prime_tot/100] d2 points(d2$crm,d2$prime_mean, type='b', col='green') # peut-?tre que le facteur d'application du crm n'est pas exactement prix*crm/100 # on va faire une r?gression lin?aire pour d?terminer le rapport entre le crm e le prix # sur les moyennes des prix (non pond?r?) mod1 <- lm(d2$mean_prime_tot~d2$crm) summary(mod1) # sur l'ensemble des prix mod2 <- lm(maif_train$prime_tot_ttc~maif_train$crm) summary(mod2) # mod3 <- lm( rep(m,300000) ~ maif_train$prime_tot_ttc * maif_train$crm -1 ) summary(mod3) # ne fontionne pas # on va consid?rer que le crm s'applique bien comme un bonus malus et qu'on retrouve le prix brut de : # Prix de Base = prime_totale_ttc * 100 / CRM
/2__scripts/1__R/1__AD/AD_crm.R
no_license
romainjouen/KaggleMAIF
R
false
false
2,251
r
source("2__scripts/1__R/3__Release/RTools.R") Instal_Required("data.table") Instal_Required("ade4") Instal_Required("tree") Instal_Required("lda") Instal_Required("ggplot2") Instal_Required("randomForest") #setwd(dir = "C:/Users/felix.rougier/Documents/Challenge/DataScienceNet/maif/") maif_train <- fread("1__data/1__input/Brut_Train.csv", header=T) maif_test <- fread("1__data/1__input/Brut_Test.csv", header=T) # analyse de la donn?es crm # peut-on l'utiliser pour obtenir facilement le prix d'achat de base : # distribution de CRM: d <- density(maif_train$crm) plot(d, col='red') lines(density(maif_test$crm), col='blue') hist(maif_train$crm, freq=F, ylim=c(0,0.09), main="R?partition de CRM") lines(density(maif_train$crm), col='red') t <- round(100*table(maif_train$crm)/nrow(maif_train),2) t summary(maif_train$crm) # va jusqu'? 270 mais cas tr?s particuliers : # moins de 0.01% de valeurs au dessus de 195 # comparaison des prix bruts et des prix finaux # prime totale d <- maif_train[,.(crm,prime_tot_ttc)] d plot(d$crm,d$prime_tot_ttc) # prime brute avant crm d[,prime_brute:=100*prime_tot_ttc/crm] plot(d$crm,d$prime_brute) # calcul des moyennes d[,mean_prime_tot:=mean(prime_tot_ttc), by='crm'] d[,mean_prime_brute:=mean(prime_brute), by='crm'] # repr?sentation graphique d2 <- unique(d[,.(crm,mean_prime_tot,mean_prime_brute)]) setkey(d2,crm) plot(d2$crm, d2$mean_prime_tot , type='b', col='blue', ylim=c(0,1300)) points(d2$crm, d2$mean_prime_brute , type='b', col='red') # test d2[,prime_mean:=crm*mean_prime_tot/100] d2 points(d2$crm,d2$prime_mean, type='b', col='green') # peut-?tre que le facteur d'application du crm n'est pas exactement prix*crm/100 # on va faire une r?gression lin?aire pour d?terminer le rapport entre le crm e le prix # sur les moyennes des prix (non pond?r?) mod1 <- lm(d2$mean_prime_tot~d2$crm) summary(mod1) # sur l'ensemble des prix mod2 <- lm(maif_train$prime_tot_ttc~maif_train$crm) summary(mod2) # mod3 <- lm( rep(m,300000) ~ maif_train$prime_tot_ttc * maif_train$crm -1 ) summary(mod3) # ne fontionne pas # on va consid?rer que le crm s'applique bien comme un bonus malus et qu'on retrouve le prix brut de : # Prix de Base = prime_totale_ttc * 100 / CRM
source('/Users/zeynepenkavi/Dropbox/PoldrackLab/SRO_Retest_Analyses/code/figure_scripts/figure_res_wrapper.R') if(!exists('rel_df')){ source('/Users/zeynepenkavi/Dropbox/PoldrackLab/SRO_Retest_Analyses/code/workspace_scripts/subject_data.R') source('/Users/zeynepenkavi/Dropbox/PoldrackLab/SRO_Retest_Analyses/code/helper_functions/make_rel_df.R') rel_df = make_rel_df(t1_df = test_data, t2_df = retest_data, metrics = c('spearman', 'icc', 'pearson', 'var_breakdown', 'partial_eta', 'sem')) rel_df$task = 'task' rel_df[grep('survey', rel_df$dv), 'task'] = 'survey' rel_df[grep('holt', rel_df$dv), 'task'] = "task" rel_df = rel_df %>% select(dv, task, spearman, icc, pearson, partial_eta, sem, var_subs, var_ind, var_resid) } tmp = rel_df %>% mutate(var_subs_pct = var_subs/(var_subs+var_ind+var_resid)*100, var_ind_pct = var_ind/(var_subs+var_ind+var_resid)*100, var_resid_pct = var_resid/(var_subs+var_ind+var_resid)*100) %>% select(dv, task, var_subs_pct, var_ind_pct, var_resid_pct) %>% mutate(dv = factor(dv, levels = dv[order(task)])) %>% separate(dv, c("task_group", "var"), sep="\\.",remove=FALSE,extra="merge") %>% mutate(task_group = factor(task_group, levels = task_group[order(task)])) %>% arrange(task_group, var_subs_pct) %>% mutate(rank = row_number()) %>% arrange(task, task_group, rank) %>% gather(key, value, -dv, -task_group, -var, -task, -rank) %>% ungroup()%>% mutate(task_group = gsub("_", " ", task_group), var = gsub("_", " ", var)) %>% mutate(task_group = ifelse(task_group == "psychological refractory period two choices", "psychological refractory period", ifelse(task_group == "angling risk task always sunny", "angling risk task",task_group))) %>% mutate(task_group = gsub("survey", "", task_group)) %>% filter(task=="task", !grepl("EZ|hddm", dv))%>% arrange(task_group, rank) labels = tmp %>% distinct(dv, .keep_all=T) p1 <- tmp %>% ggplot(aes(x=factor(rank), y=value, fill=factor(key, levels = c("var_resid_pct", "var_ind_pct", "var_subs_pct"))))+ geom_bar(stat='identity', alpha = 0.75, color='#00BFC4')+ scale_x_discrete(breaks = labels$rank, labels = labels$var)+ coord_flip()+ facet_grid(task_group~., switch = "y", scales = "free_y", space = "free_y") + theme(panel.spacing = unit(0.5, "lines"), strip.placement = "outside", strip.text.y = element_text(angle=180), panel.background = element_rect(fill = NA), panel.grid.major = element_line(colour = "grey85"), legend.position = 'bottom')+ theme(legend.title = element_blank())+ scale_fill_manual(breaks = c("var_subs_pct", "var_ind_pct", "var_resid_pct"), labels = c("Variance between individuals", "Variance between sessions", "Error variance"), values=c("grey65", "grey45", "grey25"))+ ylab("")+ xlab("") tmp = rel_df %>% mutate(var_subs_pct = var_subs/(var_subs+var_ind+var_resid)*100, var_ind_pct = var_ind/(var_subs+var_ind+var_resid)*100, var_resid_pct = var_resid/(var_subs+var_ind+var_resid)*100) %>% select(dv, task, var_subs_pct, var_ind_pct, var_resid_pct) %>% mutate(dv = factor(dv, levels = dv[order(task)])) %>% separate(dv, c("task_group", "var"), sep="\\.",remove=FALSE,extra="merge") %>% mutate(task_group = factor(task_group, levels = task_group[order(task)])) %>% arrange(task_group, var_subs_pct) %>% mutate(rank = row_number()) %>% arrange(task, task_group, rank) %>% gather(key, value, -dv, -task_group, -var, -task, -rank) %>% ungroup()%>% mutate(task_group = gsub("_", " ", task_group), var = gsub("_", " ", var)) %>% mutate(task_group = ifelse(task_group == "psychological refractory period two choices", "psychological refractory period", ifelse(task_group == "angling risk task always sunny", "angling risk task",task_group))) %>% mutate(task_group = gsub("survey", "", task_group)) %>% filter(task=="survey")%>% arrange(task_group, rank) labels = tmp %>% distinct(dv, .keep_all=T) p2 <- tmp %>% ggplot(aes(x=factor(rank), y=value, fill=factor(key, levels = c("var_resid_pct", "var_ind_pct", "var_subs_pct"))))+ geom_bar(stat='identity', alpha = 0.75)+ geom_bar(stat='identity', color='#F8766D', show.legend=FALSE)+ scale_x_discrete(breaks = labels$rank, labels = labels$var)+ coord_flip()+ facet_grid(task_group~., switch = "y", scales = "free_y", space = "free_y") + theme(panel.spacing = unit(0.5, "lines"), strip.placement = "outside", strip.text.y = element_text(angle=180), panel.background = element_rect(fill = NA), panel.grid.major = element_line(colour = "grey85"), legend.position = 'bottom')+ theme(legend.title = element_blank())+ scale_fill_manual(breaks = c("var_subs_pct", "var_ind_pct", "var_resid_pct"), labels = c("Variance between individuals", "Variance between sessions", "Error variance"), values=c("grey65", "grey45", "grey25"))+ ylab("")+ xlab("") mylegend<-g_legend(p2) p3 <- arrangeGrob(arrangeGrob(p1 +theme(legend.position="none"), p2 + theme(legend.position="none"), nrow=1), mylegend, nrow=2,heights=c(10, 1)) ggsave(paste0('Variance_Breakdown_Plot.', out_device), plot = p3, device = out_device, path = fig_path, width = 24, height = 20, units = "in", dpi = img_dpi) rm(tmp, labels, p1, p2 , p3)
/code/figure_scripts/Variance_Breakdown_Plot.R
no_license
zenkavi/SRO_Retest_Analyses
R
false
false
5,646
r
source('/Users/zeynepenkavi/Dropbox/PoldrackLab/SRO_Retest_Analyses/code/figure_scripts/figure_res_wrapper.R') if(!exists('rel_df')){ source('/Users/zeynepenkavi/Dropbox/PoldrackLab/SRO_Retest_Analyses/code/workspace_scripts/subject_data.R') source('/Users/zeynepenkavi/Dropbox/PoldrackLab/SRO_Retest_Analyses/code/helper_functions/make_rel_df.R') rel_df = make_rel_df(t1_df = test_data, t2_df = retest_data, metrics = c('spearman', 'icc', 'pearson', 'var_breakdown', 'partial_eta', 'sem')) rel_df$task = 'task' rel_df[grep('survey', rel_df$dv), 'task'] = 'survey' rel_df[grep('holt', rel_df$dv), 'task'] = "task" rel_df = rel_df %>% select(dv, task, spearman, icc, pearson, partial_eta, sem, var_subs, var_ind, var_resid) } tmp = rel_df %>% mutate(var_subs_pct = var_subs/(var_subs+var_ind+var_resid)*100, var_ind_pct = var_ind/(var_subs+var_ind+var_resid)*100, var_resid_pct = var_resid/(var_subs+var_ind+var_resid)*100) %>% select(dv, task, var_subs_pct, var_ind_pct, var_resid_pct) %>% mutate(dv = factor(dv, levels = dv[order(task)])) %>% separate(dv, c("task_group", "var"), sep="\\.",remove=FALSE,extra="merge") %>% mutate(task_group = factor(task_group, levels = task_group[order(task)])) %>% arrange(task_group, var_subs_pct) %>% mutate(rank = row_number()) %>% arrange(task, task_group, rank) %>% gather(key, value, -dv, -task_group, -var, -task, -rank) %>% ungroup()%>% mutate(task_group = gsub("_", " ", task_group), var = gsub("_", " ", var)) %>% mutate(task_group = ifelse(task_group == "psychological refractory period two choices", "psychological refractory period", ifelse(task_group == "angling risk task always sunny", "angling risk task",task_group))) %>% mutate(task_group = gsub("survey", "", task_group)) %>% filter(task=="task", !grepl("EZ|hddm", dv))%>% arrange(task_group, rank) labels = tmp %>% distinct(dv, .keep_all=T) p1 <- tmp %>% ggplot(aes(x=factor(rank), y=value, fill=factor(key, levels = c("var_resid_pct", "var_ind_pct", "var_subs_pct"))))+ geom_bar(stat='identity', alpha = 0.75, color='#00BFC4')+ scale_x_discrete(breaks = labels$rank, labels = labels$var)+ coord_flip()+ facet_grid(task_group~., switch = "y", scales = "free_y", space = "free_y") + theme(panel.spacing = unit(0.5, "lines"), strip.placement = "outside", strip.text.y = element_text(angle=180), panel.background = element_rect(fill = NA), panel.grid.major = element_line(colour = "grey85"), legend.position = 'bottom')+ theme(legend.title = element_blank())+ scale_fill_manual(breaks = c("var_subs_pct", "var_ind_pct", "var_resid_pct"), labels = c("Variance between individuals", "Variance between sessions", "Error variance"), values=c("grey65", "grey45", "grey25"))+ ylab("")+ xlab("") tmp = rel_df %>% mutate(var_subs_pct = var_subs/(var_subs+var_ind+var_resid)*100, var_ind_pct = var_ind/(var_subs+var_ind+var_resid)*100, var_resid_pct = var_resid/(var_subs+var_ind+var_resid)*100) %>% select(dv, task, var_subs_pct, var_ind_pct, var_resid_pct) %>% mutate(dv = factor(dv, levels = dv[order(task)])) %>% separate(dv, c("task_group", "var"), sep="\\.",remove=FALSE,extra="merge") %>% mutate(task_group = factor(task_group, levels = task_group[order(task)])) %>% arrange(task_group, var_subs_pct) %>% mutate(rank = row_number()) %>% arrange(task, task_group, rank) %>% gather(key, value, -dv, -task_group, -var, -task, -rank) %>% ungroup()%>% mutate(task_group = gsub("_", " ", task_group), var = gsub("_", " ", var)) %>% mutate(task_group = ifelse(task_group == "psychological refractory period two choices", "psychological refractory period", ifelse(task_group == "angling risk task always sunny", "angling risk task",task_group))) %>% mutate(task_group = gsub("survey", "", task_group)) %>% filter(task=="survey")%>% arrange(task_group, rank) labels = tmp %>% distinct(dv, .keep_all=T) p2 <- tmp %>% ggplot(aes(x=factor(rank), y=value, fill=factor(key, levels = c("var_resid_pct", "var_ind_pct", "var_subs_pct"))))+ geom_bar(stat='identity', alpha = 0.75)+ geom_bar(stat='identity', color='#F8766D', show.legend=FALSE)+ scale_x_discrete(breaks = labels$rank, labels = labels$var)+ coord_flip()+ facet_grid(task_group~., switch = "y", scales = "free_y", space = "free_y") + theme(panel.spacing = unit(0.5, "lines"), strip.placement = "outside", strip.text.y = element_text(angle=180), panel.background = element_rect(fill = NA), panel.grid.major = element_line(colour = "grey85"), legend.position = 'bottom')+ theme(legend.title = element_blank())+ scale_fill_manual(breaks = c("var_subs_pct", "var_ind_pct", "var_resid_pct"), labels = c("Variance between individuals", "Variance between sessions", "Error variance"), values=c("grey65", "grey45", "grey25"))+ ylab("")+ xlab("") mylegend<-g_legend(p2) p3 <- arrangeGrob(arrangeGrob(p1 +theme(legend.position="none"), p2 + theme(legend.position="none"), nrow=1), mylegend, nrow=2,heights=c(10, 1)) ggsave(paste0('Variance_Breakdown_Plot.', out_device), plot = p3, device = out_device, path = fig_path, width = 24, height = 20, units = "in", dpi = img_dpi) rm(tmp, labels, p1, p2 , p3)
## Copyright (C) 2019 Prim'Act, Quentin Guibert ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS ## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see <https://www.gnu.org/licenses/>. # Management rules: profit sharing ###-------------------------- # Initialisation ###-------------------------- # Get a object which contains the liability portfolio and related assumptions central <- get(load(paste(racine@address$save_folder$central, "best_estimate.RData", sep = "/"))) ptf_passif <- central@canton@ptf_passif # Current year year <- 1L ###-------------------------- # Asset and liability before profit sharing ###-------------------------- # Liability portfolio at the end of the year before profit sharing # ptf_eoy <- proj_annee_av_pb(an = year, x = ptf_passif, tx_soc = 0.155, coef_inf = 1, list_rd = c(0.02,0.01,0.01,0)) liab_eoy <- viellissement_av_pb(an = year, ptf_passif, coef_inf = 1, list_rd =c(0.02,0.01,0.01,0), tx_soc = 0.155) asset_eoy <- update_PortFin(an = year, ptf_fin, new_mp_ESG = central@canton@mp_esg, flux_milieu = liab_eoy[["flux_milieu"]], flux_fin = liab_eoy[["flux_fin"]]) # Get the updated asset portfolio ptf_fin <- asset_eoy[["ptf"]] # Get the financial incomes and the realized capital gain and loss on bonds income <- asset_eoy[["revenu_fin"]] var_vnc_bond <- asset_eoy[["var_vnc_oblig"]] # Reallocate the asset portfolio asset_realloc <- reallocate(ptf_fin, central@canton@param_alm@ptf_reference, central@canton@param_alm@alloc_cible) # Compute the technical results, including Delta provisions on 'PRE' result_tech <- calc_result_technique(liab_eoy, asset_realloc[["var_pre"]]) print(resultat_tech) # Compute the financial results result_fin <- calc_resultat_fin(income + var_vnc_bond, asset_realloc[["pmvr"]], frais_fin = 0, asset_realloc[["var_rc"]]) # Compute the TRA (return rate on assets according to the Frenc GAAP) tra <- calc_tra(asset_realloc[["plac_moy_vnc"]], result_fin) print(tra) ###-------------------------- # Apply the profit sharing algorithm ###-------------------------- result_revalo <- calc_revalo(central@canton, liab_eoy, tra, asset_realloc[["plac_moy_vnc"]], result_tech) #updated PPB result_revalo$ppb # Profit sharing rate result_revalo$tx_pb # Amont of profil sharing to allocate result_revalo$add_rev_nette_stock # Amount of gain of loss which are be realized for reaching the target revalorisation rate result_revalo$pmvl_liq ###-------------------------- # Explore the profit sharing algorithm with simple examples ###-------------------------- # Step 0: initialisation ###------------------------- # Data tra_1 <- 0.05 tra_2 <- 0.02 tra_3 <- 0.01 tra_4 <- - 0.01 # 4 products and their profit sharing rates pm_moy <- rep(100, 4) tx_pb <- c(0.90, 0.95, 0.97, 1) # Create an initial PPB as nul ppb <- new(Class = "Ppb") ppb@valeur_ppb <- ppb@ppb_debut <- 8 # The initial amount of PPB is equal to 8 ppb@hist_ppb <- rep(1, 8) # This amount have be endowed uniformaly during the last 8 years ppb@seuil_rep <- ppb@seuil_dot <- 0.5 # The PPB can be endowed or ceded until 50% # Assume the loadings are nul tx_enc_moy <- c(0, 0, 0, 0) # Step 1: contractual profit sharing ###------------------------- # Compute the financial result related to the liability # base_fin_1 <- tra_1 * (sum(pm_moy) + ppb["ppb_debut"]) * pm_moy / sum(pm_moy) base_fin_1 <- base_prod_fin(tra_1, pm_moy, ppb) base_fin_2 <- base_prod_fin(tra_2, pm_moy, ppb) base_fin_3 <- base_prod_fin(tra_3, pm_moy, ppb) base_fin_4 <- base_prod_fin(tra_4, pm_moy, ppb) # Revalorisation considering a minimum rate of 1% rev_stock_brut <- pm_moy * 0.01 ch_enc_th <- pm_moy * (1 + 0.01) * tx_enc_moy # Amount of contractual profit sharing considering the minimal rate reval_contr_1 <- pb_contr(base_fin_1$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) reval_contr_2 <- pb_contr(base_fin_2$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) reval_contr_3 <- pb_contr(base_fin_3$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) reval_contr_4 <- pb_contr(base_fin_4$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) # Step 2: TMG ###------------------------- # The PPB can finance the need ralated to the TMG garantee tmg <- 0.02 # High TMG # tmg <- 0 # No TMG bes_tmg_stock <- pm_moy * tmg bes_tmg_prest <- pm_moy * 0 # Assumption no TMG on benefits financement_tmg <- finance_tmg(bes_tmg_prest, bes_tmg_stock, ppb) # Update the PPB objet ppb <- financement_tmg[["ppb"]] # Step 3: Regulatory constraints on the PPB ###------------------------- # Regulatory constraint: 8 years for using the PPB ppb_8 <- ppb_8ans(ppb) # Update the PPB objet ppb <- ppb_8[["ppb"]] # Allocate this amount to each product, e.g. with the weights in terms of MP som <- sum(pm_moy) ppb8_ind <- ppb_8$ppb_8 * pm_moy / som # Step 4: Reach the target rate ###------------------------- # Assume the insured expects a rate on return of 3.00% target_rate <- 0.03 bes_tx_cible <- pm_moy * target_rate # Option #1 Use the PPB for reaching this target tx_cibl_ppb_1 <- finance_cible_ppb(bes_tx_cible, reval_contr_1$rev_stock_nette_contr, ppb, ppb8_ind) tx_cibl_ppb_2 <- finance_cible_ppb(bes_tx_cible, reval_contr_2$rev_stock_nette_contr, ppb, ppb8_ind) tx_cibl_ppb_3 <- finance_cible_ppb(bes_tx_cible, reval_contr_3$rev_stock_nette_contr, ppb, ppb8_ind) tx_cibl_ppb_4 <- finance_cible_ppb(bes_tx_cible, reval_contr_4$rev_stock_nette_contr, ppb, ppb8_ind) # Mise a jour de la PPB, e.g. in case #1 ppb <- tx_cibl_ppb_1$ppb # Option #2 Sell shares for reaching this target # Assume the amount of unrealized gain of shares which can be sold is limited to 5 seuil_pmvl <- 5 # Revalorisation after selling shares tx_cibl_pmvl_1 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_1$rev_stock_nette, base_fin_1$base_prod_fin, seuil_pmvl, tx_pb) tx_cibl_pmvl_2 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_2$rev_stock_nette, base_fin_2$base_prod_fin, seuil_pmvl, tx_pb) tx_cibl_pmvl_3 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_3$rev_stock_nette, base_fin_3$base_prod_fin, seuil_pmvl, tx_pb) tx_cibl_pmvl_4 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_4$rev_stock_nette, base_fin_4$base_prod_fin, seuil_pmvl, tx_pb) # Step 5: Apply the legal constraints on the overall portfolio #--------------------------------------------------------------- # Technical results is zero result_tech <- 0 it_tech <- rev_stock_brut revalo_finale_1 <- finance_contrainte_legale(base_fin_1$base_prod_fin, base_fin_1$base_prod_fin_port, result_tech, it_tech, tx_cibl_pmvl_1$rev_stock_nette, bes_tmg_prest, tx_cibl_ppb_1$dotation, 0, ppb, central@canton@param_revalo) ###-------------------------- # Summary function for launching all the steps over the year ###-------------------------- result_proj_an <-proj_an(x = central@canton, annee_fin = central@param_be@nb_annee, pre_on = T)
/5-profit_sharing.R
no_license
RebeccaWel/Environnement
R
false
false
7,869
r
## Copyright (C) 2019 Prim'Act, Quentin Guibert ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS ## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see <https://www.gnu.org/licenses/>. # Management rules: profit sharing ###-------------------------- # Initialisation ###-------------------------- # Get a object which contains the liability portfolio and related assumptions central <- get(load(paste(racine@address$save_folder$central, "best_estimate.RData", sep = "/"))) ptf_passif <- central@canton@ptf_passif # Current year year <- 1L ###-------------------------- # Asset and liability before profit sharing ###-------------------------- # Liability portfolio at the end of the year before profit sharing # ptf_eoy <- proj_annee_av_pb(an = year, x = ptf_passif, tx_soc = 0.155, coef_inf = 1, list_rd = c(0.02,0.01,0.01,0)) liab_eoy <- viellissement_av_pb(an = year, ptf_passif, coef_inf = 1, list_rd =c(0.02,0.01,0.01,0), tx_soc = 0.155) asset_eoy <- update_PortFin(an = year, ptf_fin, new_mp_ESG = central@canton@mp_esg, flux_milieu = liab_eoy[["flux_milieu"]], flux_fin = liab_eoy[["flux_fin"]]) # Get the updated asset portfolio ptf_fin <- asset_eoy[["ptf"]] # Get the financial incomes and the realized capital gain and loss on bonds income <- asset_eoy[["revenu_fin"]] var_vnc_bond <- asset_eoy[["var_vnc_oblig"]] # Reallocate the asset portfolio asset_realloc <- reallocate(ptf_fin, central@canton@param_alm@ptf_reference, central@canton@param_alm@alloc_cible) # Compute the technical results, including Delta provisions on 'PRE' result_tech <- calc_result_technique(liab_eoy, asset_realloc[["var_pre"]]) print(resultat_tech) # Compute the financial results result_fin <- calc_resultat_fin(income + var_vnc_bond, asset_realloc[["pmvr"]], frais_fin = 0, asset_realloc[["var_rc"]]) # Compute the TRA (return rate on assets according to the Frenc GAAP) tra <- calc_tra(asset_realloc[["plac_moy_vnc"]], result_fin) print(tra) ###-------------------------- # Apply the profit sharing algorithm ###-------------------------- result_revalo <- calc_revalo(central@canton, liab_eoy, tra, asset_realloc[["plac_moy_vnc"]], result_tech) #updated PPB result_revalo$ppb # Profit sharing rate result_revalo$tx_pb # Amont of profil sharing to allocate result_revalo$add_rev_nette_stock # Amount of gain of loss which are be realized for reaching the target revalorisation rate result_revalo$pmvl_liq ###-------------------------- # Explore the profit sharing algorithm with simple examples ###-------------------------- # Step 0: initialisation ###------------------------- # Data tra_1 <- 0.05 tra_2 <- 0.02 tra_3 <- 0.01 tra_4 <- - 0.01 # 4 products and their profit sharing rates pm_moy <- rep(100, 4) tx_pb <- c(0.90, 0.95, 0.97, 1) # Create an initial PPB as nul ppb <- new(Class = "Ppb") ppb@valeur_ppb <- ppb@ppb_debut <- 8 # The initial amount of PPB is equal to 8 ppb@hist_ppb <- rep(1, 8) # This amount have be endowed uniformaly during the last 8 years ppb@seuil_rep <- ppb@seuil_dot <- 0.5 # The PPB can be endowed or ceded until 50% # Assume the loadings are nul tx_enc_moy <- c(0, 0, 0, 0) # Step 1: contractual profit sharing ###------------------------- # Compute the financial result related to the liability # base_fin_1 <- tra_1 * (sum(pm_moy) + ppb["ppb_debut"]) * pm_moy / sum(pm_moy) base_fin_1 <- base_prod_fin(tra_1, pm_moy, ppb) base_fin_2 <- base_prod_fin(tra_2, pm_moy, ppb) base_fin_3 <- base_prod_fin(tra_3, pm_moy, ppb) base_fin_4 <- base_prod_fin(tra_4, pm_moy, ppb) # Revalorisation considering a minimum rate of 1% rev_stock_brut <- pm_moy * 0.01 ch_enc_th <- pm_moy * (1 + 0.01) * tx_enc_moy # Amount of contractual profit sharing considering the minimal rate reval_contr_1 <- pb_contr(base_fin_1$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) reval_contr_2 <- pb_contr(base_fin_2$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) reval_contr_3 <- pb_contr(base_fin_3$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) reval_contr_4 <- pb_contr(base_fin_4$base_prod_fin, tx_pb, rev_stock_brut, ch_enc_th, tx_enc_moy) # Step 2: TMG ###------------------------- # The PPB can finance the need ralated to the TMG garantee tmg <- 0.02 # High TMG # tmg <- 0 # No TMG bes_tmg_stock <- pm_moy * tmg bes_tmg_prest <- pm_moy * 0 # Assumption no TMG on benefits financement_tmg <- finance_tmg(bes_tmg_prest, bes_tmg_stock, ppb) # Update the PPB objet ppb <- financement_tmg[["ppb"]] # Step 3: Regulatory constraints on the PPB ###------------------------- # Regulatory constraint: 8 years for using the PPB ppb_8 <- ppb_8ans(ppb) # Update the PPB objet ppb <- ppb_8[["ppb"]] # Allocate this amount to each product, e.g. with the weights in terms of MP som <- sum(pm_moy) ppb8_ind <- ppb_8$ppb_8 * pm_moy / som # Step 4: Reach the target rate ###------------------------- # Assume the insured expects a rate on return of 3.00% target_rate <- 0.03 bes_tx_cible <- pm_moy * target_rate # Option #1 Use the PPB for reaching this target tx_cibl_ppb_1 <- finance_cible_ppb(bes_tx_cible, reval_contr_1$rev_stock_nette_contr, ppb, ppb8_ind) tx_cibl_ppb_2 <- finance_cible_ppb(bes_tx_cible, reval_contr_2$rev_stock_nette_contr, ppb, ppb8_ind) tx_cibl_ppb_3 <- finance_cible_ppb(bes_tx_cible, reval_contr_3$rev_stock_nette_contr, ppb, ppb8_ind) tx_cibl_ppb_4 <- finance_cible_ppb(bes_tx_cible, reval_contr_4$rev_stock_nette_contr, ppb, ppb8_ind) # Mise a jour de la PPB, e.g. in case #1 ppb <- tx_cibl_ppb_1$ppb # Option #2 Sell shares for reaching this target # Assume the amount of unrealized gain of shares which can be sold is limited to 5 seuil_pmvl <- 5 # Revalorisation after selling shares tx_cibl_pmvl_1 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_1$rev_stock_nette, base_fin_1$base_prod_fin, seuil_pmvl, tx_pb) tx_cibl_pmvl_2 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_2$rev_stock_nette, base_fin_2$base_prod_fin, seuil_pmvl, tx_pb) tx_cibl_pmvl_3 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_3$rev_stock_nette, base_fin_3$base_prod_fin, seuil_pmvl, tx_pb) tx_cibl_pmvl_4 <- finance_cible_pmvl(bes_tx_cible, tx_cibl_ppb_4$rev_stock_nette, base_fin_4$base_prod_fin, seuil_pmvl, tx_pb) # Step 5: Apply the legal constraints on the overall portfolio #--------------------------------------------------------------- # Technical results is zero result_tech <- 0 it_tech <- rev_stock_brut revalo_finale_1 <- finance_contrainte_legale(base_fin_1$base_prod_fin, base_fin_1$base_prod_fin_port, result_tech, it_tech, tx_cibl_pmvl_1$rev_stock_nette, bes_tmg_prest, tx_cibl_ppb_1$dotation, 0, ppb, central@canton@param_revalo) ###-------------------------- # Summary function for launching all the steps over the year ###-------------------------- result_proj_an <-proj_an(x = central@canton, annee_fin = central@param_be@nb_annee, pre_on = T)
xdistance <- function(x, y, method = "euclidean") { # calculate cross-dissimilarities between # rows of x and rows of y # returns a nonsymmetric matrix where # d[a, b] is the dissimilarity between # x[a, ] and y[b, ] # Sarah Goslee 2017-02-17, modified from legacy Splus code dated 01/01/01 if(is.null(ncol(x))) { x <- matrix(x, ncol=1) rownames(x) <- seq_len(nrow(x)) } if(is.null(ncol(y))) { y <- matrix(y, ncol=1) rownames(y) <- seq_len(nrow(y)) } if(!(ncol(x) == ncol(y))) stop("Matrices must have the same number of columns\n") x.names <- paste0("x", row.names(x)) y.names <- paste0("y", row.names(y)) x <- as.matrix(x) y <- as.matrix(y) d <- rbind(x, y) d <- full(distance(d, method=method)) d <- d[seq(1, nrow(x)), seq(nrow(x) + 1, nrow(x) + nrow(y)), drop=FALSE] rownames(d) <- x.names colnames(d) <- y.names class(d) <- "xdist" d }
/R/xdistance.R
no_license
cran/ecodist
R
false
false
980
r
xdistance <- function(x, y, method = "euclidean") { # calculate cross-dissimilarities between # rows of x and rows of y # returns a nonsymmetric matrix where # d[a, b] is the dissimilarity between # x[a, ] and y[b, ] # Sarah Goslee 2017-02-17, modified from legacy Splus code dated 01/01/01 if(is.null(ncol(x))) { x <- matrix(x, ncol=1) rownames(x) <- seq_len(nrow(x)) } if(is.null(ncol(y))) { y <- matrix(y, ncol=1) rownames(y) <- seq_len(nrow(y)) } if(!(ncol(x) == ncol(y))) stop("Matrices must have the same number of columns\n") x.names <- paste0("x", row.names(x)) y.names <- paste0("y", row.names(y)) x <- as.matrix(x) y <- as.matrix(y) d <- rbind(x, y) d <- full(distance(d, method=method)) d <- d[seq(1, nrow(x)), seq(nrow(x) + 1, nrow(x) + nrow(y)), drop=FALSE] rownames(d) <- x.names colnames(d) <- y.names class(d) <- "xdist" d }
# Copyright 2019 Battelle Memorial Institute; see the LICENSE file. #' module_water_water_demand_industry_xml #' #' Construct XML data structure for \code{water_demand_industry.xml}. #' #' @param command API command to execute #' @param ... other optional parameters, depending on command #' @return Depends on \code{command}: either a vector of required inputs, #' a vector of output names, or (if \code{command} is "MAKE") all #' the generated outputs: \code{water_demand_industry.xml}. The corresponding file in the #' original data system was \code{batch_water_demand_industry.xml.R} (water XML). module_water_water_demand_industry_xml <- function(command, ...) { if(command == driver.DECLARE_INPUTS) { return(c("L232.TechCoef")) } else if(command == driver.DECLARE_OUTPUTS) { return(c(XML = "water_demand_industry.xml")) } else if(command == driver.MAKE) { all_data <- list(...)[[1]] # Load required inputs L232.TechCoef <- get_data(all_data, "L232.TechCoef") # =================================================== # Produce outputs create_xml("water_demand_industry.xml") %>% add_xml_data(L232.TechCoef, "TechCoef") %>% add_precursors("L232.TechCoef") -> water_demand_industry.xml return_data(water_demand_industry.xml) } else { stop("Unknown command") } }
/input/gcamdata/R/zwater_xml_water_demand_industry.R
permissive
JGCRI/gcam-core
R
false
false
1,336
r
# Copyright 2019 Battelle Memorial Institute; see the LICENSE file. #' module_water_water_demand_industry_xml #' #' Construct XML data structure for \code{water_demand_industry.xml}. #' #' @param command API command to execute #' @param ... other optional parameters, depending on command #' @return Depends on \code{command}: either a vector of required inputs, #' a vector of output names, or (if \code{command} is "MAKE") all #' the generated outputs: \code{water_demand_industry.xml}. The corresponding file in the #' original data system was \code{batch_water_demand_industry.xml.R} (water XML). module_water_water_demand_industry_xml <- function(command, ...) { if(command == driver.DECLARE_INPUTS) { return(c("L232.TechCoef")) } else if(command == driver.DECLARE_OUTPUTS) { return(c(XML = "water_demand_industry.xml")) } else if(command == driver.MAKE) { all_data <- list(...)[[1]] # Load required inputs L232.TechCoef <- get_data(all_data, "L232.TechCoef") # =================================================== # Produce outputs create_xml("water_demand_industry.xml") %>% add_xml_data(L232.TechCoef, "TechCoef") %>% add_precursors("L232.TechCoef") -> water_demand_industry.xml return_data(water_demand_industry.xml) } else { stop("Unknown command") } }
library("ggspatial") library("ggplot2") theme_set(theme_bw()) library("sf") library("rnaturalearth") library("rnaturalearthdata") world <- ne_countries(scale = "medium", returnclass = "sf") class(world) # black and white map with compass and distance legend ggplot(data = world) + geom_sf() + annotation_scale(location = "bl", width_hint = 0.5) + annotation_north_arrow(location = "bl", which_north = "true", pad_x = unit(0.75, "in"), pad_y = unit(0.5, "in"), style = north_arrow_fancy_orienteering) + coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97)) ## Scale on map varies by more than 10%, scale bar may be inaccurate # with country names world_points<- st_centroid(world) world_points <- cbind(world, st_coordinates(st_centroid(world$geometry))) ggplot(data = world) + geom_sf() + geom_text(data= world_points,aes(x=X, y=Y, label=name), color = "darkblue", fontface = "bold", check_overlap = FALSE) + annotate(geom = "text", x = -90, y = 26, label = "Gulf of Mexico", fontface = "italic", color = "grey22", size = 6) + coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97), expand = FALSE) ggplot(data = world) + geom_sf(fill= 'antiquewhite') + geom_text(data= world_points,aes(x=X, y=Y, label=name), color = 'darkblue', fontface = 'bold', check_overlap = FALSE) + annotate(geom = 'text', x = -300, y = 400, label = 'Gulf of Mexico', fontface = 'italic', color = 'grey22', size = 6) + annotation_scale(location = 'bl', width_hint = 0.5) + annotation_north_arrow(location = 'bl', which_north = 'true', pad_x = unit(0.75, 'in'), pad_y = unit(0.5, 'in'), style = north_arrow_fancy_orienteering) + coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97), expand = FALSE) + xlab('Longitude') + ylab('Latitude') + ggtitle('Map of the Gulf of Mexico and the Caribbean Sea') + theme(panel.grid.major = element_line(color = gray(.5), linetype = 'dashed', size = 0.5), panel.background = element_rect(fill = 'aliceblue'))
/charts/map.with.compass.and.distance.r
no_license
gsdavis1959/R_examples
R
false
false
2,074
r
library("ggspatial") library("ggplot2") theme_set(theme_bw()) library("sf") library("rnaturalearth") library("rnaturalearthdata") world <- ne_countries(scale = "medium", returnclass = "sf") class(world) # black and white map with compass and distance legend ggplot(data = world) + geom_sf() + annotation_scale(location = "bl", width_hint = 0.5) + annotation_north_arrow(location = "bl", which_north = "true", pad_x = unit(0.75, "in"), pad_y = unit(0.5, "in"), style = north_arrow_fancy_orienteering) + coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97)) ## Scale on map varies by more than 10%, scale bar may be inaccurate # with country names world_points<- st_centroid(world) world_points <- cbind(world, st_coordinates(st_centroid(world$geometry))) ggplot(data = world) + geom_sf() + geom_text(data= world_points,aes(x=X, y=Y, label=name), color = "darkblue", fontface = "bold", check_overlap = FALSE) + annotate(geom = "text", x = -90, y = 26, label = "Gulf of Mexico", fontface = "italic", color = "grey22", size = 6) + coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97), expand = FALSE) ggplot(data = world) + geom_sf(fill= 'antiquewhite') + geom_text(data= world_points,aes(x=X, y=Y, label=name), color = 'darkblue', fontface = 'bold', check_overlap = FALSE) + annotate(geom = 'text', x = -300, y = 400, label = 'Gulf of Mexico', fontface = 'italic', color = 'grey22', size = 6) + annotation_scale(location = 'bl', width_hint = 0.5) + annotation_north_arrow(location = 'bl', which_north = 'true', pad_x = unit(0.75, 'in'), pad_y = unit(0.5, 'in'), style = north_arrow_fancy_orienteering) + coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97), expand = FALSE) + xlab('Longitude') + ylab('Latitude') + ggtitle('Map of the Gulf of Mexico and the Caribbean Sea') + theme(panel.grid.major = element_line(color = gray(.5), linetype = 'dashed', size = 0.5), panel.background = element_rect(fill = 'aliceblue'))
plot4 <- function(ucifile = "C:/Users/cwilhelm/Documents/Coursera/exdata%2Fdata%2Fhousehold_power_consumption/household_power_consumption.txt") { ucidata <- read.table(ucifile,header=TRUE,sep=";",na.strings="?") subfirst <- subset(ucidata,Date=="1/2/2007") subsecond <- subset(ucidata,Date=="2/2/2007") subdata <- rbind(subfirst,subsecond) subdata$Timestamp <- paste(subdata$Date, subdata$Time) png("plot4.png",height=480,width=480) par(mfrow=c(2,2)) plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Global_active_power,type="l",xlab="",ylab="Global Active Power") plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Voltage,type="l",xlab="datetime",ylab="Voltage") plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") points(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Sub_metering_2,type="l",col="red") points(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Sub_metering_3,type="l",col="blue") legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lty=1,bty="n") plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Global_reactive_power,type="l",xlab="datetime",ylab="Global_reactive_power") dev.off() }
/Plot4.R
no_license
cwilhelm486/ExData_Plotting1
R
false
false
1,324
r
plot4 <- function(ucifile = "C:/Users/cwilhelm/Documents/Coursera/exdata%2Fdata%2Fhousehold_power_consumption/household_power_consumption.txt") { ucidata <- read.table(ucifile,header=TRUE,sep=";",na.strings="?") subfirst <- subset(ucidata,Date=="1/2/2007") subsecond <- subset(ucidata,Date=="2/2/2007") subdata <- rbind(subfirst,subsecond) subdata$Timestamp <- paste(subdata$Date, subdata$Time) png("plot4.png",height=480,width=480) par(mfrow=c(2,2)) plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Global_active_power,type="l",xlab="",ylab="Global Active Power") plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Voltage,type="l",xlab="datetime",ylab="Voltage") plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") points(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Sub_metering_2,type="l",col="red") points(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Sub_metering_3,type="l",col="blue") legend("topright",legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lty=1,bty="n") plot(strptime(subdata$Timestamp, "%d/%m/%Y %H:%M:%S"),subdata$Global_reactive_power,type="l",xlab="datetime",ylab="Global_reactive_power") dev.off() }
\name{FastRCS-package} \alias{FastPCS-package} \docType{package} \title{Code to compute the FastRCS regression outlyingness index.} \description{ Uses the FastRCS algorithm to compute the RCS outlyingness index of regression. } \details{ \tabular{ll}{ Package: \tab FastRCS\cr Type: \tab Package\cr Version: \tab 0.1.1\cr Date: \tab 2013-01-13\cr Suggests: \tab mvtnorm\cr License: \tab GPL (>= 2)\cr LazyLoad: \tab yes\cr } Index: \preformatted{ FastRCS Function to compute the FastRCS regression outlyingness index. FRCSnumStarts Internal function used to compute the FastRCS regression outlyingness index. plot.FastRCS Robust Diagnostic Plots For FastRCS. quanf Internal function used to compute the FastRCS regression outlyingness index. } } \references{ Vakili, K. and Schmitt, E. (2014). Finding Regression Outliers With FastRCS. (http://arxiv.org/abs/1307.4834) } \author{ Kaveh Vakili [aut, cre], Maintainer: Kaveh Vakili <vakili.kaveh.email@gmail.com> } \keyword{package}
/fuzzedpackages/FastRCS/man/FastRCS-package.Rd
no_license
akhikolla/testpackages
R
false
false
1,109
rd
\name{FastRCS-package} \alias{FastPCS-package} \docType{package} \title{Code to compute the FastRCS regression outlyingness index.} \description{ Uses the FastRCS algorithm to compute the RCS outlyingness index of regression. } \details{ \tabular{ll}{ Package: \tab FastRCS\cr Type: \tab Package\cr Version: \tab 0.1.1\cr Date: \tab 2013-01-13\cr Suggests: \tab mvtnorm\cr License: \tab GPL (>= 2)\cr LazyLoad: \tab yes\cr } Index: \preformatted{ FastRCS Function to compute the FastRCS regression outlyingness index. FRCSnumStarts Internal function used to compute the FastRCS regression outlyingness index. plot.FastRCS Robust Diagnostic Plots For FastRCS. quanf Internal function used to compute the FastRCS regression outlyingness index. } } \references{ Vakili, K. and Schmitt, E. (2014). Finding Regression Outliers With FastRCS. (http://arxiv.org/abs/1307.4834) } \author{ Kaveh Vakili [aut, cre], Maintainer: Kaveh Vakili <vakili.kaveh.email@gmail.com> } \keyword{package}
#' @title To explain how to initialize clusters for the divisive algorithm. #' @description To explain how to initialize clusters for the divisive algorithm. #' @param initList is a clusters list. It will contain clusters with one element. #' @details This function will explain how to calculate every cluster that can be created by joining initial clusters with each other. It creates clusters #' from length = 1 until a cluster with every element is created. #' @details These clusters will be used to find the most different clusters that we can create by dividing the initial cluster. #' @author Roberto AlcΓ‘ntara \email{roberto.alcantara@@edu.uah.es} #' @author Juan JosΓ© Cuadrado \email{jjcg@@uah.es} #' @author Universidad de AlcalΓ‘ de Henares #' @return A cluster list. Explanation. #' @examples #' #' data <- c(1:8) #' #' matrix <- matrix(data, ncol=2) #' #' listData <- toListDivisive(data) #' #' listMatrix <- toListDivisive(matrix) #' #' initClusters.details(listData) #' #' initClusters.details(listMatrix) #' #' @export initClusters.details <- function(initList){ message("\n 'initClusters' method initializes the clusters used in the divisive algorithm. \n\n") message("\n To know which are the most different clusters, we need to know the distance between \n every possible clusters that could be created with the initial elements. \n") message("\n This step is the most computationally complex, so it will make the algorithm to get the \n solution with delay, or even, not to find a solution because of the computers capacities.\n\n") clusters <- initList unitClusters <- initList aux <- initList goal <- initList[[length(initList)]] res <- c() auxAux <- c() while(nrow(clusters[[length(clusters)]]) != length(unitClusters)){ for(i in seq_len(length(aux))){ lastElement <- aux[[i]] lastElement <- (lastElement[nrow(lastElement),]) lastElement <- matrix(lastElement,ncol=2) clusterIndex <- getClusterIndex(unitClusters,lastElement) for (j in 1:length(unitClusters)){ cluster1 <- aux[[i]] cluster1 <- matrix(cluster1,ncol=2) cluster2 <- unitClusters[[j]] if (j > clusterIndex){ newCluster <- c() for (k in (1:nrow(cluster1))){ newCluster <- c(newCluster,cluster1[k,]) } for (k in (1:nrow(cluster2))){ newCluster <- c(newCluster,cluster2[k,]) } newCluster <- matrix(newCluster, ncol=2, byrow=TRUE) res[[length(res) + 1]] <- newCluster data <- newCluster[nrow(newCluster),] asMatrix <- matrix(data,ncol=2) if(!equalCluster(asMatrix,goal)){ auxAux[[length(auxAux) + 1]] <- newCluster } } } } aux <- auxAux auxAux <- c() clusters <- c(clusters, res) res <- c() } message("\n The clusters created using \n") print(unitClusters) message("\n are: \n") print(clusters) clusters }
/R/initClusters.details.R
no_license
cran/LearnClust
R
false
false
3,054
r
#' @title To explain how to initialize clusters for the divisive algorithm. #' @description To explain how to initialize clusters for the divisive algorithm. #' @param initList is a clusters list. It will contain clusters with one element. #' @details This function will explain how to calculate every cluster that can be created by joining initial clusters with each other. It creates clusters #' from length = 1 until a cluster with every element is created. #' @details These clusters will be used to find the most different clusters that we can create by dividing the initial cluster. #' @author Roberto AlcΓ‘ntara \email{roberto.alcantara@@edu.uah.es} #' @author Juan JosΓ© Cuadrado \email{jjcg@@uah.es} #' @author Universidad de AlcalΓ‘ de Henares #' @return A cluster list. Explanation. #' @examples #' #' data <- c(1:8) #' #' matrix <- matrix(data, ncol=2) #' #' listData <- toListDivisive(data) #' #' listMatrix <- toListDivisive(matrix) #' #' initClusters.details(listData) #' #' initClusters.details(listMatrix) #' #' @export initClusters.details <- function(initList){ message("\n 'initClusters' method initializes the clusters used in the divisive algorithm. \n\n") message("\n To know which are the most different clusters, we need to know the distance between \n every possible clusters that could be created with the initial elements. \n") message("\n This step is the most computationally complex, so it will make the algorithm to get the \n solution with delay, or even, not to find a solution because of the computers capacities.\n\n") clusters <- initList unitClusters <- initList aux <- initList goal <- initList[[length(initList)]] res <- c() auxAux <- c() while(nrow(clusters[[length(clusters)]]) != length(unitClusters)){ for(i in seq_len(length(aux))){ lastElement <- aux[[i]] lastElement <- (lastElement[nrow(lastElement),]) lastElement <- matrix(lastElement,ncol=2) clusterIndex <- getClusterIndex(unitClusters,lastElement) for (j in 1:length(unitClusters)){ cluster1 <- aux[[i]] cluster1 <- matrix(cluster1,ncol=2) cluster2 <- unitClusters[[j]] if (j > clusterIndex){ newCluster <- c() for (k in (1:nrow(cluster1))){ newCluster <- c(newCluster,cluster1[k,]) } for (k in (1:nrow(cluster2))){ newCluster <- c(newCluster,cluster2[k,]) } newCluster <- matrix(newCluster, ncol=2, byrow=TRUE) res[[length(res) + 1]] <- newCluster data <- newCluster[nrow(newCluster),] asMatrix <- matrix(data,ncol=2) if(!equalCluster(asMatrix,goal)){ auxAux[[length(auxAux) + 1]] <- newCluster } } } } aux <- auxAux auxAux <- c() clusters <- c(clusters, res) res <- c() } message("\n The clusters created using \n") print(unitClusters) message("\n are: \n") print(clusters) clusters }
% Generated by roxygen2 (4.1.0): do not edit by hand % Please edit documentation in R/fsldilate.R \name{fsldilate} \alias{fsldilate} \title{Dilate image using FSL} \usage{ fsldilate(file, outfile = NULL, retimg = FALSE, reorient = FALSE, intern = TRUE, kopts = "", opts = "", verbose = TRUE, ...) } \arguments{ \item{file}{(character) image to be dilated} \item{outfile}{(character) resultant dilated image name} \item{retimg}{(logical) return image of class nifti} \item{reorient}{(logical) If retimg, should file be reoriented when read in? Passed to \code{\link{readNIfTI}}.} \item{intern}{(logical) to be passed to \code{\link{system}}} \item{kopts}{(character) options for kernel} \item{opts}{(character) additional options to be passed to fslmaths} \item{verbose}{(logical) print out command before running} \item{...}{additional arguments passed to \code{\link{readNIfTI}}.} } \value{ Result from system command, depends if intern is TRUE or FALSE. If retimg is TRUE, then the image will be returned. } \description{ This function calls \code{fslmaths -ero} after inverting the image to dilate an image with either the default FSL kernel or the kernel specified in \code{kopts}. The function either saves the image or returns an object of class nifti. } \examples{ if (have.fsl()){ system.time({ x = array(rnorm(1e6), dim = c(100, 100, 100)) img = nifti(x, dim= c(100, 100, 100), datatype = convert.datatype()$FLOAT32, cal.min = min(x), cal.max = max(x), pixdim = rep(1, 4)) mask = img > .5 dilated = fsldilate(mask, kopts = "-kernel boxv 5", retimg=TRUE) }) } }
/man/fsldilate.Rd
no_license
emsweene/fslr
R
false
false
1,583
rd
% Generated by roxygen2 (4.1.0): do not edit by hand % Please edit documentation in R/fsldilate.R \name{fsldilate} \alias{fsldilate} \title{Dilate image using FSL} \usage{ fsldilate(file, outfile = NULL, retimg = FALSE, reorient = FALSE, intern = TRUE, kopts = "", opts = "", verbose = TRUE, ...) } \arguments{ \item{file}{(character) image to be dilated} \item{outfile}{(character) resultant dilated image name} \item{retimg}{(logical) return image of class nifti} \item{reorient}{(logical) If retimg, should file be reoriented when read in? Passed to \code{\link{readNIfTI}}.} \item{intern}{(logical) to be passed to \code{\link{system}}} \item{kopts}{(character) options for kernel} \item{opts}{(character) additional options to be passed to fslmaths} \item{verbose}{(logical) print out command before running} \item{...}{additional arguments passed to \code{\link{readNIfTI}}.} } \value{ Result from system command, depends if intern is TRUE or FALSE. If retimg is TRUE, then the image will be returned. } \description{ This function calls \code{fslmaths -ero} after inverting the image to dilate an image with either the default FSL kernel or the kernel specified in \code{kopts}. The function either saves the image or returns an object of class nifti. } \examples{ if (have.fsl()){ system.time({ x = array(rnorm(1e6), dim = c(100, 100, 100)) img = nifti(x, dim= c(100, 100, 100), datatype = convert.datatype()$FLOAT32, cal.min = min(x), cal.max = max(x), pixdim = rep(1, 4)) mask = img > .5 dilated = fsldilate(mask, kopts = "-kernel boxv 5", retimg=TRUE) }) } }
# update package if necessary ---- devtools::install_github("kassandra-ru/kassandr") # load packages ---- library(docxtractr) library(kassandr) library(tidyverse) library(rio) library(lubridate) # set data folder ---- info = Sys.info() # ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΎ систСмС if (info[1] == "Linux") { set_libreoffice_path("/usr/bin/libreoffice") # ubuntu or macos Sys.setenv(LD_LIBRARY_PATH = "/usr/lib/libreoffice/program/") # ubuntu protection against libreglo.so not found path = "~/Documents/kassandra/data/raw/" } if (info[1] == "Windows") { Sys.setenv("TAR" = "internal") # if install_github() fails on Windows OS set_libreoffice_path("C:/Program Files/LibreOffice/program/soffice.exe") # windows path = "D:/Research/Kassandra/data/raw/" } # create today's folder ---- access_date = Sys.Date() today_folder = paste0(path, access_date, "/") if (!dir.exists(today_folder)) { dir.create(today_folder) } # download setup ---- method = "curl" # maybe "curl", "wget", "libcurl", "auto", "internal", "wininet" extra = "-L" # options for downloading files, passed to `download.file()`: used for "wget" and "curl" methods # i_ipc.xlsx ---- url_from = "https://rosstat.gov.ru/storage/mediabank/pddei1ud/i_ipc.xlsx" raw_path_to = "i_ipc.xlsx" csv_path_to = "i_ipc.csv" univariate = TRUE frequency = 12 comment = "Monthly chained CPI from Russian Statistical Agency" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_i_ipc_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab5a.xls ---- url_from = "https://gks.ru/storage/mediabank/e6uKSphi/tab5a.xls" raw_path_to = "tab5a.xls" csv_path_to = "tab5a.csv" univariate = TRUE frequency = 4 comment = "Gross domestic product quarterly current prices" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab5a_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab9a.xls ---- url_from = "http://www.gks.ru/free_doc/new_site/vvp/kv/tab9a.xls" raw_path_to = "tab9a.xls" csv_path_to = "tab9a.csv" univariate = TRUE frequency = 4 comment = "Deflator index in percent to the previous quarter" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab9a_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab9.xls ---- url_from = "http://www.gks.ru/free_doc/new_site/vvp/kv/tab9.xls" raw_path_to = "tab9.xls" csv_path_to = "tab9.csv" univariate = TRUE frequency = 4 comment = "Deflator index in percent to the previous quarter early data" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab9_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab6b.xls ---- url_from = "https://gks.ru/storage/mediabank/35KdpOvs/tab6b.xls" raw_path_to = "tab6b.xls" csv_path_to = "tab6b.csv" univariate = TRUE frequency = 4 comment = "Gross domestic product quarterly 2016 prices" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab6b_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # lendrate.html ---- url_from = "http://www.cbr.ru/hd_base/mkr/mkr_monthes/?UniDbQuery.Posted=True&UniDbQuery.From=08.2000&UniDbQuery.To=01.2100&UniDbQuery.st=SF&UniDbQuery.st=HR&UniDbQuery.st=MB&UniDbQuery.Currency=-1&UniDbQuery.sk=Dd1_&UniDbQuery.sk=Dd7&UniDbQuery.sk=Dd30&UniDbQuery.sk=Dd90&UniDbQuery.sk=Dd180&UniDbQuery.sk=Dd360" raw_path_to = "lendrate.html" csv_path_to = "lendrate.csv" univariate = FALSE frequency = 12 comment = "Monthly lending rate multiple duration periods" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_lendrate(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # urov_12kv.doc ---- url_from = "http://www.gks.ru/free_doc/new_site/population/urov/urov_12kv.doc" raw_path_to = "urov_12kv.doc" csv_path_to = "urov_12kv.csv" univariate = FALSE frequency = 12 comment = "Real disposable income percentage to previous period and to same month of previous year" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_urov_12kv_doc(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-07.xlsx ---- url_from = "https://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-07.xlsx" raw_path_to = "1-07.xlsx" csv_path_to = "1-07.csv" univariate = TRUE frequency = 12 comment = "Construction" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_nn_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-03.xlsx ---- url_from = "https://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-03.xlsx" raw_path_to = "1-03.xlsx" csv_path_to = "1-03.csv" univariate = TRUE frequency = 12 comment = "Agriculture index" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_nn_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-11.xlsx ---- url_from = "https://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-11.xlsx" raw_path_to = "1-11.xlsx" csv_path_to = "1-11.csv" univariate = TRUE frequency = 12 comment = "Budget" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_nn_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # m2-m2_sa.xlsx ---- url_from = "http://www.cbr.ru/vfs/statistics/credit_statistics/M2-M2_SA.xlsx" raw_path_to = "m2-m2_sa.xlsx" csv_path_to = "m2-m2_sa.csv" univariate = TRUE frequency = 12 comment = "Seasonally adjusted M2" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_m2_m2_sa_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # reserves.html ---- url_from = "http://www.cbr.ru/hd_base/mrrf/mrrf_m/?UniDbQuery.Posted=True&UniDbQuery.From=01.1900&UniDbQuery.To=01.2021" raw_path_to = "reserves.html" csv_path_to = "reserves.csv" univariate = FALSE frequency = 12 comment = "Reserves data from cbr" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_reserves(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # ind_okved2.xlsx ---- url_from = "http://www.gks.ru/free_doc/new_site/business/prom/ind_okved2.xlsx" raw_path_to = "ind_okved2.xlsx" csv_path_to = "ind_okved2.csv" univariate = FALSE frequency = NA comment = "Industrial production index" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_ind_okved2_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # trade.xls ---- url_from = "https://www.cbr.ru/vfs/statistics/credit_statistics/trade/trade.xls" raw_path_to = "trade.xls" csv_path_to = "trade.csv" univariate = FALSE frequency = 12 comment = "Trade statistics" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_trade_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-06-0.xlsx ---- url_from = "http://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-06-0.xlsx" raw_path_to = "1-06-0.xlsx" csv_path_to = "invest.csv" univariate = TRUE frequency = 4 comment = "Fixed capital investment" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_06_0_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # exchangerate.csv ---- csv_path_to = "exchangerate.csv" univariate = TRUE frequency = NA comment = "NA Exchange rate from cbr" csv_path_to_full = paste0(today_folder, csv_path_to) data_processed = parse_exchangerate(access_date) export_with_safe_date(data_processed, csv_path_to_full) # ind_baza_2018.xls ---- url_from = "https://rosstat.gov.ru/storage/mediabank/BYkjy3Bn/Ind_sub-2018.xls" raw_path_to = "Ind_sub-2018.xls" csv_path_to = "ind_baza_2018.csv" univariate = FALSE frequency = NA comment = "Industrial production index, new edition, base year = 2018" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_ind_okved2_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) }
/2021-01-25/downloader_v2.R
no_license
kassandra-ru/model
R
false
false
15,021
r
# update package if necessary ---- devtools::install_github("kassandra-ru/kassandr") # load packages ---- library(docxtractr) library(kassandr) library(tidyverse) library(rio) library(lubridate) # set data folder ---- info = Sys.info() # ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΎ систСмС if (info[1] == "Linux") { set_libreoffice_path("/usr/bin/libreoffice") # ubuntu or macos Sys.setenv(LD_LIBRARY_PATH = "/usr/lib/libreoffice/program/") # ubuntu protection against libreglo.so not found path = "~/Documents/kassandra/data/raw/" } if (info[1] == "Windows") { Sys.setenv("TAR" = "internal") # if install_github() fails on Windows OS set_libreoffice_path("C:/Program Files/LibreOffice/program/soffice.exe") # windows path = "D:/Research/Kassandra/data/raw/" } # create today's folder ---- access_date = Sys.Date() today_folder = paste0(path, access_date, "/") if (!dir.exists(today_folder)) { dir.create(today_folder) } # download setup ---- method = "curl" # maybe "curl", "wget", "libcurl", "auto", "internal", "wininet" extra = "-L" # options for downloading files, passed to `download.file()`: used for "wget" and "curl" methods # i_ipc.xlsx ---- url_from = "https://rosstat.gov.ru/storage/mediabank/pddei1ud/i_ipc.xlsx" raw_path_to = "i_ipc.xlsx" csv_path_to = "i_ipc.csv" univariate = TRUE frequency = 12 comment = "Monthly chained CPI from Russian Statistical Agency" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_i_ipc_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab5a.xls ---- url_from = "https://gks.ru/storage/mediabank/e6uKSphi/tab5a.xls" raw_path_to = "tab5a.xls" csv_path_to = "tab5a.csv" univariate = TRUE frequency = 4 comment = "Gross domestic product quarterly current prices" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab5a_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab9a.xls ---- url_from = "http://www.gks.ru/free_doc/new_site/vvp/kv/tab9a.xls" raw_path_to = "tab9a.xls" csv_path_to = "tab9a.csv" univariate = TRUE frequency = 4 comment = "Deflator index in percent to the previous quarter" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab9a_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab9.xls ---- url_from = "http://www.gks.ru/free_doc/new_site/vvp/kv/tab9.xls" raw_path_to = "tab9.xls" csv_path_to = "tab9.csv" univariate = TRUE frequency = 4 comment = "Deflator index in percent to the previous quarter early data" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab9_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # tab6b.xls ---- url_from = "https://gks.ru/storage/mediabank/35KdpOvs/tab6b.xls" raw_path_to = "tab6b.xls" csv_path_to = "tab6b.csv" univariate = TRUE frequency = 4 comment = "Gross domestic product quarterly 2016 prices" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_tab6b_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # lendrate.html ---- url_from = "http://www.cbr.ru/hd_base/mkr/mkr_monthes/?UniDbQuery.Posted=True&UniDbQuery.From=08.2000&UniDbQuery.To=01.2100&UniDbQuery.st=SF&UniDbQuery.st=HR&UniDbQuery.st=MB&UniDbQuery.Currency=-1&UniDbQuery.sk=Dd1_&UniDbQuery.sk=Dd7&UniDbQuery.sk=Dd30&UniDbQuery.sk=Dd90&UniDbQuery.sk=Dd180&UniDbQuery.sk=Dd360" raw_path_to = "lendrate.html" csv_path_to = "lendrate.csv" univariate = FALSE frequency = 12 comment = "Monthly lending rate multiple duration periods" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_lendrate(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # urov_12kv.doc ---- url_from = "http://www.gks.ru/free_doc/new_site/population/urov/urov_12kv.doc" raw_path_to = "urov_12kv.doc" csv_path_to = "urov_12kv.csv" univariate = FALSE frequency = 12 comment = "Real disposable income percentage to previous period and to same month of previous year" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_urov_12kv_doc(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-07.xlsx ---- url_from = "https://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-07.xlsx" raw_path_to = "1-07.xlsx" csv_path_to = "1-07.csv" univariate = TRUE frequency = 12 comment = "Construction" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_nn_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-03.xlsx ---- url_from = "https://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-03.xlsx" raw_path_to = "1-03.xlsx" csv_path_to = "1-03.csv" univariate = TRUE frequency = 12 comment = "Agriculture index" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_nn_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-11.xlsx ---- url_from = "https://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-11.xlsx" raw_path_to = "1-11.xlsx" csv_path_to = "1-11.csv" univariate = TRUE frequency = 12 comment = "Budget" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_nn_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # m2-m2_sa.xlsx ---- url_from = "http://www.cbr.ru/vfs/statistics/credit_statistics/M2-M2_SA.xlsx" raw_path_to = "m2-m2_sa.xlsx" csv_path_to = "m2-m2_sa.csv" univariate = TRUE frequency = 12 comment = "Seasonally adjusted M2" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_m2_m2_sa_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # reserves.html ---- url_from = "http://www.cbr.ru/hd_base/mrrf/mrrf_m/?UniDbQuery.Posted=True&UniDbQuery.From=01.1900&UniDbQuery.To=01.2021" raw_path_to = "reserves.html" csv_path_to = "reserves.csv" univariate = FALSE frequency = 12 comment = "Reserves data from cbr" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_reserves(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # ind_okved2.xlsx ---- url_from = "http://www.gks.ru/free_doc/new_site/business/prom/ind_okved2.xlsx" raw_path_to = "ind_okved2.xlsx" csv_path_to = "ind_okved2.csv" univariate = FALSE frequency = NA comment = "Industrial production index" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_ind_okved2_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # trade.xls ---- url_from = "https://www.cbr.ru/vfs/statistics/credit_statistics/trade/trade.xls" raw_path_to = "trade.xls" csv_path_to = "trade.csv" univariate = FALSE frequency = 12 comment = "Trade statistics" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_trade_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # 1-06-0.xlsx ---- url_from = "http://www.gks.ru/bgd/regl/b20_02/IssWWW.exe/Stg/d010/1-06-0.xlsx" raw_path_to = "1-06-0.xlsx" csv_path_to = "invest.csv" univariate = TRUE frequency = 4 comment = "Fixed capital investment" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_1_06_0_xlsx(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) } # exchangerate.csv ---- csv_path_to = "exchangerate.csv" univariate = TRUE frequency = NA comment = "NA Exchange rate from cbr" csv_path_to_full = paste0(today_folder, csv_path_to) data_processed = parse_exchangerate(access_date) export_with_safe_date(data_processed, csv_path_to_full) # ind_baza_2018.xls ---- url_from = "https://rosstat.gov.ru/storage/mediabank/BYkjy3Bn/Ind_sub-2018.xls" raw_path_to = "Ind_sub-2018.xls" csv_path_to = "ind_baza_2018.csv" univariate = FALSE frequency = NA comment = "Industrial production index, new edition, base year = 2018" csv_path_to_full = paste0(today_folder, csv_path_to) raw_path_to_full = paste0(today_folder, raw_path_to) utils::download.file(url = url_from, destfile = raw_path_to_full, method = method, extra = extra) if (length(grep("Доступ Π·Π°ΠΏΡ€Π΅Ρ‰Π΅Π½", read_lines(raw_path_to_full))) > 0) { warning("Probably file moved to another location") stop("Fucking `Access denied` inside a file :(") } data_processed = convert_ind_okved2_xls(raw_path_to_full, access_date) export_with_safe_date(data_processed, csv_path_to_full) if (file.exists(raw_path_to_full)) { file.remove(raw_path_to_full) }
## These are a pair of functions that cache the inverse of a matrix. Matrix inversion is usually a costly computation and caching the inverse of a matrix can prove to be efficient for large matrices. ## Usage: If x is the matrix inverse of which to be calculated; cachedmatrix <- makeCacheMatrix(x). Then call cacheSolve on cachedmatrix: cacheSolve(cachedmatrix). ## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { inv <- NULL set <- function(y){ x <<- y inv <<- NULL } get <- function() x setinv <- function(solve) inv <<- solve getinv <- function() inv list(set = set, get = get, setinv = setinv, getinv = getinv) } ## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { Β Β Β Β Β Β Β Β inv <- x$getinv() if(!is.null(inv)){ message("getting cached data") return(inv) } data <- x$get() inv <- solve(data, ...) x$setinv(inv) inv }
/cachematrix.R
no_license
emelaktas/ProgrammingAssignment2
R
false
false
1,153
r
## These are a pair of functions that cache the inverse of a matrix. Matrix inversion is usually a costly computation and caching the inverse of a matrix can prove to be efficient for large matrices. ## Usage: If x is the matrix inverse of which to be calculated; cachedmatrix <- makeCacheMatrix(x). Then call cacheSolve on cachedmatrix: cacheSolve(cachedmatrix). ## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { inv <- NULL set <- function(y){ x <<- y inv <<- NULL } get <- function() x setinv <- function(solve) inv <<- solve getinv <- function() inv list(set = set, get = get, setinv = setinv, getinv = getinv) } ## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { Β Β Β Β Β Β Β Β inv <- x$getinv() if(!is.null(inv)){ message("getting cached data") return(inv) } data <- x$get() inv <- solve(data, ...) x$setinv(inv) inv }
# definitions of groups of variables: var_smd = c("origin", "site", "quadrat", "latitude", "longitude") var_defense = c("tannin", "lignin", "saponins", "flavonoid", "trichome", "cn", "sla", "ssl") var_clim = c("MAT", "MAXT", "MINT", "ST", "AP", "WP", "DP", "SP") var_clim = c("CPC1", "CPC2") var_symb = c("infection", "shannon") var_symb = c() var_herb = c("herbivory") var_all = c(var_smd, var_defense, var_clim, var_symb, var_herb) var_def = c(var_smd, var_defense) load_data = function() { col_spec = cols( .default = col_double(), origin = col_character(), site = col_character(), quadrat = col_character() ) data_native = read_csv("../data/data_native.csv", col_types = col_spec) data_intro = read_csv("../data/data_intro.csv", col_types = col_spec) data_full = bind_rows(data_native, data_intro) data_full = data_full %>% mutate(ssl=.$stemlength/.$stembiomass) tpc = rda(data_full %>% select(c("MAT","MAXT","MINT","ST")) %>% scale()) ppc = rda(data_full %>% select(c("AP","WP","DP","SP")) %>% scale()) cpc = rda(data_full %>% select(c("MAT", "MAXT", "MINT", "ST", "AP", "WP", "DP", "SP")) %>% scale()) data_full$TPC = tpc$CA$u[,1] data_full$PPC = ppc$CA$u[,1] data_full$CPC1 = cpc$CA$u[,1] data_full$CPC2 = cpc$CA$u[,2] data_full } draw_climate_pca = function(data_full) { cpc = data_full %>% select(c("MAT", "MAXT", "MINT", "ST", "AP", "WP", "DP", "SP")) %>% scale() %>% rda() summ.cpc = summary(cpc) st = summ.cpc$site %>% as.data.frame() sp = summ.cpc$species %>% as.data.frame() gr = data.frame(syndrome=data_full$site, origin=data_full$origin) pca_defense = cpc fig = ggplot() + geom_point(aes(st$PC1, st$PC2, shape=gr$origin), size=2) + geom_segment(aes(x=0, y=0, xend=sp$PC1, yend=sp$PC2), arrow=arrow(angle=22.5, length=unit(0.2,"cm"), type="closed"), linetype=1, size=0.5, colour = "gray") + geom_text(aes(sp$PC1, sp$PC2, label=row.names(sp)), hjust=0.2, vjust=1.5) + labs(x=paste("PC1 (", format(100 * summary(pca_defense)$cont[[1]][2,1], digits=4), "%)", sep=""), y=paste("PC2 (", format(100 * summary(pca_defense)$cont[[1]][2,2], digits=4), "%)", sep="")) + geom_hline(yintercept=0,linetype=2,size=0.2) + geom_vline(xintercept=0,linetype=2,size=0.2)+ guides(shape=guide_legend(title="Origin"),color=guide_legend(title="Origin")) + scale_shape_manual(values = c(16, 1)) + theme_bw() fig } draw_defense_pca = function(st, sp, gr, pca_defense) { ggplot() + geom_point(aes(st$PC1, st$PC2, color=gr$syndrome, shape=gr$origin)) + stat_ellipse(aes(st$PC1, st$PC2, color=gr$syndrome, group=gr$syndrome)) + geom_segment(aes(x=0, y=0, xend=sp$PC1, yend=sp$PC2), arrow=arrow(angle=22.5, length=unit(0.2,"cm"), type="closed"), linetype=1, size=0.5, colour = "red") + geom_text(aes(sp$PC1, sp$PC2, label=row.names(sp)), hjust=0.2, vjust=1.5) + labs(x=paste("PC1 (", format(100 * summary(pca_defense)$cont[[1]][2,1], digits=4), "%)", sep=""), y=paste("PC2 (", format(100 * summary(pca_defense)$cont[[1]][2,2], digits=4), "%)", sep="")) + geom_hline(yintercept=0,linetype=2,size=0.2) + geom_vline(xintercept=0,linetype=2,size=0.2)+ guides(shape=guide_legend(title="Origin"),color=guide_legend(title="Syndrome")) + theme_bw() } clust_and_pca = function(data) { hcl = data %>% select(var_defense) %>% scale() %>% dist() %>% hclust("ward.D") gr = as.factor(cutree(hcl, 4)) pca_defense = data %>% select(var_defense) %>% scale() %>% rda() st = summary(pca_defense)$sites %>% as.data.frame() sp = summary(pca_defense)$species %>% as.data.frame() gr = data.frame(syndrome=gr, origin=data$origin) list(st=st, sp=sp, gr=gr, pca_defense=pca_defense) } permutest_cluster = function(data_def_nona, lst) { x = data_def_nona %>% mutate(syndrome=lst$gr$syndrome) x_s12 = filter(x, syndrome %in% c(1, 2)) x_s13 = filter(x, syndrome %in% c(1, 3)) x_s14 = filter(x, syndrome %in% c(1, 4)) x_s23 = filter(x, syndrome %in% c(2, 3)) x_s24 = filter(x, syndrome %in% c(2, 4)) x_s34 = filter(x, syndrome %in% c(3, 4)) # multi-groups multi = adonis(select(x, var_defense) ~ syndrome, data=x) # parse-wise pw1 = adonis(select(x_s12, var_defense) ~ syndrome, data=x_s12) pw2 = adonis(select(x_s13, var_defense) ~ syndrome, data=x_s13) pw3 = adonis(select(x_s14, var_defense) ~ syndrome, data=x_s14) pw4 = adonis(select(x_s23, var_defense) ~ syndrome, data=x_s23) pw5 = adonis(select(x_s24, var_defense) ~ syndrome, data=x_s24) pw6 = adonis(select(x_s34, var_defense) ~ syndrome, data=x_s34) rbind(multi$aov.tab, pw1$aov.tab, pw2$aov.tab, pw3$aov.tab, pw4$aov.tab, pw5$aov.tab, pw6$aov.tab) } centroids_and_area = function(data_def_nona, data_all_nona) { x = data_def_nona %>% mutate(syndrome=lst$gr$syndrome) %>% select(var_defense) %>% scale() center = sweep(x, 2, apply(x, 2, min),'-') R = apply(x, 2, max) - apply(x, 2, min) x_star = sweep(center, 2, R, "/") x_star = as_tibble(x_star)[,c(3,6,2,7,8,5,1,4)] theta = (c(1,2,3,4,5,6,7,8)-1) * 2*pi/8 xm = sweep(x_star, 2, cos(theta), "*") ym = sweep(x_star, 2, sin(theta), "*") centroids = t(apply(cbind(xm, ym), 1, function(x) pracma::poly_center(x[1:8], x[9:16]))) area = apply(cbind(xm, ym), 1, function(x) pracma::polyarea(x[1:8], x[9:16])) df = tibble( area = area, cent.x = centroids[,1], cent.y = centroids[,2], syndrome = lst$gr$syndrome, quadrat = data_def_nona$quadrat ) data = left_join(data_all_nona, df, by="quadrat") data } # Mantel test multiple_mantel = function(data, prefix) { dmat_defense = data %>% select(var_defense) %>% scale() %>% dist() dmat_cent = data %>% select(cent.x, cent.y) %>% scale() %>% dist() dmat_area = data %>% select(area) %>% scale() %>% dist() dmat_clim = data %>% select(var_clim) %>% scale() %>% dist() dmat_symb = data %>% select(var_symb) %>% scale()%>% dist() dmat_herb = data %>% select(var_herb) %>% scale() %>% dist() mm_d = multi.mantel(dmat_defense, list(clim=dmat_clim, symb=dmat_symb, herb=dmat_herb)) mm_c = multi.mantel(dmat_cent, list(clim=dmat_clim, symb=dmat_symb, herb=dmat_herb)) mm_a = multi.mantel(dmat_area, list(clim=dmat_clim, symb=dmat_symb, herb=dmat_herb)) df1 = cbind(coeff=mm_d$coefficients, t=mm_d$tstatistic, p=mm_d$probt, rsq=mm_d$r.squared)[2:4,] rownames(df1) = c("CLIM", "SYMB", "HERB") df2 = cbind(coeff=mm_a$coefficients, t=mm_a$tstatistic, p=mm_a$probt, rsq=mm_a$r.squared)[2:4,] rownames(df2) = c("CLIM", "SYMB", "HERB") df3 = cbind(coeff=mm_c$coefficients, t=mm_c$tstatistic, p=mm_c$probt, rsq=mm_c$r.squared)[2:4,] rownames(df3) = c("CLIM", "SYMB", "HERB") write.csv(rbind(df1,df2,df3), paste0("../",prefix,"_mantel.csv")) } rda_and_summ = function(data, var, fname) { rvar = data %>% select(var) %>% scale() %>% as.data.frame() evar = cbind( data %>% select(var_clim) %>% scale(), data %>% select(var_herb) %>% scale(), data %>% select(origin, latitude) ) %>% as.data.frame() ret = rda( rvar ~ origin*latitude, data = evar ) perm <- how(nperm = 999) #setBlocks(perm) <- with(data, site) aov.rda = anova(ret, by="term", permutations = perm) write.csv(aov.rda, fname) aov.rda } vp_and_plot_EOL = function(data, var, fname) { rvar = data %>% select(var) %>% scale() %>% as.data.frame() env = cbind( data %>% select(var_clim) %>% scale(), data %>% select(var_symb) %>% scale(), data %>% select(var_herb) %>% scale() ) org = data %>% select(origin) lat = data %>% select(latitude) vp = varpart(rvar, env, lat, org) plot(vp, Xnames=c("ENV","LAT","ORG")) title(fname) } vp_and_plot_ABO = function(data, var, fname) { rvar = data %>% select(var) %>% scale() %>% as.data.frame() bio = cbind( data %>% select(var_symb) %>% scale(), data %>% select(var_herb) %>% scale() ) abio = data %>% select(var_clim) %>% scale() org = data %>% select(origin) #lat = data %>% select(latitude) vp = varpart(rvar, bio, abio, org) plot(vp, Xnames=c("BIO","ABIO","ORG")) title(fname) }
/code/utils.R
permissive
Augustpan/Latitudinal_Defense_Syndromes
R
false
false
8,268
r
# definitions of groups of variables: var_smd = c("origin", "site", "quadrat", "latitude", "longitude") var_defense = c("tannin", "lignin", "saponins", "flavonoid", "trichome", "cn", "sla", "ssl") var_clim = c("MAT", "MAXT", "MINT", "ST", "AP", "WP", "DP", "SP") var_clim = c("CPC1", "CPC2") var_symb = c("infection", "shannon") var_symb = c() var_herb = c("herbivory") var_all = c(var_smd, var_defense, var_clim, var_symb, var_herb) var_def = c(var_smd, var_defense) load_data = function() { col_spec = cols( .default = col_double(), origin = col_character(), site = col_character(), quadrat = col_character() ) data_native = read_csv("../data/data_native.csv", col_types = col_spec) data_intro = read_csv("../data/data_intro.csv", col_types = col_spec) data_full = bind_rows(data_native, data_intro) data_full = data_full %>% mutate(ssl=.$stemlength/.$stembiomass) tpc = rda(data_full %>% select(c("MAT","MAXT","MINT","ST")) %>% scale()) ppc = rda(data_full %>% select(c("AP","WP","DP","SP")) %>% scale()) cpc = rda(data_full %>% select(c("MAT", "MAXT", "MINT", "ST", "AP", "WP", "DP", "SP")) %>% scale()) data_full$TPC = tpc$CA$u[,1] data_full$PPC = ppc$CA$u[,1] data_full$CPC1 = cpc$CA$u[,1] data_full$CPC2 = cpc$CA$u[,2] data_full } draw_climate_pca = function(data_full) { cpc = data_full %>% select(c("MAT", "MAXT", "MINT", "ST", "AP", "WP", "DP", "SP")) %>% scale() %>% rda() summ.cpc = summary(cpc) st = summ.cpc$site %>% as.data.frame() sp = summ.cpc$species %>% as.data.frame() gr = data.frame(syndrome=data_full$site, origin=data_full$origin) pca_defense = cpc fig = ggplot() + geom_point(aes(st$PC1, st$PC2, shape=gr$origin), size=2) + geom_segment(aes(x=0, y=0, xend=sp$PC1, yend=sp$PC2), arrow=arrow(angle=22.5, length=unit(0.2,"cm"), type="closed"), linetype=1, size=0.5, colour = "gray") + geom_text(aes(sp$PC1, sp$PC2, label=row.names(sp)), hjust=0.2, vjust=1.5) + labs(x=paste("PC1 (", format(100 * summary(pca_defense)$cont[[1]][2,1], digits=4), "%)", sep=""), y=paste("PC2 (", format(100 * summary(pca_defense)$cont[[1]][2,2], digits=4), "%)", sep="")) + geom_hline(yintercept=0,linetype=2,size=0.2) + geom_vline(xintercept=0,linetype=2,size=0.2)+ guides(shape=guide_legend(title="Origin"),color=guide_legend(title="Origin")) + scale_shape_manual(values = c(16, 1)) + theme_bw() fig } draw_defense_pca = function(st, sp, gr, pca_defense) { ggplot() + geom_point(aes(st$PC1, st$PC2, color=gr$syndrome, shape=gr$origin)) + stat_ellipse(aes(st$PC1, st$PC2, color=gr$syndrome, group=gr$syndrome)) + geom_segment(aes(x=0, y=0, xend=sp$PC1, yend=sp$PC2), arrow=arrow(angle=22.5, length=unit(0.2,"cm"), type="closed"), linetype=1, size=0.5, colour = "red") + geom_text(aes(sp$PC1, sp$PC2, label=row.names(sp)), hjust=0.2, vjust=1.5) + labs(x=paste("PC1 (", format(100 * summary(pca_defense)$cont[[1]][2,1], digits=4), "%)", sep=""), y=paste("PC2 (", format(100 * summary(pca_defense)$cont[[1]][2,2], digits=4), "%)", sep="")) + geom_hline(yintercept=0,linetype=2,size=0.2) + geom_vline(xintercept=0,linetype=2,size=0.2)+ guides(shape=guide_legend(title="Origin"),color=guide_legend(title="Syndrome")) + theme_bw() } clust_and_pca = function(data) { hcl = data %>% select(var_defense) %>% scale() %>% dist() %>% hclust("ward.D") gr = as.factor(cutree(hcl, 4)) pca_defense = data %>% select(var_defense) %>% scale() %>% rda() st = summary(pca_defense)$sites %>% as.data.frame() sp = summary(pca_defense)$species %>% as.data.frame() gr = data.frame(syndrome=gr, origin=data$origin) list(st=st, sp=sp, gr=gr, pca_defense=pca_defense) } permutest_cluster = function(data_def_nona, lst) { x = data_def_nona %>% mutate(syndrome=lst$gr$syndrome) x_s12 = filter(x, syndrome %in% c(1, 2)) x_s13 = filter(x, syndrome %in% c(1, 3)) x_s14 = filter(x, syndrome %in% c(1, 4)) x_s23 = filter(x, syndrome %in% c(2, 3)) x_s24 = filter(x, syndrome %in% c(2, 4)) x_s34 = filter(x, syndrome %in% c(3, 4)) # multi-groups multi = adonis(select(x, var_defense) ~ syndrome, data=x) # parse-wise pw1 = adonis(select(x_s12, var_defense) ~ syndrome, data=x_s12) pw2 = adonis(select(x_s13, var_defense) ~ syndrome, data=x_s13) pw3 = adonis(select(x_s14, var_defense) ~ syndrome, data=x_s14) pw4 = adonis(select(x_s23, var_defense) ~ syndrome, data=x_s23) pw5 = adonis(select(x_s24, var_defense) ~ syndrome, data=x_s24) pw6 = adonis(select(x_s34, var_defense) ~ syndrome, data=x_s34) rbind(multi$aov.tab, pw1$aov.tab, pw2$aov.tab, pw3$aov.tab, pw4$aov.tab, pw5$aov.tab, pw6$aov.tab) } centroids_and_area = function(data_def_nona, data_all_nona) { x = data_def_nona %>% mutate(syndrome=lst$gr$syndrome) %>% select(var_defense) %>% scale() center = sweep(x, 2, apply(x, 2, min),'-') R = apply(x, 2, max) - apply(x, 2, min) x_star = sweep(center, 2, R, "/") x_star = as_tibble(x_star)[,c(3,6,2,7,8,5,1,4)] theta = (c(1,2,3,4,5,6,7,8)-1) * 2*pi/8 xm = sweep(x_star, 2, cos(theta), "*") ym = sweep(x_star, 2, sin(theta), "*") centroids = t(apply(cbind(xm, ym), 1, function(x) pracma::poly_center(x[1:8], x[9:16]))) area = apply(cbind(xm, ym), 1, function(x) pracma::polyarea(x[1:8], x[9:16])) df = tibble( area = area, cent.x = centroids[,1], cent.y = centroids[,2], syndrome = lst$gr$syndrome, quadrat = data_def_nona$quadrat ) data = left_join(data_all_nona, df, by="quadrat") data } # Mantel test multiple_mantel = function(data, prefix) { dmat_defense = data %>% select(var_defense) %>% scale() %>% dist() dmat_cent = data %>% select(cent.x, cent.y) %>% scale() %>% dist() dmat_area = data %>% select(area) %>% scale() %>% dist() dmat_clim = data %>% select(var_clim) %>% scale() %>% dist() dmat_symb = data %>% select(var_symb) %>% scale()%>% dist() dmat_herb = data %>% select(var_herb) %>% scale() %>% dist() mm_d = multi.mantel(dmat_defense, list(clim=dmat_clim, symb=dmat_symb, herb=dmat_herb)) mm_c = multi.mantel(dmat_cent, list(clim=dmat_clim, symb=dmat_symb, herb=dmat_herb)) mm_a = multi.mantel(dmat_area, list(clim=dmat_clim, symb=dmat_symb, herb=dmat_herb)) df1 = cbind(coeff=mm_d$coefficients, t=mm_d$tstatistic, p=mm_d$probt, rsq=mm_d$r.squared)[2:4,] rownames(df1) = c("CLIM", "SYMB", "HERB") df2 = cbind(coeff=mm_a$coefficients, t=mm_a$tstatistic, p=mm_a$probt, rsq=mm_a$r.squared)[2:4,] rownames(df2) = c("CLIM", "SYMB", "HERB") df3 = cbind(coeff=mm_c$coefficients, t=mm_c$tstatistic, p=mm_c$probt, rsq=mm_c$r.squared)[2:4,] rownames(df3) = c("CLIM", "SYMB", "HERB") write.csv(rbind(df1,df2,df3), paste0("../",prefix,"_mantel.csv")) } rda_and_summ = function(data, var, fname) { rvar = data %>% select(var) %>% scale() %>% as.data.frame() evar = cbind( data %>% select(var_clim) %>% scale(), data %>% select(var_herb) %>% scale(), data %>% select(origin, latitude) ) %>% as.data.frame() ret = rda( rvar ~ origin*latitude, data = evar ) perm <- how(nperm = 999) #setBlocks(perm) <- with(data, site) aov.rda = anova(ret, by="term", permutations = perm) write.csv(aov.rda, fname) aov.rda } vp_and_plot_EOL = function(data, var, fname) { rvar = data %>% select(var) %>% scale() %>% as.data.frame() env = cbind( data %>% select(var_clim) %>% scale(), data %>% select(var_symb) %>% scale(), data %>% select(var_herb) %>% scale() ) org = data %>% select(origin) lat = data %>% select(latitude) vp = varpart(rvar, env, lat, org) plot(vp, Xnames=c("ENV","LAT","ORG")) title(fname) } vp_and_plot_ABO = function(data, var, fname) { rvar = data %>% select(var) %>% scale() %>% as.data.frame() bio = cbind( data %>% select(var_symb) %>% scale(), data %>% select(var_herb) %>% scale() ) abio = data %>% select(var_clim) %>% scale() org = data %>% select(origin) #lat = data %>% select(latitude) vp = varpart(rvar, bio, abio, org) plot(vp, Xnames=c("BIO","ABIO","ORG")) title(fname) }
\name{Huber} \alias{Huber} \title{Huber Loss } \description{Evaluates the Huber loss function defined as \deqn{ f(r) = \left\{ \begin{array}{ll} \frac{1}{2}|r|^2 & |r| \le c \\ c(|r|-\frac{1}{2}c) & |r| > c \end{array} \right. }{f(r)=(1/2)*r^2 if |r|<=c} \deqn{}{f(r)=c*(|r|-(1/2)*c) if |r|>c } } \usage{ Huber(r, c = 1.345) } \arguments{ \item{r }{a real number or vector. } \item{c }{a positive number. If the value is negative, it's absolute value will be used. } } \examples{ set.seed(1) x = rnorm(200, mean = 1) y = Huber(x) plot(x, y) abline(h = (1.345)^2/2) }
/man/Huber.Rd
no_license
cran/qrmix
R
false
false
585
rd
\name{Huber} \alias{Huber} \title{Huber Loss } \description{Evaluates the Huber loss function defined as \deqn{ f(r) = \left\{ \begin{array}{ll} \frac{1}{2}|r|^2 & |r| \le c \\ c(|r|-\frac{1}{2}c) & |r| > c \end{array} \right. }{f(r)=(1/2)*r^2 if |r|<=c} \deqn{}{f(r)=c*(|r|-(1/2)*c) if |r|>c } } \usage{ Huber(r, c = 1.345) } \arguments{ \item{r }{a real number or vector. } \item{c }{a positive number. If the value is negative, it's absolute value will be used. } } \examples{ set.seed(1) x = rnorm(200, mean = 1) y = Huber(x) plot(x, y) abline(h = (1.345)^2/2) }
\name{xmb} \alias{xmb} \title{More robust test of whether something is NA or null. Should not give an error or NA, whatever x is.} \usage{ xmb(x, y = "") } \arguments{ \item{x}{The object to be tested. May not even exist.} \item{y}{true if missing or null or y, otherwise false. NOTE IT GIVES F IF IT IS ANY DATA FRAME, EVEN AN EMPTY ONE} } \description{ More robust test of whether something is NA or null. Should not give an error or NA, whatever x is. }
/man/xmb.Rd
no_license
stevepowell99/omnivr
R
false
false
467
rd
\name{xmb} \alias{xmb} \title{More robust test of whether something is NA or null. Should not give an error or NA, whatever x is.} \usage{ xmb(x, y = "") } \arguments{ \item{x}{The object to be tested. May not even exist.} \item{y}{true if missing or null or y, otherwise false. NOTE IT GIVES F IF IT IS ANY DATA FRAME, EVEN AN EMPTY ONE} } \description{ More robust test of whether something is NA or null. Should not give an error or NA, whatever x is. }
dataset <- read.csv("C:/Users/jensb/Documents/dataanalyse/dataanalyse/datasets/dataset-82167.csv") View(dataset.82167) # geef de namen van de variabelen weer names(dataset) # geef enkel de variabele hd weer dataset$hd
/eerstetest.R
no_license
embobrecht/dataanalyse
R
false
false
225
r
dataset <- read.csv("C:/Users/jensb/Documents/dataanalyse/dataanalyse/datasets/dataset-82167.csv") View(dataset.82167) # geef de namen van de variabelen weer names(dataset) # geef enkel de variabele hd weer dataset$hd
with(a5db1d12f78c845b4a783167e77071f2f, {ROOT <- 'D:/SEMOSS_v4.0.0_x64/SEMOSS_v4.0.0_x64/semosshome/db/Atadata2__3b3e4a3b-d382-4e98-9950-9b4e8b308c1c/version/80bb2a25-ac5d-47d0-abfc-b3f3811f0936';rm(list=ls())});
/80bb2a25-ac5d-47d0-abfc-b3f3811f0936/R/Temp/aMgSCnlb73PO6.R
no_license
ayanmanna8/test
R
false
false
212
r
with(a5db1d12f78c845b4a783167e77071f2f, {ROOT <- 'D:/SEMOSS_v4.0.0_x64/SEMOSS_v4.0.0_x64/semosshome/db/Atadata2__3b3e4a3b-d382-4e98-9950-9b4e8b308c1c/version/80bb2a25-ac5d-47d0-abfc-b3f3811f0936';rm(list=ls())});
.libPaths("/data/hydro/R_libs35") .libPaths() library(data.table) library(dplyr) library(tidyverse) library(lubridate) source_path = "/home/hnoorazar/chilling_codes/current_draft/chill_core.R" source(source_path) options(digit=9) options(digits=9) start_time <- Sys.time() ###################################################################### args = commandArgs(trailingOnly=TRUE) model_type = args[1] observed_dt <- data.table() ###################################################################### # Define main output path frost_out = "/data/hydro/users/Hossein/chill/frost_bloom_initial_database/" param_dir = file.path("/home/hnoorazar/chilling_codes/parameters/") local_files <- read.delim(file = paste0(param_dir, "file_list.txt"), header = F) local_files <- as.vector(local_files$V1) LocationGroups_NoMontana <- read.csv(paste0(param_dir, "LocationGroups_NoMontana.csv"), header=T, sep=",", as.is=T) LocationGroups_NoMontana <- within(LocationGroups_NoMontana, remove(lat, long)) ###################################################################### observed_dir <- "/data/hydro/jennylabcommon2/metdata/historical/UI_historical/VIC_Binary_CONUS_to_2016/" setwd(observed_dir) print (paste0("we should be in :", observed_dir)) print (getwd()) dir_con <- dir() dir_con <- dir_con[grep(pattern = "data_", x = dir_con)] dir_con <- dir_con[which(dir_con %in% local_files)] # 3. Process the data ----------------------------------------------------- for(file in dir_con){ lat <- substr(x = file, start = 6, stop = 13) long <- substr(x = file, start = 15, stop = 24) met_data <- read_binary(file_path = file, hist = T, no_vars=8) met_data <- data.table(met_data) # Clean it up met_data <- met_data %>% select(c(year, month, day, tmin)) %>% data.table() met_data <- form_chill_season_day_of_year_observed(met_data) met_data$lat <- lat met_data$long <- long met_data$model <- "Observed" observed_dt <- rbind(observed_dt, met_data) } observed_dt <- remove_montana(observed_dt, LocationGroups_NoMontana) observed_dt <- within(observed_dt, remove(lat, long)) observed_dt <- add_time_periods_observed(observed_dt) observed_dt <- observed_dt %>% filter(tmin <= 0) observed_dt_till_Dec <- observed_dt %>% filter(month %in% c(9, 10, 11, 12)) observed_dt_till_Jan <- observed_dt %>% filter(month %in% c(9, 10, 11, 12, 13)) observed_dt_till_Feb <- observed_dt rm(observed_dt) ################################################################ ######## Jan of 1950 is in the data, which belongs to chill season 1949, ######## which we do not have it in the data, so, time period for them will be ######## NA, so we drop them. observed_dt_till_Jan <- na.omit(observed_dt_till_Jan) observed_dt_till_Feb <- na.omit(observed_dt_till_Feb) if (dir.exists(frost_out) == F) { dir.create(path = frost_out, recursive = T) } saveRDS(observed_dt_till_Dec, paste0(frost_out, "observed_dt_till_Dec.rds")) saveRDS(observed_dt_till_Jan, paste0(frost_out, "observed_dt_till_Jan.rds")) saveRDS(observed_dt_till_Feb, paste0(frost_out, "observed_dt_till_Feb.rds")) end_time <- Sys.time() print( end_time - start_time)
/chilling/03_frost_bloom_aeolus/d_read_binary_for_frost_obs.R
permissive
HNoorazar/Ag
R
false
false
3,213
r
.libPaths("/data/hydro/R_libs35") .libPaths() library(data.table) library(dplyr) library(tidyverse) library(lubridate) source_path = "/home/hnoorazar/chilling_codes/current_draft/chill_core.R" source(source_path) options(digit=9) options(digits=9) start_time <- Sys.time() ###################################################################### args = commandArgs(trailingOnly=TRUE) model_type = args[1] observed_dt <- data.table() ###################################################################### # Define main output path frost_out = "/data/hydro/users/Hossein/chill/frost_bloom_initial_database/" param_dir = file.path("/home/hnoorazar/chilling_codes/parameters/") local_files <- read.delim(file = paste0(param_dir, "file_list.txt"), header = F) local_files <- as.vector(local_files$V1) LocationGroups_NoMontana <- read.csv(paste0(param_dir, "LocationGroups_NoMontana.csv"), header=T, sep=",", as.is=T) LocationGroups_NoMontana <- within(LocationGroups_NoMontana, remove(lat, long)) ###################################################################### observed_dir <- "/data/hydro/jennylabcommon2/metdata/historical/UI_historical/VIC_Binary_CONUS_to_2016/" setwd(observed_dir) print (paste0("we should be in :", observed_dir)) print (getwd()) dir_con <- dir() dir_con <- dir_con[grep(pattern = "data_", x = dir_con)] dir_con <- dir_con[which(dir_con %in% local_files)] # 3. Process the data ----------------------------------------------------- for(file in dir_con){ lat <- substr(x = file, start = 6, stop = 13) long <- substr(x = file, start = 15, stop = 24) met_data <- read_binary(file_path = file, hist = T, no_vars=8) met_data <- data.table(met_data) # Clean it up met_data <- met_data %>% select(c(year, month, day, tmin)) %>% data.table() met_data <- form_chill_season_day_of_year_observed(met_data) met_data$lat <- lat met_data$long <- long met_data$model <- "Observed" observed_dt <- rbind(observed_dt, met_data) } observed_dt <- remove_montana(observed_dt, LocationGroups_NoMontana) observed_dt <- within(observed_dt, remove(lat, long)) observed_dt <- add_time_periods_observed(observed_dt) observed_dt <- observed_dt %>% filter(tmin <= 0) observed_dt_till_Dec <- observed_dt %>% filter(month %in% c(9, 10, 11, 12)) observed_dt_till_Jan <- observed_dt %>% filter(month %in% c(9, 10, 11, 12, 13)) observed_dt_till_Feb <- observed_dt rm(observed_dt) ################################################################ ######## Jan of 1950 is in the data, which belongs to chill season 1949, ######## which we do not have it in the data, so, time period for them will be ######## NA, so we drop them. observed_dt_till_Jan <- na.omit(observed_dt_till_Jan) observed_dt_till_Feb <- na.omit(observed_dt_till_Feb) if (dir.exists(frost_out) == F) { dir.create(path = frost_out, recursive = T) } saveRDS(observed_dt_till_Dec, paste0(frost_out, "observed_dt_till_Dec.rds")) saveRDS(observed_dt_till_Jan, paste0(frost_out, "observed_dt_till_Jan.rds")) saveRDS(observed_dt_till_Feb, paste0(frost_out, "observed_dt_till_Feb.rds")) end_time <- Sys.time() print( end_time - start_time)
context("messages") test_that("messages in callr::r do not crash session", { ret <- r(function() { cliapp::cli_text("fooobar"); 1 + 1 }) expect_identical(ret, 2) gc() }) test_that("messages in callr::r_bg do not crash session", { skip_in_covr() # TODO: what wrong with this on Windows? rx <- r_bg(function() { cliapp::cli_text("fooobar"); 1 + 1 }) rx$wait(5000) rx$kill() expect_equal(rx$get_exit_status(), 0) expect_equal(rx$get_result(), 2) processx::processx_conn_close(rx$get_output_connection()) processx::processx_conn_close(rx$get_error_connection()) gc() })
/tests/testthat/test-messages.R
permissive
bedantaguru/callr
R
false
false
596
r
context("messages") test_that("messages in callr::r do not crash session", { ret <- r(function() { cliapp::cli_text("fooobar"); 1 + 1 }) expect_identical(ret, 2) gc() }) test_that("messages in callr::r_bg do not crash session", { skip_in_covr() # TODO: what wrong with this on Windows? rx <- r_bg(function() { cliapp::cli_text("fooobar"); 1 + 1 }) rx$wait(5000) rx$kill() expect_equal(rx$get_exit_status(), 0) expect_equal(rx$get_result(), 2) processx::processx_conn_close(rx$get_output_connection()) processx::processx_conn_close(rx$get_error_connection()) gc() })
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/deviationFunctions.R \name{sortedIndex} \alias{sortedIndex} \title{Index map for data set} \usage{ sortedIndex(dt) } \arguments{ \item{dt}{data.table} } \value{ A data.table is returned that consists of indexes for the order of each column. E.g. a data table with the first column (0.3,0.5, 0.1) would get an index of (2,3,1), i.e. the elements sorted by (2,3,1) are in increasing order. The index starts with 1. } \description{ The index map allows to create subspace slices without working on the underlying data set but rather on the ordered index. }
/man/sortedIndex.Rd
no_license
holtri/R-subcon
R
false
true
632
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/deviationFunctions.R \name{sortedIndex} \alias{sortedIndex} \title{Index map for data set} \usage{ sortedIndex(dt) } \arguments{ \item{dt}{data.table} } \value{ A data.table is returned that consists of indexes for the order of each column. E.g. a data table with the first column (0.3,0.5, 0.1) would get an index of (2,3,1), i.e. the elements sorted by (2,3,1) are in increasing order. The index starts with 1. } \description{ The index map allows to create subspace slices without working on the underlying data set but rather on the ordered index. }
# Have you ever been on the data.gov.uk and been completely perplexed to where the data is available to download # ** hand shoots up ** # Well I've just found a brilliant stackoverflow post (https://stackoverflow.com/questions/32034495/list-aviable-wfs-layers-and-read-into-data-frame-with-rgdal) # that will enable you to get the data that you need into R (providing it is in WFS format). # Firstly you'll want to go to the webpage where the data resides: https://data.gov.uk/dataset/fife-secondary-school-catchment-areas # Then you want to click on the link to the WFS file (more info on this format here: https://en.wikipedia.org/wiki/Web_Feature_Service) # Then copy the link, for example: # http://arcgisweb.fife.gov.uk/geoserver/fife/ows?service=WFS&version=1.0.0& # request=GetFeature&typeName=fife:SCHOOL_SECONDARY_CATCHMENTS&maxFeatures=1000000&outputFormat=GML2 # Now all you need to do is run the code provided by 'hrbrmstr', replacing the dsn with the copied link: library(gdalUtils) library(rgdal) dsn <- "WFS:http://arcgisweb.fife.gov.uk/geoserver/fife/ows?service=WFS&version=1.0.0& request=GetFeature&typeName=fife:SCHOOL_SECONDARY_CATCHMENTS&maxFeatures=1000000&outputFormat=GML2" ogrinfo(dsn, so=TRUE) # You need to put in what you want to extract here.. ogr2ogr(dsn, "sic.shp", "fife:SCHOOL_SECONDARY_CATCHMENTS") sic <- readOGR("sic.shp", "sic", stringsAsFactors=FALSE) plot(sic) # Apparently there are 1,729 WFS files on data.gov.uk so hopefully this comes in useful
/readingWFSfiles.R
no_license
markocherrie/Helpful_Code
R
false
false
1,505
r
# Have you ever been on the data.gov.uk and been completely perplexed to where the data is available to download # ** hand shoots up ** # Well I've just found a brilliant stackoverflow post (https://stackoverflow.com/questions/32034495/list-aviable-wfs-layers-and-read-into-data-frame-with-rgdal) # that will enable you to get the data that you need into R (providing it is in WFS format). # Firstly you'll want to go to the webpage where the data resides: https://data.gov.uk/dataset/fife-secondary-school-catchment-areas # Then you want to click on the link to the WFS file (more info on this format here: https://en.wikipedia.org/wiki/Web_Feature_Service) # Then copy the link, for example: # http://arcgisweb.fife.gov.uk/geoserver/fife/ows?service=WFS&version=1.0.0& # request=GetFeature&typeName=fife:SCHOOL_SECONDARY_CATCHMENTS&maxFeatures=1000000&outputFormat=GML2 # Now all you need to do is run the code provided by 'hrbrmstr', replacing the dsn with the copied link: library(gdalUtils) library(rgdal) dsn <- "WFS:http://arcgisweb.fife.gov.uk/geoserver/fife/ows?service=WFS&version=1.0.0& request=GetFeature&typeName=fife:SCHOOL_SECONDARY_CATCHMENTS&maxFeatures=1000000&outputFormat=GML2" ogrinfo(dsn, so=TRUE) # You need to put in what you want to extract here.. ogr2ogr(dsn, "sic.shp", "fife:SCHOOL_SECONDARY_CATCHMENTS") sic <- readOGR("sic.shp", "sic", stringsAsFactors=FALSE) plot(sic) # Apparently there are 1,729 WFS files on data.gov.uk so hopefully this comes in useful
### Initialization #### library('RPostgres') library('RPostgreSQL') ### Creating connector db <- 'INSERT YOUR DB NAME HERE' host_db <- 'INSERT YOUR HOST NUMBER HERE' db_port <- 'INSERT YOUR DB PORT HERE' db_user <- 'INSERT YOUR USER NAME HERE' db_password <- 'INSERT YOUR PASSWORD HERE' con <- dbConnect(RPostgres::Postgres(), dbname = db, host=host_db, port=db_port, user=db_user, password=db_password) dbListTables(con)
/postgre_connector.R
no_license
marcosemn/Connectors
R
false
false
437
r
### Initialization #### library('RPostgres') library('RPostgreSQL') ### Creating connector db <- 'INSERT YOUR DB NAME HERE' host_db <- 'INSERT YOUR HOST NUMBER HERE' db_port <- 'INSERT YOUR DB PORT HERE' db_user <- 'INSERT YOUR USER NAME HERE' db_password <- 'INSERT YOUR PASSWORD HERE' con <- dbConnect(RPostgres::Postgres(), dbname = db, host=host_db, port=db_port, user=db_user, password=db_password) dbListTables(con)
# ---------------------------------------------------------------------------------------------------- # Hidden Markov Models # Faits stylisés des rendements financiers # ---------------------------------------------------------------------------------------------------- # written # Gabriel LEMYRE # ---------------------------------------------------------------------------------------------------- # Under the supervision of : # Maciej AUGUSTYNIAK # ---------------------------------------------------------------------------------------------------- # First version : january 8th, 2020 # Last version : february 13th, 2020 # ---------------------------------------------------------------------------------------------------- # -------------------------------------------------------- # ANALYSE D'UNE SÉRIE ET RÉSULTATS SUR LES FAITS STYLISÉS # -------------------------------------------------------- # Fonction produisant des tables et graphiques # L'idée est de montrer qu'une série présente les # caractéristiques des faits stylisés des rendements # financiers # -------------------------------------------------------- # Instalation du package forecast permettant d'utiliser les fonctions ACF, PAcf et CCf # install.packages('forecast', dependencies = TRUE) # Installation du package library(forecast) # Permet de créer des graphiques très complexes # install.packages('ggplot2', dependencies = TRUE) # Installation du package library(ggplot2) # Instalation du package cowplot opermettant de combiner des graphiques # install.packages('cowplot', dependencies = TRUE) # Installation du package library(cowplot) # -------------------------------------------------------- # Paramètres graphiques # -------------------------------------------------------- title.size.var <- 12 axis.lab.size.var <- 8 lty.ciline <- 2 lwd.ciline <- 0.3 lwd.predict <- 0.2 # Nombre de points à afficher sur l'axe horizontal nbTicks=10 # JPEG DIMENSIONS FOR OUTPUTED FILE image.width <- 1250 image.heigth <- 666 # Faits stylisés title.size.var <- 12 axis.lab.size.var <- 8 resdev=300 # -------------------- # -------------------------------------------------------- # Point (1) et (2) : Absence d'acf pour rendement mais # présence pour erreurs^2 et abs(erreurs) # -------------------------------------------------------- epsilon <- logR-mean(logR) conf.level <- 0.95 ciline <- qnorm((1 - conf.level)/2)/sqrt(length(epsilon)) # Fonction d'autocorrélation des rendements AutoCorrelation <- Acf(logR, plot = FALSE,lag.max = 200) # # Fonction d'autocorrélation des rendements centrés au carré AutoCorrelationCarreRES <- Acf(epsilon^2, plot = FALSE,lag.max = 200) # # Fonction d'autocorrélation des rendements centrés en valeur absolue AutoCorrelationAbsRES <- Acf(abs(epsilon), plot = FALSE,lag.max = 200) A.AutoCorrelation <- with(AutoCorrelation, data.frame(lag, acf)) x <- A.AutoCorrelation$lag y <- A.AutoCorrelation$acf lo.A <- loess(y~x) B.AutoCorrelation <- with(AutoCorrelationCarreRES, data.frame(lag, acf)) x <- B.AutoCorrelation$lag y <- B.AutoCorrelation$acf lo.B <- loess(y~x) C.AutoCorrelation <- with(AutoCorrelationAbsRES, data.frame(lag, acf)) x <- C.AutoCorrelation$lag y <- C.AutoCorrelation$acf lo.C <- loess(y~x) # Différence entre carré et val absolue D.AutoCorrelation <- data.frame(B.AutoCorrelation$lag, (C.AutoCorrelation-B.AutoCorrelation)$acf) names(D.AutoCorrelation) <- c("lag","acf") A <- ggplot(data = A.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title=paste("ACF des log-rendements de ",index,sep=""), x ="Lags", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.A)), color = "red", linetype = 1,lwd=lwd.predict) B <- ggplot(data = B.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title=paste("ACF des log-rendements centrés au carré de ",index,sep=""), x ="Lags", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.B)), color = "red", linetype = 1,lwd=lwd.predict) C <- ggplot(data = C.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title=paste("ACF de la valeur absolue des log-rendements centrés de ",index,sep=""), x ="Lags", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.C)), color = "red", linetype = 1,lwd=lwd.predict) D <- ggplot(data = D.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Différence entre Corrélation valeur absolue et au carré", x ="Lags", y = "Différence") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) p <- plot_grid(A,B,C,D, labels = "AUTO", ncol = 1) ggsave(paste(GraphPath,"/1 - DataStats/Dataset_ACF_",index,".png",sep=""), p) # -------------------------------------------------------- # Point (3) : Clustering des volatilités # -------------------------------------------------------- # Plot the dataset and export resulting plot jpeg(paste(GraphPath,"/1 - DataStats/Dataset_",index,".png",sep=""), width = image.width, height = image.heigth) layout(matrix(c(1,2),2,1,byrow=TRUE)) par(mar = rep(6, 4)) # Set the margin on all sides to 2 xtick<-seq(1, length(dates), by=floor(length(dates)/nbTicks)) plot(Pt,type="l",xlab="Dates",ylab="Value", xaxt="n", cex.axis=1.8, cex.lab=2) axis(side=1, at=xtick, labels=dates[xtick], cex.axis=1.8) title(main=paste("Valeur de l'indice ",index,sep=""), cex.main=2) plot(logR,type="l",xlab="Dates", xaxt="n", cex.axis=1.8, cex.lab=2) axis(side=1, at=xtick, labels=dates[xtick], cex.axis=1.8) title(main=paste("Log-rendement sur l'indice ",index,sep=""), cex.main=2) abline(h=0, col="blue") dev.off() # -------------------------------------------------------- # Point (4) : Asymétrie négative et grand aplatissement # -------------------------------------------------------- #descriptive statistics des_stats <- c("Moyenne" = mean(logR), "Écart-type" = sd(logR), "Asymétrie" = timeDate::skewness(logR, method="moment"), "Aplatissement" = timeDate::kurtosis(logR, method="moment"), "Minimum" = min(logR), "Maximum" = max(logR), "n" = length(logR) ) des_stats # -------------------------------------------------------- # Point (5) : Effet de levier # -------------------------------------------------------- maxf <- function(x){max(x,0)} negChoc <- sapply(-epsilon,FUN=maxf) posChoc <- sapply(epsilon,FUN=maxf) # Corrélation entre la valeur absolue des erreurs et un choc négatif AutoCorrelationLEVIER.NEG <- Ccf(abs(epsilon), negChoc, plot=F,lag.max = 200,level=0.95) # Corrélation entre la valeur absolue des erreurs et un choc positif AutoCorrelationLEVIER.POS <- Ccf(abs(epsilon), posChoc, plot=F,lag.max = 200) NEG.AutoCorrelation <- with(AutoCorrelationLEVIER.NEG, data.frame(lag, acf)) NEG.AutoCorrelation.df <- subset(NEG.AutoCorrelation, lag >= 0) x <- NEG.AutoCorrelation.df$lag y <- NEG.AutoCorrelation.df$acf lo.LEVIER.NEG <- loess(y~x) POS.AutoCorrelation <- with(AutoCorrelationLEVIER.POS, data.frame(lag, acf)) POS.AutoCorrelation.df <- subset(POS.AutoCorrelation, lag >= 0) x <- POS.AutoCorrelation.df$lag y <- POS.AutoCorrelation.df$acf lo.LEVIER.POS <- loess(y~x) # Corrélation entre la valeur absolue des erreurs et un choc positif AutoCorrelationLEVIER.DIFF <- data.frame(NEG.AutoCorrelation.df$lag, (NEG.AutoCorrelation.df-POS.AutoCorrelation.df)$acf) names(AutoCorrelationLEVIER.DIFF) <- c("lag","acf") NEG <- ggplot(data = NEG.AutoCorrelation.df, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue') + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue') + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Corrélation avec un choc négatif", x ="Lag", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.LEVIER.NEG)), color = "red", linetype = 1,lwd=lwd.predict) POS <- ggplot(data = POS.AutoCorrelation.df, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue') + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue') + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Corrélation avec un choc positif", x ="Lag", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.LEVIER.POS)), color = "red", linetype = 1,lwd=lwd.predict) DIFF <- ggplot(data = AutoCorrelationLEVIER.DIFF, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue') + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue') + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Corrélation choc négatif - Corrélation choc positif", x ="Lag", y = "Différence") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) p <- plot_grid(NEG,POS,DIFF, labels = "AUTO", ncol = 1) ggsave(paste(GraphPath,"/1 - DataStats/Dataset_LEVIER_",index,".png",sep=""), p)
/package/HMM/Faits_Stylises.R
no_license
GabrielLemyre/HHMM
R
false
false
12,168
r
# ---------------------------------------------------------------------------------------------------- # Hidden Markov Models # Faits stylisés des rendements financiers # ---------------------------------------------------------------------------------------------------- # written # Gabriel LEMYRE # ---------------------------------------------------------------------------------------------------- # Under the supervision of : # Maciej AUGUSTYNIAK # ---------------------------------------------------------------------------------------------------- # First version : january 8th, 2020 # Last version : february 13th, 2020 # ---------------------------------------------------------------------------------------------------- # -------------------------------------------------------- # ANALYSE D'UNE SÉRIE ET RÉSULTATS SUR LES FAITS STYLISÉS # -------------------------------------------------------- # Fonction produisant des tables et graphiques # L'idée est de montrer qu'une série présente les # caractéristiques des faits stylisés des rendements # financiers # -------------------------------------------------------- # Instalation du package forecast permettant d'utiliser les fonctions ACF, PAcf et CCf # install.packages('forecast', dependencies = TRUE) # Installation du package library(forecast) # Permet de créer des graphiques très complexes # install.packages('ggplot2', dependencies = TRUE) # Installation du package library(ggplot2) # Instalation du package cowplot opermettant de combiner des graphiques # install.packages('cowplot', dependencies = TRUE) # Installation du package library(cowplot) # -------------------------------------------------------- # Paramètres graphiques # -------------------------------------------------------- title.size.var <- 12 axis.lab.size.var <- 8 lty.ciline <- 2 lwd.ciline <- 0.3 lwd.predict <- 0.2 # Nombre de points à afficher sur l'axe horizontal nbTicks=10 # JPEG DIMENSIONS FOR OUTPUTED FILE image.width <- 1250 image.heigth <- 666 # Faits stylisés title.size.var <- 12 axis.lab.size.var <- 8 resdev=300 # -------------------- # -------------------------------------------------------- # Point (1) et (2) : Absence d'acf pour rendement mais # présence pour erreurs^2 et abs(erreurs) # -------------------------------------------------------- epsilon <- logR-mean(logR) conf.level <- 0.95 ciline <- qnorm((1 - conf.level)/2)/sqrt(length(epsilon)) # Fonction d'autocorrélation des rendements AutoCorrelation <- Acf(logR, plot = FALSE,lag.max = 200) # # Fonction d'autocorrélation des rendements centrés au carré AutoCorrelationCarreRES <- Acf(epsilon^2, plot = FALSE,lag.max = 200) # # Fonction d'autocorrélation des rendements centrés en valeur absolue AutoCorrelationAbsRES <- Acf(abs(epsilon), plot = FALSE,lag.max = 200) A.AutoCorrelation <- with(AutoCorrelation, data.frame(lag, acf)) x <- A.AutoCorrelation$lag y <- A.AutoCorrelation$acf lo.A <- loess(y~x) B.AutoCorrelation <- with(AutoCorrelationCarreRES, data.frame(lag, acf)) x <- B.AutoCorrelation$lag y <- B.AutoCorrelation$acf lo.B <- loess(y~x) C.AutoCorrelation <- with(AutoCorrelationAbsRES, data.frame(lag, acf)) x <- C.AutoCorrelation$lag y <- C.AutoCorrelation$acf lo.C <- loess(y~x) # Différence entre carré et val absolue D.AutoCorrelation <- data.frame(B.AutoCorrelation$lag, (C.AutoCorrelation-B.AutoCorrelation)$acf) names(D.AutoCorrelation) <- c("lag","acf") A <- ggplot(data = A.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title=paste("ACF des log-rendements de ",index,sep=""), x ="Lags", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.A)), color = "red", linetype = 1,lwd=lwd.predict) B <- ggplot(data = B.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title=paste("ACF des log-rendements centrés au carré de ",index,sep=""), x ="Lags", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.B)), color = "red", linetype = 1,lwd=lwd.predict) C <- ggplot(data = C.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title=paste("ACF de la valeur absolue des log-rendements centrés de ",index,sep=""), x ="Lags", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.C)), color = "red", linetype = 1,lwd=lwd.predict) D <- ggplot(data = D.AutoCorrelation, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue', size=lwd.ciline) + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Différence entre Corrélation valeur absolue et au carré", x ="Lags", y = "Différence") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) p <- plot_grid(A,B,C,D, labels = "AUTO", ncol = 1) ggsave(paste(GraphPath,"/1 - DataStats/Dataset_ACF_",index,".png",sep=""), p) # -------------------------------------------------------- # Point (3) : Clustering des volatilités # -------------------------------------------------------- # Plot the dataset and export resulting plot jpeg(paste(GraphPath,"/1 - DataStats/Dataset_",index,".png",sep=""), width = image.width, height = image.heigth) layout(matrix(c(1,2),2,1,byrow=TRUE)) par(mar = rep(6, 4)) # Set the margin on all sides to 2 xtick<-seq(1, length(dates), by=floor(length(dates)/nbTicks)) plot(Pt,type="l",xlab="Dates",ylab="Value", xaxt="n", cex.axis=1.8, cex.lab=2) axis(side=1, at=xtick, labels=dates[xtick], cex.axis=1.8) title(main=paste("Valeur de l'indice ",index,sep=""), cex.main=2) plot(logR,type="l",xlab="Dates", xaxt="n", cex.axis=1.8, cex.lab=2) axis(side=1, at=xtick, labels=dates[xtick], cex.axis=1.8) title(main=paste("Log-rendement sur l'indice ",index,sep=""), cex.main=2) abline(h=0, col="blue") dev.off() # -------------------------------------------------------- # Point (4) : Asymétrie négative et grand aplatissement # -------------------------------------------------------- #descriptive statistics des_stats <- c("Moyenne" = mean(logR), "Écart-type" = sd(logR), "Asymétrie" = timeDate::skewness(logR, method="moment"), "Aplatissement" = timeDate::kurtosis(logR, method="moment"), "Minimum" = min(logR), "Maximum" = max(logR), "n" = length(logR) ) des_stats # -------------------------------------------------------- # Point (5) : Effet de levier # -------------------------------------------------------- maxf <- function(x){max(x,0)} negChoc <- sapply(-epsilon,FUN=maxf) posChoc <- sapply(epsilon,FUN=maxf) # Corrélation entre la valeur absolue des erreurs et un choc négatif AutoCorrelationLEVIER.NEG <- Ccf(abs(epsilon), negChoc, plot=F,lag.max = 200,level=0.95) # Corrélation entre la valeur absolue des erreurs et un choc positif AutoCorrelationLEVIER.POS <- Ccf(abs(epsilon), posChoc, plot=F,lag.max = 200) NEG.AutoCorrelation <- with(AutoCorrelationLEVIER.NEG, data.frame(lag, acf)) NEG.AutoCorrelation.df <- subset(NEG.AutoCorrelation, lag >= 0) x <- NEG.AutoCorrelation.df$lag y <- NEG.AutoCorrelation.df$acf lo.LEVIER.NEG <- loess(y~x) POS.AutoCorrelation <- with(AutoCorrelationLEVIER.POS, data.frame(lag, acf)) POS.AutoCorrelation.df <- subset(POS.AutoCorrelation, lag >= 0) x <- POS.AutoCorrelation.df$lag y <- POS.AutoCorrelation.df$acf lo.LEVIER.POS <- loess(y~x) # Corrélation entre la valeur absolue des erreurs et un choc positif AutoCorrelationLEVIER.DIFF <- data.frame(NEG.AutoCorrelation.df$lag, (NEG.AutoCorrelation.df-POS.AutoCorrelation.df)$acf) names(AutoCorrelationLEVIER.DIFF) <- c("lag","acf") NEG <- ggplot(data = NEG.AutoCorrelation.df, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue') + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue') + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Corrélation avec un choc négatif", x ="Lag", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.LEVIER.NEG)), color = "red", linetype = 1,lwd=lwd.predict) POS <- ggplot(data = POS.AutoCorrelation.df, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue') + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue') + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Corrélation avec un choc positif", x ="Lag", y = "Auto-Corrélation") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) + geom_line(aes(x = lag, y = predict(lo.LEVIER.POS)), color = "red", linetype = 1,lwd=lwd.predict) DIFF <- ggplot(data = AutoCorrelationLEVIER.DIFF, mapping = aes(x = lag, y = acf)) + geom_hline(aes(yintercept = 0)) + geom_hline(aes(yintercept = ciline), linetype = lty.ciline, color = 'darkblue') + geom_hline(aes(yintercept = -ciline), linetype = lty.ciline, color = 'darkblue') + geom_segment(mapping = aes(xend = lag, yend = 0)) + labs(title="Corrélation choc négatif - Corrélation choc positif", x ="Lag", y = "Différence") + theme( plot.title = element_text(color="Black", size=title.size.var, face="bold.italic"), axis.title.x = element_text(color="black", size=axis.lab.size.var, face="bold"), axis.title.y = element_text(color="black", size=axis.lab.size.var, face="bold") ) p <- plot_grid(NEG,POS,DIFF, labels = "AUTO", ncol = 1) ggsave(paste(GraphPath,"/1 - DataStats/Dataset_LEVIER_",index,".png",sep=""), p)
library(tidyverse) library(lubridate) library(janitor) library(miceadds) source.all("functions/") dir.create("4_clean_data/temp") # Home Nations countries <- c("england", "scotland", "wales", "ireland") for (i in 1:length(countries)){ country <- countries[i] file_path <- paste("2_raw_data/", country, ".csv", sep = "") country_data <- read_csv(file_path) clean_data <- clean_rugby_data(country_data) %>% mutate(country = str_to_title(country)) %>% fix_home_nation_location() dir_path <- paste("4_clean_data/", country, sep ="") dir.create(dir_path) clean_file_path <- paste("4_clean_data/",country, "/", country, "_clean", ".csv", sep = "") clean_data %>% write_csv(clean_file_path) clean_file_path <- paste("4_clean_data/temp/", country, ".csv", sep = "") clean_data %>% write_csv(clean_file_path) } # Clean France Data france <- read_csv("2_raw_data/france.csv") clean_data <- clean_rugby_data(france) %>% mutate(country = "France") %>% fix_france_location() dir_path <- paste("4_clean_data/france") dir.create(dir_path) clean_data %>% write_csv("4_clean_data/france/france_clean.csv") clean_data %>% write_csv("4_clean_data/temp/france_clean.csv") italy <- read_csv("2_raw_data/italy.csv") clean_data <- clean_rugby_data(italy) %>% mutate(country = "Italy") %>% fix_italy_location() dir_path <- paste("4_clean_data/italy") dir.create(dir_path) clean_data %>% write_csv("4_clean_data/italy/italy_clean.csv") clean_data %>% write_csv("4_clean_data/temp/italy_clean.csv") files <- c() for (file in list.files("4_clean_data/temp")){ file_path <- paste("4_clean_data/temp/", file, sep = "") files <- c(files, file_path) } complete_data <- NULL for (file in files){ part_data <- read_csv(file) complete_data <-bind_rows(complete_data, part_data) } complete_data %>% relocate(country, .before = cap_no) %>% write_csv("4_clean_data/full_table.csv") unlink("4_clean_data/temp/", recursive = TRUE)
/3_cleaning_scripts/1_home_nations_clean_data.R
no_license
hgw2/rugby_players_project
R
false
false
2,030
r
library(tidyverse) library(lubridate) library(janitor) library(miceadds) source.all("functions/") dir.create("4_clean_data/temp") # Home Nations countries <- c("england", "scotland", "wales", "ireland") for (i in 1:length(countries)){ country <- countries[i] file_path <- paste("2_raw_data/", country, ".csv", sep = "") country_data <- read_csv(file_path) clean_data <- clean_rugby_data(country_data) %>% mutate(country = str_to_title(country)) %>% fix_home_nation_location() dir_path <- paste("4_clean_data/", country, sep ="") dir.create(dir_path) clean_file_path <- paste("4_clean_data/",country, "/", country, "_clean", ".csv", sep = "") clean_data %>% write_csv(clean_file_path) clean_file_path <- paste("4_clean_data/temp/", country, ".csv", sep = "") clean_data %>% write_csv(clean_file_path) } # Clean France Data france <- read_csv("2_raw_data/france.csv") clean_data <- clean_rugby_data(france) %>% mutate(country = "France") %>% fix_france_location() dir_path <- paste("4_clean_data/france") dir.create(dir_path) clean_data %>% write_csv("4_clean_data/france/france_clean.csv") clean_data %>% write_csv("4_clean_data/temp/france_clean.csv") italy <- read_csv("2_raw_data/italy.csv") clean_data <- clean_rugby_data(italy) %>% mutate(country = "Italy") %>% fix_italy_location() dir_path <- paste("4_clean_data/italy") dir.create(dir_path) clean_data %>% write_csv("4_clean_data/italy/italy_clean.csv") clean_data %>% write_csv("4_clean_data/temp/italy_clean.csv") files <- c() for (file in list.files("4_clean_data/temp")){ file_path <- paste("4_clean_data/temp/", file, sep = "") files <- c(files, file_path) } complete_data <- NULL for (file in files){ part_data <- read_csv(file) complete_data <-bind_rows(complete_data, part_data) } complete_data %>% relocate(country, .before = cap_no) %>% write_csv("4_clean_data/full_table.csv") unlink("4_clean_data/temp/", recursive = TRUE)
# Package Start-up Functions .onAttach <- function(libname, pkgname) { if (interactive() && is.null(options('bhklab.startup_'))) { oldOpts <- options() options(warn=-1) on.exit(options(oldOpts)) packageStartupMessage( " RadioGx package brought to you by: \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u255a\u2550\u2550\u2550\u2550\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u255d For more of our work visit bhklab.ca! " ) # Prevent repeated messages when loading multiple lab packages options(bhklab.startup_=FALSE) } }
/R/zzz.R
no_license
bhklab/RadioGx
R
false
false
1,977
r
# Package Start-up Functions .onAttach <- function(libname, pkgname) { if (interactive() && is.null(options('bhklab.startup_'))) { oldOpts <- options() options(warn=-1) on.exit(options(oldOpts)) packageStartupMessage( " RadioGx package brought to you by: \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255d \u255a\u2550\u2550\u2550\u2550\u2550\u255d \u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u255d\u255a\u2550\u255d \u255a\u2550\u255d\u255a\u2550\u2550\u2550\u2550\u2550\u255d For more of our work visit bhklab.ca! " ) # Prevent repeated messages when loading multiple lab packages options(bhklab.startup_=FALSE) } }
require(dplyr) require(ggplot2) require(tidyr) require(reshape2) require(gtools) require(mice) require(dummies) require(e1071) require(mice) require(scales) set.seed(12345) #load data sets sessions_df <- read.csv("sessions.csv", header=TRUE) train_df_start <- read.csv("train_users_2.csv", header=TRUE) summarystats_df <- read.csv("age_gender_bkts.csv") countries_df <- read.csv("countries.csv") ## Sessions Wrangling sessions_df <- group_by(sessions_df, user_id) sessions_summary <- sessions_df %>% group_by(user_id) %>% summarise(secs_elapsed_avg = mean(secs_elapsed, na.rm=TRUE), secs_elapsed_total = sum(secs_elapsed, na.rm=TRUE), secs_elapsed_sd = sd(secs_elapsed, na.rm=TRUE), secs_elapsed_min= min(secs_elapsed, na.rm=TRUE), secs_elapsed_max = max(secs_elapsed, na.rm=TRUE), secs_elapsed_median = median(secs_elapsed, na.rm=TRUE), secs_elapsed_IQR = IQR(secs_elapsed, na.rm=TRUE)) sessions_summary_pl <- sessions_df %>% group_by(user_id) %>% count(user_id) sessions_sum2 <- select(sessions_df, user_id, device_type) %>% distinct(device_type) colnames(sessions_summary_pl)[2] <- "total_actions" sessions_summary <- merge(sessions_summary, sessions_summary_pl, by="user_id") sessions_summary <- filter(sessions_summary, user_id != "") sessions_summary[is.na(sessions_summary)==TRUE] <- 0 sessions_actions <- select(sessions_df, user_id, action) sessions_actions2 <- melt(sessions_actions, id="user_id", na.rm=TRUE) sessions_actions2 <- dcast(sessions_actions2, user_id ~ value + variable, length) sessions_actions2 <- filter(sessions_actions2, user_id != "") names(sessions_actions2)[2] <- "blank_action" sessions_device <- select(sessions_df, user_id, device_type) sessions_device2 <- sessions_device %>% group_by(user_id) %>% summarize(device_type = names(which.max(table(device_type)))) sessions_device2 <- filter(sessions_device2, user_id != "") sessions_device3 <- melt(sessions_device2, id="user_id", na.rm=TRUE) sessions_device3 <- dcast(sessions_device3, user_id ~ value + variable, length) sessions_summary <- left_join(sessions_summary, sessions_device3, by="user_id") sessions_final <- left_join(sessions_summary, sessions_actions2, by="user_id") ##Training set wrangling train_df1 <- train_df_start colnames(train_df1)[1] <- "user_id" #Fix date objects train_df1$date_account_created <- as.Date(train_df1$date_account_created) train_df1$date_first_booking <- NULL train_df1$timestamp_first_active[train_df1$timestamp_first_active == ""] <- NA train_df1$timestamp_first_active <- as.POSIXct(as.character(train_df1$timestamp_first_active), format="%Y%m%d%H%M%S") train_df1$timestamp_first_active <- as.Date(train_df1$timestamp_first_active, format="%Y-%m-%d") train_df1$timestamp_first_active[is.na(train_df1$timestamp_first_active)==TRUE] <- train_df1$date_account_created #Clean up age train_df1$age[train_df1$age > 98] <- NA train_df1$age[train_df1$age < 15] <- NA train_df1$age[is.na(train_df1$age)==TRUE] <- -1 train_df1$first_affiliate_tracked[train_df1$first_affiliate_tracked == ""] <- NA train_df1$country_destination <- as.factor(train_df1$country_destination) #Optional NA replacement train_df2 <- train_df1 train_df2[is.na(train_df2)] <- -1 train_dfclean <- train_df2 train_age <- train_dfclean[, c("user_id", "age")] #train_dfclean$age <- NULL #Feature Engineering train_fe <- train_dfclean train_fe <- dummy.data.frame(train_fe, names=c("gender", "signup_method", "signup_flow", "language", "affiliate_channel", "affiliate_provider", "first_affiliate_tracked", "signup_app", "first_device_type", "first_browser"), omit.constants = TRUE, sep="_", fun=as.numeric, dummy.classes = "numeric") train_fe <- separate(train_fe, date_account_created, into=c("year_account_created", "month_account_created", "day_account_created"), sep="-") train_fe <- separate(train_fe, timestamp_first_active, into=c("year_first_active", "month_first_active", "day_first_active"), sep="-") train_fe <- transform(train_fe, year_account_created = as.numeric(year_account_created), month_account_created=as.numeric(month_account_created), day_account_created=as.numeric(day_account_created), year_first_active=as.numeric(year_first_active), month_first_active=as.numeric(month_first_active), day_first_active=as.numeric(day_first_active)) train_fe$destination_booked <- train_fe$country_destination != "NDF" train_join <- train_fe train_join[is.na(train_join)] <- -1 #Join sessions and train sets train_full <- inner_join(train_join, sessions_final, by="user_id") outcome_labels <- bind_cols(as.data.frame(outcome), as.data.frame(outcome.org)) outcome_labels$outcome <- as.factor(outcome_labels$outcome) outcome_labels <- levels(outcome_labels$outcome.org) train_boost1 <- train_full outcome1.org <- train_boost1[, "destination_booked"] outcome1 <- outcome1.org num.class1 = length(levels(outcome1)) levels(outcome1) = 1:num.class1 outcome1 <- as.numeric(outcome1) outcome.org <- train_boost1[, "country_destination"] outcome <- outcome.org num.class = length(levels(outcome)) levels(outcome) = 1:num.class outcome <- as.numeric(outcome) outcome <- outcome - 1 outcome_labels <- bind_cols(as.data.frame(outcome), as.data.frame(outcome.org)) outcome_labels$outcome <- as.factor(outcome_labels$outcome) outcome_labels <- levels(outcome_labels$outcome.org) train_boost1$country_destination <- NULL train_boost1$destination_booked <- NULL train_boost2 <- train_join outcome2.org <- train_boost2[, "country_destination"] outcome2 <- outcome2.org num.class2 = length(levels(outcome2)) levels(outcome2) = 1:num.class2 outcome2 <- as.numeric(outcome2) outcome2 <- outcome2 - 1 outcome2_labels <- bind_cols(as.data.frame(outcome2), as.data.frame(outcome2.org)) outcome2_labels$outcome <- as.factor(outcome2_labels$outcome2) outcome2_labels <- levels(outcome2_labels$outcome2.org) train_boost2$country_destination <- NULL train_boost2$destination_booked <- NULL #other junk actions <- as.data.frame(levels(sessions_df$action)) colnames(actions) <- "actions" #Graphs! ggplot(train_df1, aes(x=timestamp_first_active, fill=first_affiliate_tracked)) + geom_histogram(binwidth = 250) ggplot(train_df1, aes(x=age))+ geom_histogram() destination_summary <- as.data.frame(summary(train_df1$country_destination)) colnames(destination_summary) <- "Count" destination_summary$Percentages <- percent(prop.table(destination_summary$Count)) destination_summary$Destination <- rownames(destination_summary) destination_summary <- destination_summary[,c(3,1:2)] destination_summary <- arrange(destination_summary, desc(Count)) write.csv(destination_summary, "destination_summary.csv", row.names=TRUE) ggplot(train_df1, aes(x=date_account_created)) + geom_histogram(color="black", fill="blue", bins=42) + ggtitle("Accounts Created Over Time") + xlab("Date Account Created") + ylab("Frequency") agebyyear <- as.data.frame(train_df_start$age) colnames(agebyyear) <- "Age" agebyyear$Year <- as.numeric(train_fe$year_account_created) ggplot(agebyyear, aes(x=Age)) + geom_histogram(breaks=c(min(agebyyear$Age), seq(10,100,5), max(agebyyear$Age)), fill="red", col="black") ggplot(agebyyear, aes(x=Year, y=Age)) + geom_jitter(col="blue") summary(agebyyear$Age) summary(ageoutliers) firstdevice <- as.data.frame(train_fe$year_account_created) colnames(firstdevice) <- "Year" firstdevice$First_Device <- train_df_start$first_device_type firstdevice2010 <- filter(firstdevice, Year == 2010) colnames(firstdevice2010) <- c("Year", "2010") firstdevice2010table <- as.data.frame(table(firstdevice2010$"2010")) firstdevice2010table$Freq <- prop.table(firstdevice2010table$Freq) firstdevice2011 <- filter(firstdevice, Year == 2011) colnames(firstdevice2011) <- c("Year", "2011") firstdevice2011table <- as.data.frame(table(firstdevice2011$"2011")) firstdevice2011table$Freq <- prop.table(firstdevice2011table$Freq) firstdevice2012 <- filter(firstdevice, Year == 2012) colnames(firstdevice2012) <- c("Year", "2012") firstdevice2012table <- as.data.frame(table(firstdevice2012$"2012")) firstdevice2012table$Freq <- prop.table(firstdevice2012table$Freq) firstdevice2013 <- filter(firstdevice, Year == 2013) colnames(firstdevice2013) <- c("Year", "2013") firstdevice2013table <- as.data.frame(table(firstdevice2013$"2013")) firstdevice2013table$Freq <- prop.table(firstdevice2013table$Freq) firstdevice2014 <- filter(firstdevice, Year == 2014) colnames(firstdevice2014) <- c("Year", "2014") firstdevice2014table <- as.data.frame(table(firstdevice2014$"2014")) firstdevice2014table$Freq <- prop.table(firstdevice2014table$Freq) firstdevicefull <- full_join(firstdevice2010table, firstdevice2011table, by="Var1") firstdevicefull <- full_join(firstdevicefull, firstdevice2012table, by="Var1") firstdevicefull <- full_join(firstdevicefull, firstdevice2013table, by="Var1") firstdevicefull <- full_join(firstdevicefull, firstdevice2014table, by="Var1") colnames(firstdevicefull) <- c("Device", "2010", "2011", "2012", "2013", "2014") firstdevicefull[,2:6] <- round(firstdevicefull[,2:6], 4) write.csv(firstdevicefull, "firstdevicefull.csv")
/wrangle_code.R
no_license
zrodnick/airbnb_capstone
R
false
false
9,055
r
require(dplyr) require(ggplot2) require(tidyr) require(reshape2) require(gtools) require(mice) require(dummies) require(e1071) require(mice) require(scales) set.seed(12345) #load data sets sessions_df <- read.csv("sessions.csv", header=TRUE) train_df_start <- read.csv("train_users_2.csv", header=TRUE) summarystats_df <- read.csv("age_gender_bkts.csv") countries_df <- read.csv("countries.csv") ## Sessions Wrangling sessions_df <- group_by(sessions_df, user_id) sessions_summary <- sessions_df %>% group_by(user_id) %>% summarise(secs_elapsed_avg = mean(secs_elapsed, na.rm=TRUE), secs_elapsed_total = sum(secs_elapsed, na.rm=TRUE), secs_elapsed_sd = sd(secs_elapsed, na.rm=TRUE), secs_elapsed_min= min(secs_elapsed, na.rm=TRUE), secs_elapsed_max = max(secs_elapsed, na.rm=TRUE), secs_elapsed_median = median(secs_elapsed, na.rm=TRUE), secs_elapsed_IQR = IQR(secs_elapsed, na.rm=TRUE)) sessions_summary_pl <- sessions_df %>% group_by(user_id) %>% count(user_id) sessions_sum2 <- select(sessions_df, user_id, device_type) %>% distinct(device_type) colnames(sessions_summary_pl)[2] <- "total_actions" sessions_summary <- merge(sessions_summary, sessions_summary_pl, by="user_id") sessions_summary <- filter(sessions_summary, user_id != "") sessions_summary[is.na(sessions_summary)==TRUE] <- 0 sessions_actions <- select(sessions_df, user_id, action) sessions_actions2 <- melt(sessions_actions, id="user_id", na.rm=TRUE) sessions_actions2 <- dcast(sessions_actions2, user_id ~ value + variable, length) sessions_actions2 <- filter(sessions_actions2, user_id != "") names(sessions_actions2)[2] <- "blank_action" sessions_device <- select(sessions_df, user_id, device_type) sessions_device2 <- sessions_device %>% group_by(user_id) %>% summarize(device_type = names(which.max(table(device_type)))) sessions_device2 <- filter(sessions_device2, user_id != "") sessions_device3 <- melt(sessions_device2, id="user_id", na.rm=TRUE) sessions_device3 <- dcast(sessions_device3, user_id ~ value + variable, length) sessions_summary <- left_join(sessions_summary, sessions_device3, by="user_id") sessions_final <- left_join(sessions_summary, sessions_actions2, by="user_id") ##Training set wrangling train_df1 <- train_df_start colnames(train_df1)[1] <- "user_id" #Fix date objects train_df1$date_account_created <- as.Date(train_df1$date_account_created) train_df1$date_first_booking <- NULL train_df1$timestamp_first_active[train_df1$timestamp_first_active == ""] <- NA train_df1$timestamp_first_active <- as.POSIXct(as.character(train_df1$timestamp_first_active), format="%Y%m%d%H%M%S") train_df1$timestamp_first_active <- as.Date(train_df1$timestamp_first_active, format="%Y-%m-%d") train_df1$timestamp_first_active[is.na(train_df1$timestamp_first_active)==TRUE] <- train_df1$date_account_created #Clean up age train_df1$age[train_df1$age > 98] <- NA train_df1$age[train_df1$age < 15] <- NA train_df1$age[is.na(train_df1$age)==TRUE] <- -1 train_df1$first_affiliate_tracked[train_df1$first_affiliate_tracked == ""] <- NA train_df1$country_destination <- as.factor(train_df1$country_destination) #Optional NA replacement train_df2 <- train_df1 train_df2[is.na(train_df2)] <- -1 train_dfclean <- train_df2 train_age <- train_dfclean[, c("user_id", "age")] #train_dfclean$age <- NULL #Feature Engineering train_fe <- train_dfclean train_fe <- dummy.data.frame(train_fe, names=c("gender", "signup_method", "signup_flow", "language", "affiliate_channel", "affiliate_provider", "first_affiliate_tracked", "signup_app", "first_device_type", "first_browser"), omit.constants = TRUE, sep="_", fun=as.numeric, dummy.classes = "numeric") train_fe <- separate(train_fe, date_account_created, into=c("year_account_created", "month_account_created", "day_account_created"), sep="-") train_fe <- separate(train_fe, timestamp_first_active, into=c("year_first_active", "month_first_active", "day_first_active"), sep="-") train_fe <- transform(train_fe, year_account_created = as.numeric(year_account_created), month_account_created=as.numeric(month_account_created), day_account_created=as.numeric(day_account_created), year_first_active=as.numeric(year_first_active), month_first_active=as.numeric(month_first_active), day_first_active=as.numeric(day_first_active)) train_fe$destination_booked <- train_fe$country_destination != "NDF" train_join <- train_fe train_join[is.na(train_join)] <- -1 #Join sessions and train sets train_full <- inner_join(train_join, sessions_final, by="user_id") outcome_labels <- bind_cols(as.data.frame(outcome), as.data.frame(outcome.org)) outcome_labels$outcome <- as.factor(outcome_labels$outcome) outcome_labels <- levels(outcome_labels$outcome.org) train_boost1 <- train_full outcome1.org <- train_boost1[, "destination_booked"] outcome1 <- outcome1.org num.class1 = length(levels(outcome1)) levels(outcome1) = 1:num.class1 outcome1 <- as.numeric(outcome1) outcome.org <- train_boost1[, "country_destination"] outcome <- outcome.org num.class = length(levels(outcome)) levels(outcome) = 1:num.class outcome <- as.numeric(outcome) outcome <- outcome - 1 outcome_labels <- bind_cols(as.data.frame(outcome), as.data.frame(outcome.org)) outcome_labels$outcome <- as.factor(outcome_labels$outcome) outcome_labels <- levels(outcome_labels$outcome.org) train_boost1$country_destination <- NULL train_boost1$destination_booked <- NULL train_boost2 <- train_join outcome2.org <- train_boost2[, "country_destination"] outcome2 <- outcome2.org num.class2 = length(levels(outcome2)) levels(outcome2) = 1:num.class2 outcome2 <- as.numeric(outcome2) outcome2 <- outcome2 - 1 outcome2_labels <- bind_cols(as.data.frame(outcome2), as.data.frame(outcome2.org)) outcome2_labels$outcome <- as.factor(outcome2_labels$outcome2) outcome2_labels <- levels(outcome2_labels$outcome2.org) train_boost2$country_destination <- NULL train_boost2$destination_booked <- NULL #other junk actions <- as.data.frame(levels(sessions_df$action)) colnames(actions) <- "actions" #Graphs! ggplot(train_df1, aes(x=timestamp_first_active, fill=first_affiliate_tracked)) + geom_histogram(binwidth = 250) ggplot(train_df1, aes(x=age))+ geom_histogram() destination_summary <- as.data.frame(summary(train_df1$country_destination)) colnames(destination_summary) <- "Count" destination_summary$Percentages <- percent(prop.table(destination_summary$Count)) destination_summary$Destination <- rownames(destination_summary) destination_summary <- destination_summary[,c(3,1:2)] destination_summary <- arrange(destination_summary, desc(Count)) write.csv(destination_summary, "destination_summary.csv", row.names=TRUE) ggplot(train_df1, aes(x=date_account_created)) + geom_histogram(color="black", fill="blue", bins=42) + ggtitle("Accounts Created Over Time") + xlab("Date Account Created") + ylab("Frequency") agebyyear <- as.data.frame(train_df_start$age) colnames(agebyyear) <- "Age" agebyyear$Year <- as.numeric(train_fe$year_account_created) ggplot(agebyyear, aes(x=Age)) + geom_histogram(breaks=c(min(agebyyear$Age), seq(10,100,5), max(agebyyear$Age)), fill="red", col="black") ggplot(agebyyear, aes(x=Year, y=Age)) + geom_jitter(col="blue") summary(agebyyear$Age) summary(ageoutliers) firstdevice <- as.data.frame(train_fe$year_account_created) colnames(firstdevice) <- "Year" firstdevice$First_Device <- train_df_start$first_device_type firstdevice2010 <- filter(firstdevice, Year == 2010) colnames(firstdevice2010) <- c("Year", "2010") firstdevice2010table <- as.data.frame(table(firstdevice2010$"2010")) firstdevice2010table$Freq <- prop.table(firstdevice2010table$Freq) firstdevice2011 <- filter(firstdevice, Year == 2011) colnames(firstdevice2011) <- c("Year", "2011") firstdevice2011table <- as.data.frame(table(firstdevice2011$"2011")) firstdevice2011table$Freq <- prop.table(firstdevice2011table$Freq) firstdevice2012 <- filter(firstdevice, Year == 2012) colnames(firstdevice2012) <- c("Year", "2012") firstdevice2012table <- as.data.frame(table(firstdevice2012$"2012")) firstdevice2012table$Freq <- prop.table(firstdevice2012table$Freq) firstdevice2013 <- filter(firstdevice, Year == 2013) colnames(firstdevice2013) <- c("Year", "2013") firstdevice2013table <- as.data.frame(table(firstdevice2013$"2013")) firstdevice2013table$Freq <- prop.table(firstdevice2013table$Freq) firstdevice2014 <- filter(firstdevice, Year == 2014) colnames(firstdevice2014) <- c("Year", "2014") firstdevice2014table <- as.data.frame(table(firstdevice2014$"2014")) firstdevice2014table$Freq <- prop.table(firstdevice2014table$Freq) firstdevicefull <- full_join(firstdevice2010table, firstdevice2011table, by="Var1") firstdevicefull <- full_join(firstdevicefull, firstdevice2012table, by="Var1") firstdevicefull <- full_join(firstdevicefull, firstdevice2013table, by="Var1") firstdevicefull <- full_join(firstdevicefull, firstdevice2014table, by="Var1") colnames(firstdevicefull) <- c("Device", "2010", "2011", "2012", "2013", "2014") firstdevicefull[,2:6] <- round(firstdevicefull[,2:6], 4) write.csv(firstdevicefull, "firstdevicefull.csv")
library(xml2) library(rvest) setwd("C:/Users/xia/Desktop/splcml-result/data1/") datasets <-c('nr','gpcr','ic','e') for (j in 1:4){ data <-read.csv(paste0(datasets[j],"_admat_dgc.csv"),header=F) data<- t(data[1,-1]) m<-dim(data)[1] dgname <- matrix(data=0,nrow = m,ncol = 1) for (i in 1:m){ site <- paste0("https://www.genome.jp/dbget-bin/www_bget?dr:",data[i,1]) webpage <- read_html(site) name1 <- html_nodes(webpage,'.td51 div div ') name1 <- gsub("<div style=\"width:555px;overflow-x:auto;overflow-y:hidden\">","",name1) name1 <- gsub("<br>\n</div>","",name1) name1 <- unlist(strsplit(name1, ";")) name1 <- name1[1] dgname[i] <- name1 } drugname <-data.frame(data,dgname) colnames(drugname) <- c('drugID','drugName') write.csv(drugname,paste0("drugName_",datasets[j],".csv"),row.names = F) }
/code for SPLCMF/rcode/drugIDtoName.R
no_license
Macau-LYXia/SPLCMF-DTI
R
false
false
846
r
library(xml2) library(rvest) setwd("C:/Users/xia/Desktop/splcml-result/data1/") datasets <-c('nr','gpcr','ic','e') for (j in 1:4){ data <-read.csv(paste0(datasets[j],"_admat_dgc.csv"),header=F) data<- t(data[1,-1]) m<-dim(data)[1] dgname <- matrix(data=0,nrow = m,ncol = 1) for (i in 1:m){ site <- paste0("https://www.genome.jp/dbget-bin/www_bget?dr:",data[i,1]) webpage <- read_html(site) name1 <- html_nodes(webpage,'.td51 div div ') name1 <- gsub("<div style=\"width:555px;overflow-x:auto;overflow-y:hidden\">","",name1) name1 <- gsub("<br>\n</div>","",name1) name1 <- unlist(strsplit(name1, ";")) name1 <- name1[1] dgname[i] <- name1 } drugname <-data.frame(data,dgname) colnames(drugname) <- c('drugID','drugName') write.csv(drugname,paste0("drugName_",datasets[j],".csv"),row.names = F) }
#how much memory the dataset will require print(object.size(read.delim("hh_power.txt", sep = ";",stringsAsFactors = FALSE)),units="Mb") #its okay to load the whole file & take a subset after power <- read.delim("hh_power.txt", sep = ";",stringsAsFactors = FALSE) #subset data powerss <- power[power$Date=="1/2/2007" | power$Date=="2/2/2007",] #formatting the date-variable d <- paste0(0, substr(powerss$Date,1,1)) m <- paste0(0, substr(powerss$Date,3,3)) y <- substr(powerss$Date,5,8) powerss$Date <- strptime(paste0(d,"/",m,"/",y),"%d/%m/%Y") powerss$Date <- as.Date(powerss$Date,"%Y-%m-%d") #powerss$Time <- strptime(powerss$Time, "%T") powerss$Global_active_power <- as.numeric(powerss$Global_active_power) powerss$Global_reactive_power <- as.numeric(powerss$Global_reactive_power) powerss$Voltage <- as.numeric(powerss$Voltage) powerss$Global_intensity <- as.numeric(powerss$Global_intensity) powerss$Sub_metering_1 <- as.numeric(powerss$Sub_metering_1) powerss$Sub_metering_2 <- as.numeric(powerss$Sub_metering_2) powerss$Sub_metering_3 <- as.numeric(powerss$Sub_metering_3) #Plot 4 png(filename = "plot4.png", width = 480, height = 480, units = "px", pointsize = 12, bg = "white") par(mfrow=c(2,2)) #1 plot(powerss$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) #2 plot(powerss$Voltage, type="l", ylab="Voltage", xlab="datetime", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) #3 plot(powerss$Sub_metering_1, type="l", ylab="Energy sub metering", xlab="", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) lines(powerss$Sub_metering_2, col="red") lines(powerss$Sub_metering_3, col="blue") legend("topright", legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),cex=0.5, lty=c(1,1,1), col=c("black","red", "blue")) #4 plot(powerss$Global_reactive_power, type="l", ylab="Global_reactive_power", xlab="datetime", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) par(mfrow=c(1,1)) dev.off()
/plot4.R
no_license
mamack/exploratory-graphs
R
false
false
2,096
r
#how much memory the dataset will require print(object.size(read.delim("hh_power.txt", sep = ";",stringsAsFactors = FALSE)),units="Mb") #its okay to load the whole file & take a subset after power <- read.delim("hh_power.txt", sep = ";",stringsAsFactors = FALSE) #subset data powerss <- power[power$Date=="1/2/2007" | power$Date=="2/2/2007",] #formatting the date-variable d <- paste0(0, substr(powerss$Date,1,1)) m <- paste0(0, substr(powerss$Date,3,3)) y <- substr(powerss$Date,5,8) powerss$Date <- strptime(paste0(d,"/",m,"/",y),"%d/%m/%Y") powerss$Date <- as.Date(powerss$Date,"%Y-%m-%d") #powerss$Time <- strptime(powerss$Time, "%T") powerss$Global_active_power <- as.numeric(powerss$Global_active_power) powerss$Global_reactive_power <- as.numeric(powerss$Global_reactive_power) powerss$Voltage <- as.numeric(powerss$Voltage) powerss$Global_intensity <- as.numeric(powerss$Global_intensity) powerss$Sub_metering_1 <- as.numeric(powerss$Sub_metering_1) powerss$Sub_metering_2 <- as.numeric(powerss$Sub_metering_2) powerss$Sub_metering_3 <- as.numeric(powerss$Sub_metering_3) #Plot 4 png(filename = "plot4.png", width = 480, height = 480, units = "px", pointsize = 12, bg = "white") par(mfrow=c(2,2)) #1 plot(powerss$Global_active_power, type="l", ylab="Global Active Power (kilowatts)", xlab="", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) #2 plot(powerss$Voltage, type="l", ylab="Voltage", xlab="datetime", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) #3 plot(powerss$Sub_metering_1, type="l", ylab="Energy sub metering", xlab="", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) lines(powerss$Sub_metering_2, col="red") lines(powerss$Sub_metering_3, col="blue") legend("topright", legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),cex=0.5, lty=c(1,1,1), col=c("black","red", "blue")) #4 plot(powerss$Global_reactive_power, type="l", ylab="Global_reactive_power", xlab="datetime", xaxt="n") axis(1, at=c(0,middle,right),labels=c("Thu","Fri","Sat"), las=0) par(mfrow=c(1,1)) dev.off()
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/nma.R \name{nameTreatments} \alias{nameTreatments} \title{Match treatment names to ID numbers} \usage{ nameTreatments(results, coding, ...) } \arguments{ \item{results}{A data frame as returned by \code{extractComparison}} \item{coding}{A data frame with two columns 'id' and 'description'. 'id' must be the treatment id numbers corresponding to the way the treatments were coded in the network. 'description' should be the name of the treatment.} } \value{ The same data frame with the treatment names appended } \description{ Match treatment names to ID numbers } \details{ This function matches the coded treatment id numbers in the network to the corresponding human readable names. The mapping from id number to name should be provided as a two column data frame via the \code{coding} argument. This function is intended to work on the data frame generated as the output from \code{extractComparison}. This function will mainly be called via \code{extractMTCResults} and should only be used directly if you understand what you are doing. The general work flow is \code{mtc.run} > \code{calcAllPairs} > \code{extractComparison} > \code{nameTreatments} > \code{makeTab}. \code{extractMTCResults} will handle the last four steps for you. } \seealso{ \code{\link{extractComparison}}, \code{\link{calcAllPairs}}, \code{\link{extractMTCResults}} }
/man/nameTreatments.Rd
no_license
RichardBirnie/mautils
R
false
true
1,444
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/nma.R \name{nameTreatments} \alias{nameTreatments} \title{Match treatment names to ID numbers} \usage{ nameTreatments(results, coding, ...) } \arguments{ \item{results}{A data frame as returned by \code{extractComparison}} \item{coding}{A data frame with two columns 'id' and 'description'. 'id' must be the treatment id numbers corresponding to the way the treatments were coded in the network. 'description' should be the name of the treatment.} } \value{ The same data frame with the treatment names appended } \description{ Match treatment names to ID numbers } \details{ This function matches the coded treatment id numbers in the network to the corresponding human readable names. The mapping from id number to name should be provided as a two column data frame via the \code{coding} argument. This function is intended to work on the data frame generated as the output from \code{extractComparison}. This function will mainly be called via \code{extractMTCResults} and should only be used directly if you understand what you are doing. The general work flow is \code{mtc.run} > \code{calcAllPairs} > \code{extractComparison} > \code{nameTreatments} > \code{makeTab}. \code{extractMTCResults} will handle the last four steps for you. } \seealso{ \code{\link{extractComparison}}, \code{\link{calcAllPairs}}, \code{\link{extractMTCResults}} }
#' @param taxonKey A taxon key from the GBIF backbone. All included and synonym taxa #' are included in the search, so a search for aves with taxononKey=212 #' (i.e. /occurrence/search?taxonKey=212) will match all birds, no matter which #' species. You can pass many keys by passing occ_search in a call to an #' lapply-family function (see last example below). #' @param scientificName A scientific name from the GBIF backbone. All included and synonym #' taxa are included in the search. #' @param datasetKey The occurrence dataset key (a uuid) #' @param catalogNumber An identifier of any form assigned by the source within a #' physical collection or digital dataset for the record which may not unique, #' but should be fairly unique in combination with the institution and collection code. #' @param collectorName The person who recorded the occurrence. #' @param collectionCode An identifier of any form assigned by the source to identify #' the physical collection or digital dataset uniquely within the text of an institution. #' @param institutionCode An identifier of any form assigned by the source to identify #' the institution the record belongs to. Not guaranteed to be que. #' @param country The 2-letter country code (as per ISO-3166-1) of the country in #' which the occurrence was recorded. See here #' \url{http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2} #' @param basisOfRecord Basis of record, as defined in our BasisOfRecord enum here #' \url{http://bit.ly/19kBGhG}. Acceptable values are: #' \itemize{ #' \item FOSSIL_SPECIMEN An occurrence record describing a fossilized specimen. #' \item HUMAN_OBSERVATION An occurrence record describing an observation made by #' one or more people. #' \item LITERATURE An occurrence record based on literature alone. #' \item LIVING_SPECIMEN An occurrence record describing a living specimen, e.g. #' \item MACHINE_OBSERVATION An occurrence record describing an observation made #' by a machine. #' \item OBSERVATION An occurrence record describing an observation. #' \item PRESERVED_SPECIMEN An occurrence record describing a preserved specimen. #' \item UNKNOWN Unknown basis for the record. #' } #' @param eventDate Occurrence date in ISO 8601 format: yyyy, yyyy-MM, yyyy-MM-dd, or #' MM-dd. #' @param year The 4 digit year. A year of 98 will be interpreted as AD 98. #' @param month The month of the year, starting with 1 for January. #' @param search Query terms. The value for this parameter can be a simple word or a phrase. #' @param decimalLatitude Latitude in decimals between -90 and 90 based on WGS 84. #' Supports range queries. #' @param decimalLongitude Longitude in decimals between -180 and 180 based on WGS 84. #' Supports range queries. #' @param publishingCountry The 2-letter country code (as per ISO-3166-1) of the #' country in which the occurrence was recorded. #' @param elevation Elevation in meters above sea level. #' @param depth Depth in meters relative to elevation. For example 10 meters below a #' lake surface with given elevation. #' @param geometry Searches for occurrences inside a polygon described in Well Known #' Text (WKT) format. A WKT shape written as either POINT, LINESTRING, LINEARRING #' or POLYGON. Example of a polygon: ((30.1 10.1, 20, 20 40, 40 40, 30.1 10.1)) #' would be queried as \url{http://bit.ly/HwUSif}. #' @param spatialIssues (logical) Includes/excludes occurrence records which contain spatial #' issues (as determined in our record interpretation), i.e. spatialIssues=TRUE #' returns only those records with spatial issues while spatialIssues=FALSE includes #' only records without spatial issues. The absence of this parameter returns any #' record with or without spatial issues. #' @param issue (character) One of many possible issues with each occurrence record. See #' Details. #' @param hasCoordinate (logical) Return only occurence records with lat/long data (TRUE) or #' all records (FALSE, default). #' @param typeStatus Type status of the specimen. One of many options. See ?typestatus #' @param recordNumber Number recorded by collector of the data, different from GBIF record #' number. See \url{http://rs.tdwg.org/dwc/terms/#recordNumber} for more info #' @param lastInterpreted Date the record was last modified in GBIF, in ISO 8601 format: #' yyyy, yyyy-MM, yyyy-MM-dd, or MM-dd. Supports range queries. #' @param continent Continent. One of africa, antarctica, asia, europe, north_america #' (North America includes the Caribbean and reachies down and includes Panama), oceania, #' or south_america #' @param fields (character) Default ('minimal') will return just taxon name, key, latitude, and #' longitute. 'all' returns all fields. Or specify each field you want returned by name, e.g. #' fields = c('name','latitude','elevation'). #' @param return One of data, hier, meta, or all. If data, a data.frame with the #' data. hier returns the classifications in a list for each record. meta #' returns the metadata for the entire call. all gives all data back in a list. #' @param mediatype Media type. Default is NULL, so no filtering on mediatype. Options: #' NULL, 'MovingImage', 'Sound', and 'StillImage'.`` #' @return A data.frame or list #' @description #' Note that you can pass in a vector to one of taxonkey, datasetKey, and #' catalogNumber parameters in a function call, but not a vector >1 of the three #' parameters at the same time #' #' \bold{Hierarchies:} hierarchies are returned wih each occurrence object. There is no #' option no to return them from the API. However, within the \code{occ_search} #' function you can select whether to return just hierarchies, just data, all of #' data and hiearchies and metadata, or just metadata. If all hierarchies are the #' same we just return one for you. #' #' \bold{Data:} By default only three data fields are returned: name (the species name), #' decimallatitude, and decimallongitude. Set parameter minimal=FALSE if you want more data. #' #' \bold{Nerds:} You can pass parameters not defined in this function into the call to #' the GBIF API to control things about the call itself using the \code{callopts} #' function. See an example below that passes in the \code{verbose} function to #' get details on the http call. #' #' \bold{Scientific names vs. taxon keys:} In the previous GBIF API and the version of rgbif that wrapped #' that API, you could search the equivalent of this function with a species name, which was #' convenient. However, names are messy right. So it sorta makes sense to sort out the species #' key numbers you want exactly, and then get your occurrence data with this function. GBIF has #' added a parameter scientificName to allow searches by scientific names in this function - which #' includes synonym taxa. #' #' \bold{WKT:} Examples of valid WKT objects: #' \itemize{ #' \item 'POLYGON((30.1 10.1, 10 20, 20 60, 60 60, 30.1 10.1))' #' \item 'POINT(30.1 10.1)' #' \item 'LINESTRING(3 4,10 50,20 25)' #' \item 'LINEARRING' ???' - Not sure how to specify this. Anyone? #' } #' #' \bold{Range queries:} A range query is as it sounds - you query on a range of values defined by #' a lower and upper limit. Do a range query by specifying the lower and upper limit in a vector #' like \code{depth='50,100'}. It would be more R like to specify the range in a vector like #' \code{c(50,100)}, but that sort of syntax allows you to do many searches, one for each element in #' the vector - thus range queries have to differ. The following parameters support range queries. #' \itemize{ #' \item decimalLatitude #' \item decimalLongitude #' \item depth #' \item elevation #' \item eventDate #' \item lastInterpreted #' \item month #' \item year #' } #' #' \bold{Issue:} The options for the issue parameter (from #' http://gbif.github.io/gbif-api/apidocs/org/gbif/api/vocabulary/OccurrenceIssue.html): #' \itemize{ #' \item BASIS_OF_RECORD_INVALID The given basis of record is impossible to interpret or seriously #' different from the recommended vocabulary. #' \item CONTINENT_COUNTRY_MISMATCH The interpreted continent and country do not match up. #' \item CONTINENT_DERIVED_FROM_COORDINATES The interpreted continent is based on the coordinates, #' not the verbatim string information. #' \item CONTINENT_INVALID Uninterpretable continent values found. #' \item COORDINATE_INVALID Coordinate value given in some form but GBIF is unable to interpret it. #' \item COORDINATE_OUT_OF_RANGE Coordinate has invalid lat/lon values out of their decimal max #' range. #' \item COORDINATE_REPROJECTED The original coordinate was successfully reprojected from a #' different geodetic datum to WGS84. #' \item COORDINATE_REPROJECTION_FAILED The given decimal latitude and longitude could not be #' reprojected to WGS84 based on the provided datum. #' \item COORDINATE_REPROJECTION_SUSPICIOUS Indicates successful coordinate reprojection according #' to provided datum, but which results in a datum shift larger than 0.1 decimal degrees. #' \item COORDINATE_ROUNDED Original coordinate modified by rounding to 5 decimals. #' \item COUNTRY_COORDINATE_MISMATCH The interpreted occurrence coordinates fall outside of the #' indicated country. #' \item COUNTRY_DERIVED_FROM_COORDINATES The interpreted country is based on the coordinates, not #' the verbatim string information. #' \item COUNTRY_INVALID Uninterpretable country values found. #' \item COUNTRY_MISMATCH Interpreted country for dwc:country and dwc:countryCode contradict each #' other. #' \item DEPTH_MIN_MAX_SWAPPED Set if supplied min>max #' \item DEPTH_NON_NUMERIC Set if depth is a non numeric value #' \item DEPTH_NOT_METRIC Set if supplied depth is not given in the metric system, for example #' using feet instead of meters #' \item DEPTH_UNLIKELY Set if depth is larger than 11.000m or negative. #' \item ELEVATION_MIN_MAX_SWAPPED Set if supplied min > max elevation #' \item ELEVATION_NON_NUMERIC Set if elevation is a non numeric value #' \item ELEVATION_NOT_METRIC Set if supplied elevation is not given in the metric system, for #' example using feet instead of meters #' \item ELEVATION_UNLIKELY Set if elevation is above the troposphere (17km) or below 11km #' (Mariana Trench). #' \item GEODETIC_DATUM_ASSUMED_WGS84 Indicating that the interpreted coordinates assume they are #' based on WGS84 datum as the datum was either not indicated or interpretable. #' \item GEODETIC_DATUM_INVALID The geodetic datum given could not be interpreted. #' \item IDENTIFIED_DATE_INVALID The date given for dwc:dateIdentified is invalid and cant be #' interpreted at all. #' \item IDENTIFIED_DATE_UNLIKELY The date given for dwc:dateIdentified is in the future or before #' Linnean times (1700). #' \item MODIFIED_DATE_INVALID A (partial) invalid date is given for dc:modified, such as a non #' existing date, invalid zero month, etc. #' \item MODIFIED_DATE_UNLIKELY The date given for dc:modified is in the future or predates unix #' time (1970). #' \item MULTIMEDIA_DATE_INVALID An invalid date is given for dc:created of a multimedia object. #' \item MULTIMEDIA_URI_INVALID An invalid uri is given for a multimedia object. #' \item PRESUMED_NEGATED_LATITUDE Latitude appears to be negated, e.g. #' \item PRESUMED_NEGATED_LONGITUDE Longitude appears to be negated, e.g. #' \item PRESUMED_SWAPPED_COORDINATE Latitude and longitude appear to be swapped. #' \item RECORDED_DATE_INVALID A (partial) invalid date is given, such as a non existing date, #' invalid zero month, etc. #' \item RECORDED_DATE_MISMATCH The recording date specified as the eventDate string and the #' individual year, month, day are contradicting. #' \item RECORDED_DATE_UNLIKELY The recording date is highly unlikely, falling either into the #' future or represents a very old date before 1600 that predates modern taxonomy. #' \item REFERENCES_URI_INVALID An invalid uri is given for dc:references. #' \item TAXON_MATCH_FUZZY Matching to the taxonomic backbone can only be done using a fuzzy, non #' exact match. #' \item TAXON_MATCH_HIGHERRANK Matching to the taxonomic backbone can only be done on a higher #' rank and not the scientific name. #' \item TAXON_MATCH_NONE Matching to the taxonomic backbone cannot be done cause there was no #' match at all or several matches with too little information to keep them apart (homonyms). #' \item TYPE_STATUS_INVALID The given type status is impossible to interpret or seriously #' different from the recommended vocabulary. #' \item ZERO_COORDINATE Coordinate is the exact 0/0 coordinate, often indicating a bad null #' coordinate. #' }
/man-roxygen/occsearch.r
permissive
jarioksa/rgbif
R
false
false
12,780
r
#' @param taxonKey A taxon key from the GBIF backbone. All included and synonym taxa #' are included in the search, so a search for aves with taxononKey=212 #' (i.e. /occurrence/search?taxonKey=212) will match all birds, no matter which #' species. You can pass many keys by passing occ_search in a call to an #' lapply-family function (see last example below). #' @param scientificName A scientific name from the GBIF backbone. All included and synonym #' taxa are included in the search. #' @param datasetKey The occurrence dataset key (a uuid) #' @param catalogNumber An identifier of any form assigned by the source within a #' physical collection or digital dataset for the record which may not unique, #' but should be fairly unique in combination with the institution and collection code. #' @param collectorName The person who recorded the occurrence. #' @param collectionCode An identifier of any form assigned by the source to identify #' the physical collection or digital dataset uniquely within the text of an institution. #' @param institutionCode An identifier of any form assigned by the source to identify #' the institution the record belongs to. Not guaranteed to be que. #' @param country The 2-letter country code (as per ISO-3166-1) of the country in #' which the occurrence was recorded. See here #' \url{http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2} #' @param basisOfRecord Basis of record, as defined in our BasisOfRecord enum here #' \url{http://bit.ly/19kBGhG}. Acceptable values are: #' \itemize{ #' \item FOSSIL_SPECIMEN An occurrence record describing a fossilized specimen. #' \item HUMAN_OBSERVATION An occurrence record describing an observation made by #' one or more people. #' \item LITERATURE An occurrence record based on literature alone. #' \item LIVING_SPECIMEN An occurrence record describing a living specimen, e.g. #' \item MACHINE_OBSERVATION An occurrence record describing an observation made #' by a machine. #' \item OBSERVATION An occurrence record describing an observation. #' \item PRESERVED_SPECIMEN An occurrence record describing a preserved specimen. #' \item UNKNOWN Unknown basis for the record. #' } #' @param eventDate Occurrence date in ISO 8601 format: yyyy, yyyy-MM, yyyy-MM-dd, or #' MM-dd. #' @param year The 4 digit year. A year of 98 will be interpreted as AD 98. #' @param month The month of the year, starting with 1 for January. #' @param search Query terms. The value for this parameter can be a simple word or a phrase. #' @param decimalLatitude Latitude in decimals between -90 and 90 based on WGS 84. #' Supports range queries. #' @param decimalLongitude Longitude in decimals between -180 and 180 based on WGS 84. #' Supports range queries. #' @param publishingCountry The 2-letter country code (as per ISO-3166-1) of the #' country in which the occurrence was recorded. #' @param elevation Elevation in meters above sea level. #' @param depth Depth in meters relative to elevation. For example 10 meters below a #' lake surface with given elevation. #' @param geometry Searches for occurrences inside a polygon described in Well Known #' Text (WKT) format. A WKT shape written as either POINT, LINESTRING, LINEARRING #' or POLYGON. Example of a polygon: ((30.1 10.1, 20, 20 40, 40 40, 30.1 10.1)) #' would be queried as \url{http://bit.ly/HwUSif}. #' @param spatialIssues (logical) Includes/excludes occurrence records which contain spatial #' issues (as determined in our record interpretation), i.e. spatialIssues=TRUE #' returns only those records with spatial issues while spatialIssues=FALSE includes #' only records without spatial issues. The absence of this parameter returns any #' record with or without spatial issues. #' @param issue (character) One of many possible issues with each occurrence record. See #' Details. #' @param hasCoordinate (logical) Return only occurence records with lat/long data (TRUE) or #' all records (FALSE, default). #' @param typeStatus Type status of the specimen. One of many options. See ?typestatus #' @param recordNumber Number recorded by collector of the data, different from GBIF record #' number. See \url{http://rs.tdwg.org/dwc/terms/#recordNumber} for more info #' @param lastInterpreted Date the record was last modified in GBIF, in ISO 8601 format: #' yyyy, yyyy-MM, yyyy-MM-dd, or MM-dd. Supports range queries. #' @param continent Continent. One of africa, antarctica, asia, europe, north_america #' (North America includes the Caribbean and reachies down and includes Panama), oceania, #' or south_america #' @param fields (character) Default ('minimal') will return just taxon name, key, latitude, and #' longitute. 'all' returns all fields. Or specify each field you want returned by name, e.g. #' fields = c('name','latitude','elevation'). #' @param return One of data, hier, meta, or all. If data, a data.frame with the #' data. hier returns the classifications in a list for each record. meta #' returns the metadata for the entire call. all gives all data back in a list. #' @param mediatype Media type. Default is NULL, so no filtering on mediatype. Options: #' NULL, 'MovingImage', 'Sound', and 'StillImage'.`` #' @return A data.frame or list #' @description #' Note that you can pass in a vector to one of taxonkey, datasetKey, and #' catalogNumber parameters in a function call, but not a vector >1 of the three #' parameters at the same time #' #' \bold{Hierarchies:} hierarchies are returned wih each occurrence object. There is no #' option no to return them from the API. However, within the \code{occ_search} #' function you can select whether to return just hierarchies, just data, all of #' data and hiearchies and metadata, or just metadata. If all hierarchies are the #' same we just return one for you. #' #' \bold{Data:} By default only three data fields are returned: name (the species name), #' decimallatitude, and decimallongitude. Set parameter minimal=FALSE if you want more data. #' #' \bold{Nerds:} You can pass parameters not defined in this function into the call to #' the GBIF API to control things about the call itself using the \code{callopts} #' function. See an example below that passes in the \code{verbose} function to #' get details on the http call. #' #' \bold{Scientific names vs. taxon keys:} In the previous GBIF API and the version of rgbif that wrapped #' that API, you could search the equivalent of this function with a species name, which was #' convenient. However, names are messy right. So it sorta makes sense to sort out the species #' key numbers you want exactly, and then get your occurrence data with this function. GBIF has #' added a parameter scientificName to allow searches by scientific names in this function - which #' includes synonym taxa. #' #' \bold{WKT:} Examples of valid WKT objects: #' \itemize{ #' \item 'POLYGON((30.1 10.1, 10 20, 20 60, 60 60, 30.1 10.1))' #' \item 'POINT(30.1 10.1)' #' \item 'LINESTRING(3 4,10 50,20 25)' #' \item 'LINEARRING' ???' - Not sure how to specify this. Anyone? #' } #' #' \bold{Range queries:} A range query is as it sounds - you query on a range of values defined by #' a lower and upper limit. Do a range query by specifying the lower and upper limit in a vector #' like \code{depth='50,100'}. It would be more R like to specify the range in a vector like #' \code{c(50,100)}, but that sort of syntax allows you to do many searches, one for each element in #' the vector - thus range queries have to differ. The following parameters support range queries. #' \itemize{ #' \item decimalLatitude #' \item decimalLongitude #' \item depth #' \item elevation #' \item eventDate #' \item lastInterpreted #' \item month #' \item year #' } #' #' \bold{Issue:} The options for the issue parameter (from #' http://gbif.github.io/gbif-api/apidocs/org/gbif/api/vocabulary/OccurrenceIssue.html): #' \itemize{ #' \item BASIS_OF_RECORD_INVALID The given basis of record is impossible to interpret or seriously #' different from the recommended vocabulary. #' \item CONTINENT_COUNTRY_MISMATCH The interpreted continent and country do not match up. #' \item CONTINENT_DERIVED_FROM_COORDINATES The interpreted continent is based on the coordinates, #' not the verbatim string information. #' \item CONTINENT_INVALID Uninterpretable continent values found. #' \item COORDINATE_INVALID Coordinate value given in some form but GBIF is unable to interpret it. #' \item COORDINATE_OUT_OF_RANGE Coordinate has invalid lat/lon values out of their decimal max #' range. #' \item COORDINATE_REPROJECTED The original coordinate was successfully reprojected from a #' different geodetic datum to WGS84. #' \item COORDINATE_REPROJECTION_FAILED The given decimal latitude and longitude could not be #' reprojected to WGS84 based on the provided datum. #' \item COORDINATE_REPROJECTION_SUSPICIOUS Indicates successful coordinate reprojection according #' to provided datum, but which results in a datum shift larger than 0.1 decimal degrees. #' \item COORDINATE_ROUNDED Original coordinate modified by rounding to 5 decimals. #' \item COUNTRY_COORDINATE_MISMATCH The interpreted occurrence coordinates fall outside of the #' indicated country. #' \item COUNTRY_DERIVED_FROM_COORDINATES The interpreted country is based on the coordinates, not #' the verbatim string information. #' \item COUNTRY_INVALID Uninterpretable country values found. #' \item COUNTRY_MISMATCH Interpreted country for dwc:country and dwc:countryCode contradict each #' other. #' \item DEPTH_MIN_MAX_SWAPPED Set if supplied min>max #' \item DEPTH_NON_NUMERIC Set if depth is a non numeric value #' \item DEPTH_NOT_METRIC Set if supplied depth is not given in the metric system, for example #' using feet instead of meters #' \item DEPTH_UNLIKELY Set if depth is larger than 11.000m or negative. #' \item ELEVATION_MIN_MAX_SWAPPED Set if supplied min > max elevation #' \item ELEVATION_NON_NUMERIC Set if elevation is a non numeric value #' \item ELEVATION_NOT_METRIC Set if supplied elevation is not given in the metric system, for #' example using feet instead of meters #' \item ELEVATION_UNLIKELY Set if elevation is above the troposphere (17km) or below 11km #' (Mariana Trench). #' \item GEODETIC_DATUM_ASSUMED_WGS84 Indicating that the interpreted coordinates assume they are #' based on WGS84 datum as the datum was either not indicated or interpretable. #' \item GEODETIC_DATUM_INVALID The geodetic datum given could not be interpreted. #' \item IDENTIFIED_DATE_INVALID The date given for dwc:dateIdentified is invalid and cant be #' interpreted at all. #' \item IDENTIFIED_DATE_UNLIKELY The date given for dwc:dateIdentified is in the future or before #' Linnean times (1700). #' \item MODIFIED_DATE_INVALID A (partial) invalid date is given for dc:modified, such as a non #' existing date, invalid zero month, etc. #' \item MODIFIED_DATE_UNLIKELY The date given for dc:modified is in the future or predates unix #' time (1970). #' \item MULTIMEDIA_DATE_INVALID An invalid date is given for dc:created of a multimedia object. #' \item MULTIMEDIA_URI_INVALID An invalid uri is given for a multimedia object. #' \item PRESUMED_NEGATED_LATITUDE Latitude appears to be negated, e.g. #' \item PRESUMED_NEGATED_LONGITUDE Longitude appears to be negated, e.g. #' \item PRESUMED_SWAPPED_COORDINATE Latitude and longitude appear to be swapped. #' \item RECORDED_DATE_INVALID A (partial) invalid date is given, such as a non existing date, #' invalid zero month, etc. #' \item RECORDED_DATE_MISMATCH The recording date specified as the eventDate string and the #' individual year, month, day are contradicting. #' \item RECORDED_DATE_UNLIKELY The recording date is highly unlikely, falling either into the #' future or represents a very old date before 1600 that predates modern taxonomy. #' \item REFERENCES_URI_INVALID An invalid uri is given for dc:references. #' \item TAXON_MATCH_FUZZY Matching to the taxonomic backbone can only be done using a fuzzy, non #' exact match. #' \item TAXON_MATCH_HIGHERRANK Matching to the taxonomic backbone can only be done on a higher #' rank and not the scientific name. #' \item TAXON_MATCH_NONE Matching to the taxonomic backbone cannot be done cause there was no #' match at all or several matches with too little information to keep them apart (homonyms). #' \item TYPE_STATUS_INVALID The given type status is impossible to interpret or seriously #' different from the recommended vocabulary. #' \item ZERO_COORDINATE Coordinate is the exact 0/0 coordinate, often indicating a bad null #' coordinate. #' }
#' Analyse SAR TL measurements #' #' The function performs a SAR TL analysis on a #' \code{\linkS4class{RLum.Analysis}} object including growth curve fitting. #' #' This function performs a SAR TL analysis on a set of curves. The SAR #' procedure in general is given by Murray and Wintle (2000). For the #' calculation of the Lx/Tx value the function \link{calc_TLLxTxRatio} is #' used.\cr\cr \bold{Provided rejection criteria}\cr\cr #' \sQuote{recyling.ratio}: calculated for every repeated regeneration dose #' point.\cr \sQuote{recuperation.rate}: recuperation rate calculated by #' comparing the Lx/Tx values of the zero regeneration point with the Ln/Tn #' value (the Lx/Tx ratio of the natural signal). For methodological #' background see Aitken and Smith (1988)\cr #' #' @param object \code{\linkS4class{RLum.Analysis}}(\bold{required}): input #' object containing data for analysis #' #' @param object.background currently not used #' #' @param signal.integral.min \link{integer} (\bold{required}): requires the #' channel number for the lower signal integral bound (e.g. #' \code{signal.integral.min = 100}) #' #' @param signal.integral.max \link{integer} (\bold{required}): requires the #' channel number for the upper signal integral bound (e.g. #' \code{signal.integral.max = 200}) #' #' @param sequence.structure \link{vector} \link{character} (with default): #' specifies the general sequence structure. Three steps are allowed ( #' \code{"PREHEAT"}, \code{"SIGNAL"}, \code{"BACKGROUND"}), in addition a #' parameter \code{"EXCLUDE"}. This allows excluding TL curves which are not #' relevant for the protocol analysis. (Note: None TL are removed by default) #' #' @param rejection.criteria \link{list} (with default): list containing #' rejection criteria in percentage for the calculation. #' #' @param dose.points \code{\link{numeric}} (optional): option set dose points manually #' #' @param log \link{character} (with default): a character string which #' contains "x" if the x axis is to be logarithmic, "y" if the y axis is to be #' logarithmic and "xy" or "yx" if both axes are to be logarithmic. See #' \link{plot.default}). #' #' @param \dots further arguments that will be passed to the function #' \code{\link{plot_GrowthCurve}} #' #' @return A plot (optional) and an \code{\linkS4class{RLum.Results}} object is #' returned containing the following elements: #' \item{De.values}{\link{data.frame} containing De-values and further #' parameters} \item{LnLxTnTx.values}{\link{data.frame} of all calculated Lx/Tx #' values including signal, background counts and the dose points.} #' \item{rejection.criteria}{\link{data.frame} with values that might by used #' as rejection criteria. NA is produced if no R0 dose point exists.}\cr\cr #' \bold{note:} the output should be accessed using the function #' \code{\link{get_RLum}} #' @note \bold{THIS IS A BETA VERSION}\cr\cr None TL curves will be removed #' from the input object without further warning. #' @section Function version: 0.1.4 #' #' @author Sebastian Kreutzer, IRAMAT-CRP2A, Universite Bordeaux Montaigne (France) #' #' @seealso \code{\link{calc_TLLxTxRatio}}, \code{\link{plot_GrowthCurve}}, #' \code{\linkS4class{RLum.Analysis}}, \code{\linkS4class{RLum.Results}} #' \code{\link{get_RLum}} #' #' @references Aitken, M.J. and Smith, B.W., 1988. Optical dating: recuperation #' after bleaching. Quaternary Science Reviews 7, 387-393. #' #' Murray, A.S. and Wintle, A.G., 2000. Luminescence dating of quartz using an #' improved single-aliquot regenerative-dose protocol. Radiation Measurements #' 32, 57-73. #' @keywords datagen plot #' @examples #' #' #' ##load data #' data(ExampleData.BINfileData, envir = environment()) #' #' ##transform the values from the first position in a RLum.Analysis object #' object <- Risoe.BINfileData2RLum.Analysis(TL.SAR.Data, pos=3) #' #' ##perform analysis #' analyse_SAR.TL(object, #' signal.integral.min = 210, #' signal.integral.max = 220, #' log = "y", #' fit.method = "EXP OR LIN", #' sequence.structure = c("SIGNAL", "BACKGROUND")) #' #' @export analyse_SAR.TL <- function( object, object.background, signal.integral.min, signal.integral.max, sequence.structure = c("PREHEAT", "SIGNAL", "BACKGROUND"), rejection.criteria = list(recycling.ratio = 10, recuperation.rate = 10), dose.points, log = "", ... ){ # CONFIG ----------------------------------------------------------------- ##set allowed curve types type.curves <- c("TL") ##=============================================================================# # General Integrity Checks --------------------------------------------------- ##GENERAL ##MISSING INPUT if(missing("object")==TRUE){ stop("[analyse_SAR.TL] No value set for 'object'!") } if(missing("signal.integral.min") == TRUE){ stop("[analyse_SAR.TL] No value set for 'signal.integral.min'!") } if(missing("signal.integral.max") == TRUE){ stop("[analyse_SAR.TL] No value set for 'signal.integral.max'!") } ##INPUT OBJECTS if(is(object, "RLum.Analysis") == FALSE){ stop("[analyse_SAR.TL] Input object is not of type 'RLum.Analyis'!") } # Protocol Integrity Checks -------------------------------------------------- ##Remove non TL-curves from object by selecting TL curves object@records <- get_RLum(object, recordType = type.curves) ##ANALYSE SEQUENCE OBJECT STRUCTURE ##set vector for sequence structure temp.protocol.step <- rep(sequence.structure,length(object@records))[1:length(object@records)] ##grep object strucute temp.sequence.structure <- structure_RLum(object) ##set values for step temp.sequence.structure[,"protocol.step"] <- temp.protocol.step ##remove TL curves which are excluded temp.sequence.structure <- temp.sequence.structure[which( temp.sequence.structure[,"protocol.step"]!="EXCLUDE"),] ##check integrity; signal and bg range should be equal if(length( unique( temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","x.max"]))>1){ stop(paste( "[analyse_SAR.TL()] Signal range differs. Check sequence structure.\n", temp.sequence.structure )) } ##check if the wanted curves are a multiple of the structure if(length(temp.sequence.structure[,"id"])%%length(sequence.structure)!=0){ stop("[analyse_SAR.TL()] Input TL curves are not a multiple of the sequence structure.") } # # Calculate LnLxTnTx values -------------------------------------------------- ##grep IDs for signal and background curves TL.preheat.ID <- temp.sequence.structure[ temp.sequence.structure[,"protocol.step"] == "PREHEAT","id"] TL.signal.ID <- temp.sequence.structure[ temp.sequence.structure[,"protocol.step"] == "SIGNAL","id"] TL.background.ID <- temp.sequence.structure[ temp.sequence.structure[,"protocol.step"] == "BACKGROUND","id"] ##calculate LxTx values using external function for(i in seq(1,length(TL.signal.ID),by=2)){ temp.LnLxTnTx <- get_RLum( calc_TLLxTxRatio( Lx.data.signal = get_RLum(object, record.id=TL.signal.ID[i]), Lx.data.background = get_RLum(object, record.id=TL.background.ID[i]), Tx.data.signal = get_RLum(object, record.id=TL.signal.ID[i+1]), Tx.data.background = get_RLum(object, record.id = TL.background.ID[i+1]), signal.integral.min, signal.integral.max)) ##grep dose temp.Dose <- object@records[[TL.signal.ID[i]]]@info$IRR_TIME temp.LnLxTnTx <- cbind(Dose=temp.Dose, temp.LnLxTnTx) if(exists("LnLxTnTx")==FALSE){ LnLxTnTx <- data.frame(temp.LnLxTnTx) }else{ LnLxTnTx <- rbind(LnLxTnTx,temp.LnLxTnTx) } } ##set dose.points manual if argument was set if(!missing(dose.points)){ temp.Dose <- dose.points LnLxTnTx$Dose <- dose.points } # Set regeneration points ------------------------------------------------- #generate unique dose id - this are also the # for the generated points temp.DoseID <- c(0:(length(temp.Dose)-1)) temp.DoseName <- paste("R",temp.DoseID,sep="") temp.DoseName <- cbind(Name=temp.DoseName,Dose=temp.Dose) ##set natural temp.DoseName[temp.DoseName[,"Name"]=="R0","Name"]<-"Natural" ##set R0 temp.DoseName[temp.DoseName[,"Name"]!="Natural" & temp.DoseName[,"Dose"]==0,"Name"]<-"R0" ##find duplicated doses (including 0 dose - which means the Natural) temp.DoseDuplicated<-duplicated(temp.DoseName[,"Dose"]) ##combine temp.DoseName temp.DoseName<-cbind(temp.DoseName,Repeated=temp.DoseDuplicated) ##correct value for R0 (it is not really repeated) temp.DoseName[temp.DoseName[,"Dose"]==0,"Repeated"]<-FALSE ##combine in the data frame temp.LnLxTnTx<-data.frame(Name=temp.DoseName[,"Name"], Repeated=as.logical(temp.DoseName[,"Repeated"])) LnLxTnTx<-cbind(temp.LnLxTnTx,LnLxTnTx) LnLxTnTx[,"Name"]<-as.character(LnLxTnTx[,"Name"]) # Calculate Recycling Ratio ----------------------------------------------- ##Calculate Recycling Ratio if(length(LnLxTnTx[LnLxTnTx[,"Repeated"]==TRUE,"Repeated"])>0){ ##identify repeated doses temp.Repeated<-LnLxTnTx[LnLxTnTx[,"Repeated"]==TRUE,c("Name","Dose","LxTx")] ##find concering previous dose for the repeated dose temp.Previous<-t(sapply(1:length(temp.Repeated[,1]),function(x){ LnLxTnTx[LnLxTnTx[,"Dose"]==temp.Repeated[x,"Dose"] & LnLxTnTx[,"Repeated"]==FALSE,c("Name","Dose","LxTx")] })) ##convert to data.frame temp.Previous<-as.data.frame(temp.Previous) ##set column names temp.ColNames<-sapply(1:length(temp.Repeated[,1]),function(x){ paste(temp.Repeated[x,"Name"],"/", temp.Previous[temp.Previous[,"Dose"]==temp.Repeated[x,"Dose"],"Name"], sep="") }) ##Calculate Recycling Ratio RecyclingRatio<-as.numeric(temp.Repeated[,"LxTx"])/as.numeric(temp.Previous[,"LxTx"]) ##Just transform the matrix and add column names RecyclingRatio<-t(RecyclingRatio) colnames(RecyclingRatio)<-temp.ColNames }else{RecyclingRatio<-NA} # Calculate Recuperation Rate --------------------------------------------- ##Recuperation Rate if("R0" %in% LnLxTnTx[,"Name"]==TRUE){ Recuperation<-round(LnLxTnTx[LnLxTnTx[,"Name"]=="R0","LxTx"]/ LnLxTnTx[LnLxTnTx[,"Name"]=="Natural","LxTx"],digits=4) }else{Recuperation<-NA} # Combine and Evaluate Rejection Criteria --------------------------------- RejectionCriteria <- data.frame( citeria = c(colnames(RecyclingRatio), "recuperation rate"), value = c(RecyclingRatio,Recuperation), threshold = c( rep(paste("+/-", rejection.criteria$recycling.ratio/100) ,length(RecyclingRatio)), paste("", rejection.criteria$recuperation.rate/100) ), status = c( if(is.na(RecyclingRatio)==FALSE){ sapply(1:length(RecyclingRatio), function(x){ if(abs(1-RecyclingRatio[x])>(rejection.criteria$recycling.ratio/100)){ "FAILED" }else{"OK"}})}else{NA}, if(is.na(Recuperation)==FALSE & Recuperation>rejection.criteria$recuperation.rate){"FAILED"}else{"OK"} )) ##============================================================================## ##PLOTTING ##============================================================================## # Plotting - Config ------------------------------------------------------- ##grep plot parameter par.default <- par(no.readonly = TRUE) ##colours and double for plotting col <- get("col", pos = .LuminescenceEnv) col.doubled <- rep(col, each=2) layout(matrix(c(1,1,2,2, 1,1,2,2, 3,3,4,4, 3,3,4,4, 5,5,5,5),5,4,byrow=TRUE)) par(oma=c(0,0,0,0), mar=c(4,4,3,3)) ## 1 -> TL Lx ## 2 -> TL Tx ## 3 -> TL Lx Plateau ## 4 -> TL Tx Plateau ## 5 -> Legend ##recalculate signal.integral from channels to temperature signal.integral.temperature <- c(object@records[[TL.signal.ID[1]]]@data[signal.integral.min,1] : object@records[[TL.signal.ID[1]]]@data[signal.integral.max,1]) ##warning if number of curves exceed colour values if(length(col)<length(TL.signal.ID/2)){ cat("\n[analyse_SAR.TL.R] Warning: To many curves! Only the first", length(col),"curves are plotted!") } # # Plotting TL Lx Curves ---------------------------------------------------- #open plot area LnLx plot(NA,NA, xlab="Temp. [\u00B0C]", ylab=paste("TL [a.u.]",sep=""), xlim=c(0.1, max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","x.max"])), ylim=c( min(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.min"]), max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.max"])), main=expression(paste(L[n],",",L[x]," curves",sep="")), log=log) ##plot curves sapply(seq(1,length(TL.signal.ID),by=2), function(x){ lines(object@records[[TL.signal.ID[x]]]@data,col=col.doubled[x]) }) ##mark integration limits abline(v=min(signal.integral.temperature), lty=2, col="gray") abline(v=max(signal.integral.temperature), lty=2, col="gray") # Plotting TnTx Curves ---------------------------------------------------- #open plot area TnTx plot(NA,NA, xlab="Temp. [\u00B0C]", ylab=paste("TL [a.u.]",sep=""), xlim=c(0.1, max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","x.max"])), ylim=c( min(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.min"]), max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.max"])), main=expression(paste(T[n],",",T[x]," curves",sep="")), log=log) ##plot curves sapply(seq(2,length(TL.signal.ID),by=2), function(x){ lines(object@records[[TL.signal.ID[x]]]@data,col=col.doubled[x]) }) ##mark integration limits abline(v=min(signal.integral.temperature), lty=2, col="gray") abline(v=max(signal.integral.temperature), lty=2, col="gray") # Plotting Plateau Test LnLx ------------------------------------------------- NTL.net.LnLx <- data.frame(object@records[[TL.signal.ID[1]]]@data[,1], object@records[[TL.signal.ID[1]]]@data[,2]- object@records[[TL.background.ID[1]]]@data[,2]) Reg1.net.LnLx <- data.frame(object@records[[TL.signal.ID[3]]]@data[,1], object@records[[TL.signal.ID[3]]]@data[,2]- object@records[[TL.background.ID[3]]]@data[,2]) TL.Plateau.LnLx <- data.frame(NTL.net.LnLx[,1], Reg1.net.LnLx[,2]/NTL.net.LnLx[,2]) ##Plot Plateau Test plot(NA, NA, xlab = "Temp. [\u00B0C]", ylab = "TL [a.u.]", xlim = c(min(signal.integral.temperature)*0.9, max(signal.integral.temperature)*1.1), ylim = c(0, max(NTL.net.LnLx[,2])), main = expression(paste("Plateau test ",L[n],",",L[x]," curves",sep="")) ) ##plot single curves lines(NTL.net.LnLx, col=col[1]) lines(Reg1.net.LnLx, col=col[2]) ##plot par(new=TRUE) plot(TL.Plateau.LnLx, axes=FALSE, xlab="", ylab="", ylim=c(0, quantile(TL.Plateau.LnLx[c(signal.integral.min:signal.integral.max),2], probs = c(0.90), na.rm = TRUE)+3), col="darkgreen") axis(4) # Plotting Plateau Test TnTx ------------------------------------------------- ##get NTL signal NTL.net.TnTx <- data.frame(object@records[[TL.signal.ID[2]]]@data[,1], object@records[[TL.signal.ID[2]]]@data[,2]- object@records[[TL.background.ID[2]]]@data[,2]) ##get signal from the first regeneration point Reg1.net.TnTx <- data.frame(object@records[[TL.signal.ID[4]]]@data[,1], object@records[[TL.signal.ID[4]]]@data[,2]- object@records[[TL.background.ID[4]]]@data[,2]) ##combine values TL.Plateau.TnTx <- data.frame(NTL.net.TnTx[,1], Reg1.net.TnTx[,2]/NTL.net.TnTx[,2]) ##Plot Plateau Test plot(NA, NA, xlab = "Temp. [\u00B0C]", ylab = "TL [a.u.]", xlim = c(min(signal.integral.temperature)*0.9, max(signal.integral.temperature)*1.1), ylim = c(0, max(NTL.net.TnTx[,2])), main = expression(paste("plateau Test ",T[n],",",T[x]," curves",sep="")) ) ##plot single curves lines(NTL.net.TnTx, col=col[1]) lines(Reg1.net.TnTx, col=col[2]) ##plot par(new=TRUE) plot(TL.Plateau.TnTx, axes=FALSE, xlab="", ylab="", ylim=c(0, quantile(TL.Plateau.TnTx[c(signal.integral.min:signal.integral.max),2], probs = c(0.90), na.rm = TRUE)+3), col="darkgreen") axis(4) # Plotting Legend ---------------------------------------- plot(c(1:(length(TL.signal.ID)/2)), rep(8,length(TL.signal.ID)/2), type = "p", axes=FALSE, xlab="", ylab="", pch=15, col=col[1:length(TL.signal.ID)], cex=2, ylim=c(0,10) ) ##add text text(c(1:(length(TL.signal.ID)/2)), rep(4,length(TL.signal.ID)/2), paste(LnLxTnTx$Name,"\n(",LnLxTnTx$Dose,")", sep="") ) ##add line abline(h=10,lwd=0.5) ##set failed text and mark De as failed if(length(grep("FAILED",RejectionCriteria$status))>0){ mtext("[FAILED]", col="red") } ##reset par par(par.default) rm(par.default) # Plotting GC ---------------------------------------- temp.sample <- data.frame(Dose=LnLxTnTx$Dose, LxTx=LnLxTnTx$LxTx, LxTx.Error=LnLxTnTx$LxTx*0.1, TnTx=LnLxTnTx$TnTx ) temp.GC <- get_RLum(plot_GrowthCurve(temp.sample, ...))[,c("De","De.Error")] ##add recjection status if(length(grep("FAILED",RejectionCriteria$status))>0){ temp.GC <- data.frame(temp.GC, RC.Status="FAILED") }else{ temp.GC <- data.frame(temp.GC, RC.Status="OK") } # Return Values ----------------------------------------------------------- newRLumResults.analyse_SAR.TL <- set_RLum( class = "RLum.Results", data = list( De.values = temp.GC, LnLxTnTx.table = LnLxTnTx, rejection.criteria = RejectionCriteria)) return(newRLumResults.analyse_SAR.TL) }
/Luminescence/R/analyse_SAR.TL.R
no_license
ingted/R-Examples
R
false
false
18,691
r
#' Analyse SAR TL measurements #' #' The function performs a SAR TL analysis on a #' \code{\linkS4class{RLum.Analysis}} object including growth curve fitting. #' #' This function performs a SAR TL analysis on a set of curves. The SAR #' procedure in general is given by Murray and Wintle (2000). For the #' calculation of the Lx/Tx value the function \link{calc_TLLxTxRatio} is #' used.\cr\cr \bold{Provided rejection criteria}\cr\cr #' \sQuote{recyling.ratio}: calculated for every repeated regeneration dose #' point.\cr \sQuote{recuperation.rate}: recuperation rate calculated by #' comparing the Lx/Tx values of the zero regeneration point with the Ln/Tn #' value (the Lx/Tx ratio of the natural signal). For methodological #' background see Aitken and Smith (1988)\cr #' #' @param object \code{\linkS4class{RLum.Analysis}}(\bold{required}): input #' object containing data for analysis #' #' @param object.background currently not used #' #' @param signal.integral.min \link{integer} (\bold{required}): requires the #' channel number for the lower signal integral bound (e.g. #' \code{signal.integral.min = 100}) #' #' @param signal.integral.max \link{integer} (\bold{required}): requires the #' channel number for the upper signal integral bound (e.g. #' \code{signal.integral.max = 200}) #' #' @param sequence.structure \link{vector} \link{character} (with default): #' specifies the general sequence structure. Three steps are allowed ( #' \code{"PREHEAT"}, \code{"SIGNAL"}, \code{"BACKGROUND"}), in addition a #' parameter \code{"EXCLUDE"}. This allows excluding TL curves which are not #' relevant for the protocol analysis. (Note: None TL are removed by default) #' #' @param rejection.criteria \link{list} (with default): list containing #' rejection criteria in percentage for the calculation. #' #' @param dose.points \code{\link{numeric}} (optional): option set dose points manually #' #' @param log \link{character} (with default): a character string which #' contains "x" if the x axis is to be logarithmic, "y" if the y axis is to be #' logarithmic and "xy" or "yx" if both axes are to be logarithmic. See #' \link{plot.default}). #' #' @param \dots further arguments that will be passed to the function #' \code{\link{plot_GrowthCurve}} #' #' @return A plot (optional) and an \code{\linkS4class{RLum.Results}} object is #' returned containing the following elements: #' \item{De.values}{\link{data.frame} containing De-values and further #' parameters} \item{LnLxTnTx.values}{\link{data.frame} of all calculated Lx/Tx #' values including signal, background counts and the dose points.} #' \item{rejection.criteria}{\link{data.frame} with values that might by used #' as rejection criteria. NA is produced if no R0 dose point exists.}\cr\cr #' \bold{note:} the output should be accessed using the function #' \code{\link{get_RLum}} #' @note \bold{THIS IS A BETA VERSION}\cr\cr None TL curves will be removed #' from the input object without further warning. #' @section Function version: 0.1.4 #' #' @author Sebastian Kreutzer, IRAMAT-CRP2A, Universite Bordeaux Montaigne (France) #' #' @seealso \code{\link{calc_TLLxTxRatio}}, \code{\link{plot_GrowthCurve}}, #' \code{\linkS4class{RLum.Analysis}}, \code{\linkS4class{RLum.Results}} #' \code{\link{get_RLum}} #' #' @references Aitken, M.J. and Smith, B.W., 1988. Optical dating: recuperation #' after bleaching. Quaternary Science Reviews 7, 387-393. #' #' Murray, A.S. and Wintle, A.G., 2000. Luminescence dating of quartz using an #' improved single-aliquot regenerative-dose protocol. Radiation Measurements #' 32, 57-73. #' @keywords datagen plot #' @examples #' #' #' ##load data #' data(ExampleData.BINfileData, envir = environment()) #' #' ##transform the values from the first position in a RLum.Analysis object #' object <- Risoe.BINfileData2RLum.Analysis(TL.SAR.Data, pos=3) #' #' ##perform analysis #' analyse_SAR.TL(object, #' signal.integral.min = 210, #' signal.integral.max = 220, #' log = "y", #' fit.method = "EXP OR LIN", #' sequence.structure = c("SIGNAL", "BACKGROUND")) #' #' @export analyse_SAR.TL <- function( object, object.background, signal.integral.min, signal.integral.max, sequence.structure = c("PREHEAT", "SIGNAL", "BACKGROUND"), rejection.criteria = list(recycling.ratio = 10, recuperation.rate = 10), dose.points, log = "", ... ){ # CONFIG ----------------------------------------------------------------- ##set allowed curve types type.curves <- c("TL") ##=============================================================================# # General Integrity Checks --------------------------------------------------- ##GENERAL ##MISSING INPUT if(missing("object")==TRUE){ stop("[analyse_SAR.TL] No value set for 'object'!") } if(missing("signal.integral.min") == TRUE){ stop("[analyse_SAR.TL] No value set for 'signal.integral.min'!") } if(missing("signal.integral.max") == TRUE){ stop("[analyse_SAR.TL] No value set for 'signal.integral.max'!") } ##INPUT OBJECTS if(is(object, "RLum.Analysis") == FALSE){ stop("[analyse_SAR.TL] Input object is not of type 'RLum.Analyis'!") } # Protocol Integrity Checks -------------------------------------------------- ##Remove non TL-curves from object by selecting TL curves object@records <- get_RLum(object, recordType = type.curves) ##ANALYSE SEQUENCE OBJECT STRUCTURE ##set vector for sequence structure temp.protocol.step <- rep(sequence.structure,length(object@records))[1:length(object@records)] ##grep object strucute temp.sequence.structure <- structure_RLum(object) ##set values for step temp.sequence.structure[,"protocol.step"] <- temp.protocol.step ##remove TL curves which are excluded temp.sequence.structure <- temp.sequence.structure[which( temp.sequence.structure[,"protocol.step"]!="EXCLUDE"),] ##check integrity; signal and bg range should be equal if(length( unique( temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","x.max"]))>1){ stop(paste( "[analyse_SAR.TL()] Signal range differs. Check sequence structure.\n", temp.sequence.structure )) } ##check if the wanted curves are a multiple of the structure if(length(temp.sequence.structure[,"id"])%%length(sequence.structure)!=0){ stop("[analyse_SAR.TL()] Input TL curves are not a multiple of the sequence structure.") } # # Calculate LnLxTnTx values -------------------------------------------------- ##grep IDs for signal and background curves TL.preheat.ID <- temp.sequence.structure[ temp.sequence.structure[,"protocol.step"] == "PREHEAT","id"] TL.signal.ID <- temp.sequence.structure[ temp.sequence.structure[,"protocol.step"] == "SIGNAL","id"] TL.background.ID <- temp.sequence.structure[ temp.sequence.structure[,"protocol.step"] == "BACKGROUND","id"] ##calculate LxTx values using external function for(i in seq(1,length(TL.signal.ID),by=2)){ temp.LnLxTnTx <- get_RLum( calc_TLLxTxRatio( Lx.data.signal = get_RLum(object, record.id=TL.signal.ID[i]), Lx.data.background = get_RLum(object, record.id=TL.background.ID[i]), Tx.data.signal = get_RLum(object, record.id=TL.signal.ID[i+1]), Tx.data.background = get_RLum(object, record.id = TL.background.ID[i+1]), signal.integral.min, signal.integral.max)) ##grep dose temp.Dose <- object@records[[TL.signal.ID[i]]]@info$IRR_TIME temp.LnLxTnTx <- cbind(Dose=temp.Dose, temp.LnLxTnTx) if(exists("LnLxTnTx")==FALSE){ LnLxTnTx <- data.frame(temp.LnLxTnTx) }else{ LnLxTnTx <- rbind(LnLxTnTx,temp.LnLxTnTx) } } ##set dose.points manual if argument was set if(!missing(dose.points)){ temp.Dose <- dose.points LnLxTnTx$Dose <- dose.points } # Set regeneration points ------------------------------------------------- #generate unique dose id - this are also the # for the generated points temp.DoseID <- c(0:(length(temp.Dose)-1)) temp.DoseName <- paste("R",temp.DoseID,sep="") temp.DoseName <- cbind(Name=temp.DoseName,Dose=temp.Dose) ##set natural temp.DoseName[temp.DoseName[,"Name"]=="R0","Name"]<-"Natural" ##set R0 temp.DoseName[temp.DoseName[,"Name"]!="Natural" & temp.DoseName[,"Dose"]==0,"Name"]<-"R0" ##find duplicated doses (including 0 dose - which means the Natural) temp.DoseDuplicated<-duplicated(temp.DoseName[,"Dose"]) ##combine temp.DoseName temp.DoseName<-cbind(temp.DoseName,Repeated=temp.DoseDuplicated) ##correct value for R0 (it is not really repeated) temp.DoseName[temp.DoseName[,"Dose"]==0,"Repeated"]<-FALSE ##combine in the data frame temp.LnLxTnTx<-data.frame(Name=temp.DoseName[,"Name"], Repeated=as.logical(temp.DoseName[,"Repeated"])) LnLxTnTx<-cbind(temp.LnLxTnTx,LnLxTnTx) LnLxTnTx[,"Name"]<-as.character(LnLxTnTx[,"Name"]) # Calculate Recycling Ratio ----------------------------------------------- ##Calculate Recycling Ratio if(length(LnLxTnTx[LnLxTnTx[,"Repeated"]==TRUE,"Repeated"])>0){ ##identify repeated doses temp.Repeated<-LnLxTnTx[LnLxTnTx[,"Repeated"]==TRUE,c("Name","Dose","LxTx")] ##find concering previous dose for the repeated dose temp.Previous<-t(sapply(1:length(temp.Repeated[,1]),function(x){ LnLxTnTx[LnLxTnTx[,"Dose"]==temp.Repeated[x,"Dose"] & LnLxTnTx[,"Repeated"]==FALSE,c("Name","Dose","LxTx")] })) ##convert to data.frame temp.Previous<-as.data.frame(temp.Previous) ##set column names temp.ColNames<-sapply(1:length(temp.Repeated[,1]),function(x){ paste(temp.Repeated[x,"Name"],"/", temp.Previous[temp.Previous[,"Dose"]==temp.Repeated[x,"Dose"],"Name"], sep="") }) ##Calculate Recycling Ratio RecyclingRatio<-as.numeric(temp.Repeated[,"LxTx"])/as.numeric(temp.Previous[,"LxTx"]) ##Just transform the matrix and add column names RecyclingRatio<-t(RecyclingRatio) colnames(RecyclingRatio)<-temp.ColNames }else{RecyclingRatio<-NA} # Calculate Recuperation Rate --------------------------------------------- ##Recuperation Rate if("R0" %in% LnLxTnTx[,"Name"]==TRUE){ Recuperation<-round(LnLxTnTx[LnLxTnTx[,"Name"]=="R0","LxTx"]/ LnLxTnTx[LnLxTnTx[,"Name"]=="Natural","LxTx"],digits=4) }else{Recuperation<-NA} # Combine and Evaluate Rejection Criteria --------------------------------- RejectionCriteria <- data.frame( citeria = c(colnames(RecyclingRatio), "recuperation rate"), value = c(RecyclingRatio,Recuperation), threshold = c( rep(paste("+/-", rejection.criteria$recycling.ratio/100) ,length(RecyclingRatio)), paste("", rejection.criteria$recuperation.rate/100) ), status = c( if(is.na(RecyclingRatio)==FALSE){ sapply(1:length(RecyclingRatio), function(x){ if(abs(1-RecyclingRatio[x])>(rejection.criteria$recycling.ratio/100)){ "FAILED" }else{"OK"}})}else{NA}, if(is.na(Recuperation)==FALSE & Recuperation>rejection.criteria$recuperation.rate){"FAILED"}else{"OK"} )) ##============================================================================## ##PLOTTING ##============================================================================## # Plotting - Config ------------------------------------------------------- ##grep plot parameter par.default <- par(no.readonly = TRUE) ##colours and double for plotting col <- get("col", pos = .LuminescenceEnv) col.doubled <- rep(col, each=2) layout(matrix(c(1,1,2,2, 1,1,2,2, 3,3,4,4, 3,3,4,4, 5,5,5,5),5,4,byrow=TRUE)) par(oma=c(0,0,0,0), mar=c(4,4,3,3)) ## 1 -> TL Lx ## 2 -> TL Tx ## 3 -> TL Lx Plateau ## 4 -> TL Tx Plateau ## 5 -> Legend ##recalculate signal.integral from channels to temperature signal.integral.temperature <- c(object@records[[TL.signal.ID[1]]]@data[signal.integral.min,1] : object@records[[TL.signal.ID[1]]]@data[signal.integral.max,1]) ##warning if number of curves exceed colour values if(length(col)<length(TL.signal.ID/2)){ cat("\n[analyse_SAR.TL.R] Warning: To many curves! Only the first", length(col),"curves are plotted!") } # # Plotting TL Lx Curves ---------------------------------------------------- #open plot area LnLx plot(NA,NA, xlab="Temp. [\u00B0C]", ylab=paste("TL [a.u.]",sep=""), xlim=c(0.1, max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","x.max"])), ylim=c( min(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.min"]), max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.max"])), main=expression(paste(L[n],",",L[x]," curves",sep="")), log=log) ##plot curves sapply(seq(1,length(TL.signal.ID),by=2), function(x){ lines(object@records[[TL.signal.ID[x]]]@data,col=col.doubled[x]) }) ##mark integration limits abline(v=min(signal.integral.temperature), lty=2, col="gray") abline(v=max(signal.integral.temperature), lty=2, col="gray") # Plotting TnTx Curves ---------------------------------------------------- #open plot area TnTx plot(NA,NA, xlab="Temp. [\u00B0C]", ylab=paste("TL [a.u.]",sep=""), xlim=c(0.1, max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","x.max"])), ylim=c( min(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.min"]), max(temp.sequence.structure[temp.sequence.structure[,"protocol.step"]=="SIGNAL","y.max"])), main=expression(paste(T[n],",",T[x]," curves",sep="")), log=log) ##plot curves sapply(seq(2,length(TL.signal.ID),by=2), function(x){ lines(object@records[[TL.signal.ID[x]]]@data,col=col.doubled[x]) }) ##mark integration limits abline(v=min(signal.integral.temperature), lty=2, col="gray") abline(v=max(signal.integral.temperature), lty=2, col="gray") # Plotting Plateau Test LnLx ------------------------------------------------- NTL.net.LnLx <- data.frame(object@records[[TL.signal.ID[1]]]@data[,1], object@records[[TL.signal.ID[1]]]@data[,2]- object@records[[TL.background.ID[1]]]@data[,2]) Reg1.net.LnLx <- data.frame(object@records[[TL.signal.ID[3]]]@data[,1], object@records[[TL.signal.ID[3]]]@data[,2]- object@records[[TL.background.ID[3]]]@data[,2]) TL.Plateau.LnLx <- data.frame(NTL.net.LnLx[,1], Reg1.net.LnLx[,2]/NTL.net.LnLx[,2]) ##Plot Plateau Test plot(NA, NA, xlab = "Temp. [\u00B0C]", ylab = "TL [a.u.]", xlim = c(min(signal.integral.temperature)*0.9, max(signal.integral.temperature)*1.1), ylim = c(0, max(NTL.net.LnLx[,2])), main = expression(paste("Plateau test ",L[n],",",L[x]," curves",sep="")) ) ##plot single curves lines(NTL.net.LnLx, col=col[1]) lines(Reg1.net.LnLx, col=col[2]) ##plot par(new=TRUE) plot(TL.Plateau.LnLx, axes=FALSE, xlab="", ylab="", ylim=c(0, quantile(TL.Plateau.LnLx[c(signal.integral.min:signal.integral.max),2], probs = c(0.90), na.rm = TRUE)+3), col="darkgreen") axis(4) # Plotting Plateau Test TnTx ------------------------------------------------- ##get NTL signal NTL.net.TnTx <- data.frame(object@records[[TL.signal.ID[2]]]@data[,1], object@records[[TL.signal.ID[2]]]@data[,2]- object@records[[TL.background.ID[2]]]@data[,2]) ##get signal from the first regeneration point Reg1.net.TnTx <- data.frame(object@records[[TL.signal.ID[4]]]@data[,1], object@records[[TL.signal.ID[4]]]@data[,2]- object@records[[TL.background.ID[4]]]@data[,2]) ##combine values TL.Plateau.TnTx <- data.frame(NTL.net.TnTx[,1], Reg1.net.TnTx[,2]/NTL.net.TnTx[,2]) ##Plot Plateau Test plot(NA, NA, xlab = "Temp. [\u00B0C]", ylab = "TL [a.u.]", xlim = c(min(signal.integral.temperature)*0.9, max(signal.integral.temperature)*1.1), ylim = c(0, max(NTL.net.TnTx[,2])), main = expression(paste("plateau Test ",T[n],",",T[x]," curves",sep="")) ) ##plot single curves lines(NTL.net.TnTx, col=col[1]) lines(Reg1.net.TnTx, col=col[2]) ##plot par(new=TRUE) plot(TL.Plateau.TnTx, axes=FALSE, xlab="", ylab="", ylim=c(0, quantile(TL.Plateau.TnTx[c(signal.integral.min:signal.integral.max),2], probs = c(0.90), na.rm = TRUE)+3), col="darkgreen") axis(4) # Plotting Legend ---------------------------------------- plot(c(1:(length(TL.signal.ID)/2)), rep(8,length(TL.signal.ID)/2), type = "p", axes=FALSE, xlab="", ylab="", pch=15, col=col[1:length(TL.signal.ID)], cex=2, ylim=c(0,10) ) ##add text text(c(1:(length(TL.signal.ID)/2)), rep(4,length(TL.signal.ID)/2), paste(LnLxTnTx$Name,"\n(",LnLxTnTx$Dose,")", sep="") ) ##add line abline(h=10,lwd=0.5) ##set failed text and mark De as failed if(length(grep("FAILED",RejectionCriteria$status))>0){ mtext("[FAILED]", col="red") } ##reset par par(par.default) rm(par.default) # Plotting GC ---------------------------------------- temp.sample <- data.frame(Dose=LnLxTnTx$Dose, LxTx=LnLxTnTx$LxTx, LxTx.Error=LnLxTnTx$LxTx*0.1, TnTx=LnLxTnTx$TnTx ) temp.GC <- get_RLum(plot_GrowthCurve(temp.sample, ...))[,c("De","De.Error")] ##add recjection status if(length(grep("FAILED",RejectionCriteria$status))>0){ temp.GC <- data.frame(temp.GC, RC.Status="FAILED") }else{ temp.GC <- data.frame(temp.GC, RC.Status="OK") } # Return Values ----------------------------------------------------------- newRLumResults.analyse_SAR.TL <- set_RLum( class = "RLum.Results", data = list( De.values = temp.GC, LnLxTnTx.table = LnLxTnTx, rejection.criteria = RejectionCriteria)) return(newRLumResults.analyse_SAR.TL) }
complete <- function(directory, id = 1:332){ data <- NULL result <- NULL # get a list of all files in the specified directory that end in .csv files <- list.files(directory, pattern="*.csv") # loop through the monitors specified for(index in id) { # build a path to the file path <- file.path(directory, files[index]) # print(path) # read in the data data <- read.csv(path)#, nrows=5) # only include complete cases data <- data[complete.cases(data),] # combine, by rows, the monitor number and a sum of the completed cases result <- rbind(result, c(id=index, nobs=nrow(data))) } # print(result) # print(class(result)) # requirements state to return this result as a dataframe (convert our matrix to a dataframe) return(data.frame(result)) } answer <- complete("/home/user/Downloads/specdata", 1) print(answer) print("=====") answer <- complete("/home/user/Downloads/specdata", c(2, 4, 8, 10, 12)) print(answer) print("=====") answer <- complete("/home/user/Downloads/specdata", 30:25) print(answer) print("=====") answer <- complete("/home/user/Downloads/specdata", 3) print(answer)
/Week2/complete.R
no_license
XAGV1YBGAdk34WDPVVLn/datasciencecoursera
R
false
false
1,212
r
complete <- function(directory, id = 1:332){ data <- NULL result <- NULL # get a list of all files in the specified directory that end in .csv files <- list.files(directory, pattern="*.csv") # loop through the monitors specified for(index in id) { # build a path to the file path <- file.path(directory, files[index]) # print(path) # read in the data data <- read.csv(path)#, nrows=5) # only include complete cases data <- data[complete.cases(data),] # combine, by rows, the monitor number and a sum of the completed cases result <- rbind(result, c(id=index, nobs=nrow(data))) } # print(result) # print(class(result)) # requirements state to return this result as a dataframe (convert our matrix to a dataframe) return(data.frame(result)) } answer <- complete("/home/user/Downloads/specdata", 1) print(answer) print("=====") answer <- complete("/home/user/Downloads/specdata", c(2, 4, 8, 10, 12)) print(answer) print("=====") answer <- complete("/home/user/Downloads/specdata", 30:25) print(answer) print("=====") answer <- complete("/home/user/Downloads/specdata", 3) print(answer)
# Set working direcotory this.dir <- dirname(parent.frame(2)$ofile) setwd(this.dir) library(dplyr) library(rpart) library(rpart.plot) library(party) library(readr) #Feature Engineering train <- read_csv('HR_comma_sep.csv') train$sales <- as.factor(train$sales) train$salary <- as.factor(train$salary) #Fitting a Conditional Inference Tree set.seed <- (1987) fit <- cforest(as.factor(left) ~ ., data = train, controls = cforest_unbiased(ntree = 2000, mtry = 3)) #Viewing a sample tree party:::prettytree(fit@ensemble[[1]], names(fit@data@get("input"))) #Predicting for the test dataset using CIT prediction <- predict(fit, train, OOB = TRUE, type = "response") submit <- data.frame(Actual = train$left, Predicted = prediction) prop.table(table(submit$Actual, submit$Predicted),1)
/HR Analytics/HR_Analytics.R
no_license
kshirasaagar/Kaggle
R
false
false
841
r
# Set working direcotory this.dir <- dirname(parent.frame(2)$ofile) setwd(this.dir) library(dplyr) library(rpart) library(rpart.plot) library(party) library(readr) #Feature Engineering train <- read_csv('HR_comma_sep.csv') train$sales <- as.factor(train$sales) train$salary <- as.factor(train$salary) #Fitting a Conditional Inference Tree set.seed <- (1987) fit <- cforest(as.factor(left) ~ ., data = train, controls = cforest_unbiased(ntree = 2000, mtry = 3)) #Viewing a sample tree party:::prettytree(fit@ensemble[[1]], names(fit@data@get("input"))) #Predicting for the test dataset using CIT prediction <- predict(fit, train, OOB = TRUE, type = "response") submit <- data.frame(Actual = train$left, Predicted = prediction) prop.table(table(submit$Actual, submit$Predicted),1)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lime-package.r \docType{package} \name{lime-package} \alias{lime-package} \alias{_PACKAGE} \title{lime: Local Interpretable Model-Agnostic Explanations} \description{ \if{html}{\figure{logo.png}{options: align='right'}} When building complex models, it is often difficult to explain why the model should be trusted. While global measures such as accuracy are useful, they cannot be used for explaining why a model made a specific prediction. 'lime' (a port of the 'lime' 'Python' package) is a method for explaining the outcome of black box models by fitting a local model around the point in question an perturbations of this point. The approach is described in more detail in the article by Ribeiro et al. (2016) <arXiv:1602.04938>. } \details{ This package is a port of the original Python lime package implementing the prediction explanation framework laid out Ribeiro \emph{et al.} (2016). The package supports models from \code{caret} and \code{mlr} natively, but see \link[=model_support]{the docs} for how to make it work for any model. \strong{Main functions:} Use of \code{lime} is mainly through two functions. First you create an \code{explainer} object using the \code{\link[=lime]{lime()}} function based on the training data and the model, and then you can use the \code{\link[=explain]{explain()}} function along with new data and the explainer to create explanations for the model output. Along with these two functions, \code{lime} also provides the \code{\link[=plot_features]{plot_features()}} and \code{\link[=plot_text_explanations]{plot_text_explanations()}} function to visualise the explanations directly. } \references{ Ribeiro, M.T., Singh, S., Guestrin, C. \emph{"Why Should I Trust You?": Explaining the Predictions of Any Classifier}. 2016, \url{https://arxiv.org/abs/1602.04938} } \seealso{ Useful links: \itemize{ \item \url{https://lime.data-imaginist.com} \item \url{https://github.com/thomasp85/lime} \item Report bugs at \url{https://github.com/thomasp85/lime/issues} } } \author{ \strong{Maintainer}: Thomas Lin Pedersen \email{thomasp85@gmail.com} (0000-0002-5147-4711) Authors: \itemize{ \item MichaΓ«l Benesty \email{michael@benesty.fr} } }
/man/lime-package.Rd
permissive
goodekat/lime
R
false
true
2,303
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lime-package.r \docType{package} \name{lime-package} \alias{lime-package} \alias{_PACKAGE} \title{lime: Local Interpretable Model-Agnostic Explanations} \description{ \if{html}{\figure{logo.png}{options: align='right'}} When building complex models, it is often difficult to explain why the model should be trusted. While global measures such as accuracy are useful, they cannot be used for explaining why a model made a specific prediction. 'lime' (a port of the 'lime' 'Python' package) is a method for explaining the outcome of black box models by fitting a local model around the point in question an perturbations of this point. The approach is described in more detail in the article by Ribeiro et al. (2016) <arXiv:1602.04938>. } \details{ This package is a port of the original Python lime package implementing the prediction explanation framework laid out Ribeiro \emph{et al.} (2016). The package supports models from \code{caret} and \code{mlr} natively, but see \link[=model_support]{the docs} for how to make it work for any model. \strong{Main functions:} Use of \code{lime} is mainly through two functions. First you create an \code{explainer} object using the \code{\link[=lime]{lime()}} function based on the training data and the model, and then you can use the \code{\link[=explain]{explain()}} function along with new data and the explainer to create explanations for the model output. Along with these two functions, \code{lime} also provides the \code{\link[=plot_features]{plot_features()}} and \code{\link[=plot_text_explanations]{plot_text_explanations()}} function to visualise the explanations directly. } \references{ Ribeiro, M.T., Singh, S., Guestrin, C. \emph{"Why Should I Trust You?": Explaining the Predictions of Any Classifier}. 2016, \url{https://arxiv.org/abs/1602.04938} } \seealso{ Useful links: \itemize{ \item \url{https://lime.data-imaginist.com} \item \url{https://github.com/thomasp85/lime} \item Report bugs at \url{https://github.com/thomasp85/lime/issues} } } \author{ \strong{Maintainer}: Thomas Lin Pedersen \email{thomasp85@gmail.com} (0000-0002-5147-4711) Authors: \itemize{ \item MichaΓ«l Benesty \email{michael@benesty.fr} } }
\name{calendarHeat} \alias{calendarHeat} \title{An R function to display time-series data as a calendar heatmap} \usage{ calendarHeat(dates, values, ncolors = 99, color = "r2g", varname = "Values", date.form = "\%Y-\%m-\%d", ...) } \arguments{ \item{dates}{vector of Dates} \item{values}{vector of values} \item{ncolors}{number of colors to use} \item{color}{the color scheme to use. Currently supports r2b, (red to blue), r2g (red to green), and w2b (white to blue).} \item{varname}{varaible names} \item{date.form}{the format of the Date column} \item{...}{other non-specified parameters} } \description{ This graphic originally appeared \href{http://stat-computing.org/dataexpo/2009/posters/wicklin-allison.pdf}{here}. This function is included with the \code{makeR} package to support the R-Bloggers demo. See \code{demo('makeR')} for more information. } \author{ Paul Bleicher }
/man/calendarHeat.Rd
no_license
jbryer/makeR
R
false
false
927
rd
\name{calendarHeat} \alias{calendarHeat} \title{An R function to display time-series data as a calendar heatmap} \usage{ calendarHeat(dates, values, ncolors = 99, color = "r2g", varname = "Values", date.form = "\%Y-\%m-\%d", ...) } \arguments{ \item{dates}{vector of Dates} \item{values}{vector of values} \item{ncolors}{number of colors to use} \item{color}{the color scheme to use. Currently supports r2b, (red to blue), r2g (red to green), and w2b (white to blue).} \item{varname}{varaible names} \item{date.form}{the format of the Date column} \item{...}{other non-specified parameters} } \description{ This graphic originally appeared \href{http://stat-computing.org/dataexpo/2009/posters/wicklin-allison.pdf}{here}. This function is included with the \code{makeR} package to support the R-Bloggers demo. See \code{demo('makeR')} for more information. } \author{ Paul Bleicher }
\name{countries} \alias{countries} \docType{data} \title{Socioeconomic data for the most populous countries.} \description{ Socioeconomic data for the most populous countries. } \usage{data(countries)} \format{ A data frame with 42 observations on the following 7 variables. \describe{ \item{Country}{name of the country.} \item{Popul}{population.} \item{PopDens}{population density.} \item{GDPpp}{GDP per inhabitant.} \item{LifeEx}{mean life expectation} \item{InfMor}{infant mortality} \item{Illit}{illiteracy rate} } } \source{ CIA World Factbook \url{https://www.cia.gov/the-world-factbook/} } \examples{ data(countries) summary(countries) } \keyword{datasets}
/man/countries.Rd
no_license
cran/klaR
R
false
false
731
rd
\name{countries} \alias{countries} \docType{data} \title{Socioeconomic data for the most populous countries.} \description{ Socioeconomic data for the most populous countries. } \usage{data(countries)} \format{ A data frame with 42 observations on the following 7 variables. \describe{ \item{Country}{name of the country.} \item{Popul}{population.} \item{PopDens}{population density.} \item{GDPpp}{GDP per inhabitant.} \item{LifeEx}{mean life expectation} \item{InfMor}{infant mortality} \item{Illit}{illiteracy rate} } } \source{ CIA World Factbook \url{https://www.cia.gov/the-world-factbook/} } \examples{ data(countries) summary(countries) } \keyword{datasets}
install.packages("qdap") install.packages("qdapTools") library(qdapTools) library(tm) Source_dir <- c("d:/data") Find_word <- c("management") mylist <-c("here is the list") files1 <-list.files(Source_dir,pattern=".docx") # files1 # # count1 <-length(table(files1)) # count1 # # files1[1] # # name_file <- paste("d:/data/",files1[1],sep = "") # name_file # # files1[11] # # read_docx(paste("d:/data/ Good Requirement.docx")) # paste("d:/data/",files1[11],sep = "") # sprintf("d:/data/",files1[11]) # data_1<- read_docx(paste("d:/data/",files1[11],sep = "")) # data_1 # count_occurence <- function (y) { (text_docx <- read_docx(paste("d:/data/",y,sep = ""))) x <- length(grep("Find_word",text_docx)) return(x) } for (i in files1){ x<- count_occurence(i) print(x) print(i) if (x!=0){ mylist[[length(mylist)+1]] <- i } } mylist # if (length(count_occurence)==0){ mylist[[length(mylist)+1]] <- y } # data2 <-docx_data(files1[1]) # data2 # count_occurence <- grep("management",data2) length(count_occurence) # str(count_occurence) #if (length(count_occurence)==0){ mylist[[length(mylist)+1]] <- y } lapply(files1,docx_data) for(i in files1){ data1 <- cbind("d:/data/", i) data1} for(i in files1){ print(i)} val <- LETTERS[1:4] for ( i in val) { print(i) } str(val) str(files1)
/Finding the right document_1.R
no_license
karankkamra1987/R-Practice
R
false
false
1,425
r
install.packages("qdap") install.packages("qdapTools") library(qdapTools) library(tm) Source_dir <- c("d:/data") Find_word <- c("management") mylist <-c("here is the list") files1 <-list.files(Source_dir,pattern=".docx") # files1 # # count1 <-length(table(files1)) # count1 # # files1[1] # # name_file <- paste("d:/data/",files1[1],sep = "") # name_file # # files1[11] # # read_docx(paste("d:/data/ Good Requirement.docx")) # paste("d:/data/",files1[11],sep = "") # sprintf("d:/data/",files1[11]) # data_1<- read_docx(paste("d:/data/",files1[11],sep = "")) # data_1 # count_occurence <- function (y) { (text_docx <- read_docx(paste("d:/data/",y,sep = ""))) x <- length(grep("Find_word",text_docx)) return(x) } for (i in files1){ x<- count_occurence(i) print(x) print(i) if (x!=0){ mylist[[length(mylist)+1]] <- i } } mylist # if (length(count_occurence)==0){ mylist[[length(mylist)+1]] <- y } # data2 <-docx_data(files1[1]) # data2 # count_occurence <- grep("management",data2) length(count_occurence) # str(count_occurence) #if (length(count_occurence)==0){ mylist[[length(mylist)+1]] <- y } lapply(files1,docx_data) for(i in files1){ data1 <- cbind("d:/data/", i) data1} for(i in files1){ print(i)} val <- LETTERS[1:4] for ( i in val) { print(i) } str(val) str(files1)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/nn.R \name{nn} \alias{nn} \title{Get names and class of all columns in a data frame} \usage{ nn(df) } \arguments{ \item{df}{A data.frame.} } \value{ A data.frame with index and class. } \description{ Get names and class of all columns in a data frame in a friendly format. } \examples{ nn(iris) } \author{ Stephen Turner } \keyword{NA}
/man/nn.Rd
no_license
gmaubach/Tmisc
R
false
true
416
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/nn.R \name{nn} \alias{nn} \title{Get names and class of all columns in a data frame} \usage{ nn(df) } \arguments{ \item{df}{A data.frame.} } \value{ A data.frame with index and class. } \description{ Get names and class of all columns in a data frame in a friendly format. } \examples{ nn(iris) } \author{ Stephen Turner } \keyword{NA}
library(magick) library(grid) ggname = ggimage:::ggname color_image = ggimage:::color_image # color_image = function (img, color, alpha = NULL) # { # if (is.null(color)) # return(img) # if (length(color) > 1) { # stop("color should be a vector of length 1") # } # bitmap <- img[[1]] # col <- col2rgb(color) # bitmap[1, , ] <- as.raw(col[1]) # bitmap[2, , ] <- as.raw(col[2]) # bitmap[3, , ] <- as.raw(col[3]) # if (!is.null(alpha) && alpha != 1) # browser() # if(dim(bitmap)[1] == 3){ # bitmap[,4] = as.raw(255) # } # bitmap[4, , ] <- as.raw(as.integer(bitmap[4, , ]) * alpha) # image_read(bitmap) # } ##' geom layer for visualizing image files ##' ##' ##' @title geom_image.rect ##' @param mapping aes mapping ##' @param data data ##' @param stat stat ##' @param position position ##' @param inherit.aes logical, whether inherit aes from ggplot() ##' @param na.rm logical, whether remove NA values ##' @param by one of 'width' or 'height' ##' @param nudge_x horizontal adjustment to nudge image ##' @param ... additional parameters ##' @return geom layer ##' @importFrom ggplot2 layer ##' @export ##' @examples ##' library("ggplot2") ##' library("ggimage") ##' set.seed(2017-02-21) ##' d <- data.frame(x = rnorm(10), ##' y = rnorm(10), ##' image = sample(c("https://www.r-project.org/logo/Rlogo.png", ##' "https://jeroenooms.github.io/images/frink.png"), ##' size=10, replace = TRUE) ##' ) ##' ggplot(d, aes(x, y)) + geom_image(aes(image=image)) ##' @author guangchuang yu geom_image.rect <- function(mapping=NULL, data=NULL, stat="identity", position="identity", inherit.aes=TRUE, na.rm=FALSE, # by="width", # nudge_x = 0, ...) { # by <- match.arg(by, c("width", "height")) layer( data=data, mapping=mapping, geom=GeomImage.rect, stat=stat, position=position, show.legend=NA, inherit.aes=inherit.aes, params = list( na.rm = na.rm, # by = by, # nudge_x = nudge_x, ##angle = angle, ...), check.aes = FALSE ) } ##' @importFrom ggplot2 ggproto ##' @importFrom ggplot2 Geom ##' @importFrom ggplot2 aes ##' @importFrom ggplot2 draw_key_blank ##' @importFrom grid gTree ##' @importFrom grid gList GeomImage.rect <- ggproto("GeomImage.rect", Geom, setup_data = function(data, params) { if (is.null(data$subset)) return(data) data[which(data$subset),] }, default_aes = aes(image=system.file("extdata/Rlogo.png", package="ggimage"), #size=0.05, colour = NULL, #angle = 0, alpha=1), draw_panel = function(data, panel_params, coord, by, na.rm=FALSE, .fun = NULL, height, image_fun = NULL, # hjust=0.5, # nudge_x = 0, nudge_y = 0, asp=1) { # data$x <- data$x + nudge_x # data$y <- data$y + nudge_y data <- coord$transform(data, panel_params) if (!is.null(.fun) && is.function(.fun)) data$image <- .fun(data$image) groups <- split(data, factor(data$image)) imgs <- names(groups) grobs <- lapply(seq_along(groups), function(i) { d <- groups[[i]] imageGrob.rect(d$xmin, d$xmax, d$ymin, d$ymax, imgs[i], #by, # hjust, d$colour, d$alpha, image_fun, #d$angle, asp) }) grobs <- do.call("c", grobs) class(grobs) <- "gList" ggname("geom_image.rect", gTree(children = grobs)) }, non_missing_aes = c(#"size", "image"), required_aes = c("xmin", "xmax", "ymin", "ymax"), draw_key = draw_key_image ## draw_key_blank ## need to write the `draw_key_image` function. ) ##' @importFrom magick image_read ##' @importFrom magick image_read_svg ##' @importFrom magick image_read_pdf ##' @importFrom magick image_transparent ##' @importFrom magick image_rotate ##' @importFrom grid rasterGrob ##' @importFrom grid viewport ##' @importFrom grDevices rgb ##' @importFrom grDevices col2rgb ##' @importFrom methods is ##' @importFrom tools file_ext imageGrob.rect <- function(xmin, xmax, ymin, ymax, img, #by, hjust, colour, alpha, image_fun, #angle, asp=1) { if (!is(img, "magick-image")) { if (tools::file_ext(img) == "svg") { img <- image_read_svg(img) } else if (tools::file_ext(img) == "pdf") { img <- image_read_pdf(img) } else { img <- image_read(img) } asp <- getAR2(img)/asp } unit <- "native" width = xmax - xmin height = ymax - ymin # if (any(size == Inf)) { # x <- 0.5 # y <- 0.5 # width <- 1 # height <- 1 # unit <- "npc" # } else if (by == "width") { # width <- size # height <- size/asp # } else { # width <- size * asp # height <- size # } # # if (hjust == 0 || hjust == "left") { # x <- x + width/2 # } else if (hjust == 1 || hjust == "right") { # x <- x - width/2 # } if (!is.null(image_fun)) { img <- image_fun(img) } if (is.null(colour)) { grobs <- list() grobs[[1]] <- rasterGrob(x = xmin, y = ymin, just = c(0,0), image = img, default.units = unit, height = height, width = width, interpolate = FALSE) } else { cimg <- lapply(seq_along(colour), function(i) { color_image(img, colour[i], alpha[i]) }) grobs <- lapply(seq_along(xmin), function(i) { img <- cimg[[i]] # if (angle[i] != 0) { # img <- image_rotate(img, angle[i]) # img <- image_transparent(img, "white") # } rasterGrob(x = xmin[i], y = ymin[i], just = c(0,0), image = img, default.units = unit, height = height[i], width = width[i], interpolate = FALSE ## gp = gpar(rot = angle[i]) ## vp = viewport(angle=angle[i]) ) }) } return(grobs) } ##' @importFrom magick image_info getAR2 <- function(magick_image) { info <- image_info(magick_image) info$width/info$height } compute_just <- getFromNamespace("compute_just", "ggplot2")
/geom_image.rect.R
no_license
jrboyd/waldron
R
false
false
7,889
r
library(magick) library(grid) ggname = ggimage:::ggname color_image = ggimage:::color_image # color_image = function (img, color, alpha = NULL) # { # if (is.null(color)) # return(img) # if (length(color) > 1) { # stop("color should be a vector of length 1") # } # bitmap <- img[[1]] # col <- col2rgb(color) # bitmap[1, , ] <- as.raw(col[1]) # bitmap[2, , ] <- as.raw(col[2]) # bitmap[3, , ] <- as.raw(col[3]) # if (!is.null(alpha) && alpha != 1) # browser() # if(dim(bitmap)[1] == 3){ # bitmap[,4] = as.raw(255) # } # bitmap[4, , ] <- as.raw(as.integer(bitmap[4, , ]) * alpha) # image_read(bitmap) # } ##' geom layer for visualizing image files ##' ##' ##' @title geom_image.rect ##' @param mapping aes mapping ##' @param data data ##' @param stat stat ##' @param position position ##' @param inherit.aes logical, whether inherit aes from ggplot() ##' @param na.rm logical, whether remove NA values ##' @param by one of 'width' or 'height' ##' @param nudge_x horizontal adjustment to nudge image ##' @param ... additional parameters ##' @return geom layer ##' @importFrom ggplot2 layer ##' @export ##' @examples ##' library("ggplot2") ##' library("ggimage") ##' set.seed(2017-02-21) ##' d <- data.frame(x = rnorm(10), ##' y = rnorm(10), ##' image = sample(c("https://www.r-project.org/logo/Rlogo.png", ##' "https://jeroenooms.github.io/images/frink.png"), ##' size=10, replace = TRUE) ##' ) ##' ggplot(d, aes(x, y)) + geom_image(aes(image=image)) ##' @author guangchuang yu geom_image.rect <- function(mapping=NULL, data=NULL, stat="identity", position="identity", inherit.aes=TRUE, na.rm=FALSE, # by="width", # nudge_x = 0, ...) { # by <- match.arg(by, c("width", "height")) layer( data=data, mapping=mapping, geom=GeomImage.rect, stat=stat, position=position, show.legend=NA, inherit.aes=inherit.aes, params = list( na.rm = na.rm, # by = by, # nudge_x = nudge_x, ##angle = angle, ...), check.aes = FALSE ) } ##' @importFrom ggplot2 ggproto ##' @importFrom ggplot2 Geom ##' @importFrom ggplot2 aes ##' @importFrom ggplot2 draw_key_blank ##' @importFrom grid gTree ##' @importFrom grid gList GeomImage.rect <- ggproto("GeomImage.rect", Geom, setup_data = function(data, params) { if (is.null(data$subset)) return(data) data[which(data$subset),] }, default_aes = aes(image=system.file("extdata/Rlogo.png", package="ggimage"), #size=0.05, colour = NULL, #angle = 0, alpha=1), draw_panel = function(data, panel_params, coord, by, na.rm=FALSE, .fun = NULL, height, image_fun = NULL, # hjust=0.5, # nudge_x = 0, nudge_y = 0, asp=1) { # data$x <- data$x + nudge_x # data$y <- data$y + nudge_y data <- coord$transform(data, panel_params) if (!is.null(.fun) && is.function(.fun)) data$image <- .fun(data$image) groups <- split(data, factor(data$image)) imgs <- names(groups) grobs <- lapply(seq_along(groups), function(i) { d <- groups[[i]] imageGrob.rect(d$xmin, d$xmax, d$ymin, d$ymax, imgs[i], #by, # hjust, d$colour, d$alpha, image_fun, #d$angle, asp) }) grobs <- do.call("c", grobs) class(grobs) <- "gList" ggname("geom_image.rect", gTree(children = grobs)) }, non_missing_aes = c(#"size", "image"), required_aes = c("xmin", "xmax", "ymin", "ymax"), draw_key = draw_key_image ## draw_key_blank ## need to write the `draw_key_image` function. ) ##' @importFrom magick image_read ##' @importFrom magick image_read_svg ##' @importFrom magick image_read_pdf ##' @importFrom magick image_transparent ##' @importFrom magick image_rotate ##' @importFrom grid rasterGrob ##' @importFrom grid viewport ##' @importFrom grDevices rgb ##' @importFrom grDevices col2rgb ##' @importFrom methods is ##' @importFrom tools file_ext imageGrob.rect <- function(xmin, xmax, ymin, ymax, img, #by, hjust, colour, alpha, image_fun, #angle, asp=1) { if (!is(img, "magick-image")) { if (tools::file_ext(img) == "svg") { img <- image_read_svg(img) } else if (tools::file_ext(img) == "pdf") { img <- image_read_pdf(img) } else { img <- image_read(img) } asp <- getAR2(img)/asp } unit <- "native" width = xmax - xmin height = ymax - ymin # if (any(size == Inf)) { # x <- 0.5 # y <- 0.5 # width <- 1 # height <- 1 # unit <- "npc" # } else if (by == "width") { # width <- size # height <- size/asp # } else { # width <- size * asp # height <- size # } # # if (hjust == 0 || hjust == "left") { # x <- x + width/2 # } else if (hjust == 1 || hjust == "right") { # x <- x - width/2 # } if (!is.null(image_fun)) { img <- image_fun(img) } if (is.null(colour)) { grobs <- list() grobs[[1]] <- rasterGrob(x = xmin, y = ymin, just = c(0,0), image = img, default.units = unit, height = height, width = width, interpolate = FALSE) } else { cimg <- lapply(seq_along(colour), function(i) { color_image(img, colour[i], alpha[i]) }) grobs <- lapply(seq_along(xmin), function(i) { img <- cimg[[i]] # if (angle[i] != 0) { # img <- image_rotate(img, angle[i]) # img <- image_transparent(img, "white") # } rasterGrob(x = xmin[i], y = ymin[i], just = c(0,0), image = img, default.units = unit, height = height[i], width = width[i], interpolate = FALSE ## gp = gpar(rot = angle[i]) ## vp = viewport(angle=angle[i]) ) }) } return(grobs) } ##' @importFrom magick image_info getAR2 <- function(magick_image) { info <- image_info(magick_image) info$width/info$height } compute_just <- getFromNamespace("compute_just", "ggplot2")
regwqComp <- function (formula, data, alpha=.05) { # this is a reworked version of regwq.R from the mutoss package # rounding is removed # output is reordered in a standard order # sqrt(2) factor removed from test statistic (and adjusted elsewhere) # # important - the adjusted p values are compared to the adjusted alphas # it is NOT enough to compare adjusted p to the original alpha # # no guarantees on the procedure itself as that is preserved from mutoss if (missing(data)) { dat <- model.frame(formula) } else { dat <- model.frame(formula, data) } if (ncol(dat) != 2) { stop("Specify one response and only one class variable in the formula") } if (is.numeric(dat[, 1]) == FALSE) { stop("Response variable must be numeric") } response <- dat[, 1] group <- as.factor(dat[, 2]) fl <- levels(group) a <- nlevels(group) N <- length(response) samples <- split(response, group) n <- sapply(samples, "length") mm <- sapply(samples, "mean") vv <- sapply(samples, "var") MSE <- sum((n - 1) * vv)/(N - a) df <- N - a nc <- a * (a - 1)/2 order.h1 <- data.frame(Sample = fl, SampleNum = 1:a, Size = n, Means = mm, Variance = vv) ordered <- order.h1[order(order.h1$Means, decreasing = FALSE), ] rownames(ordered) <- 1:a i <- 1:(a - 1) h1 <- list() for (s in 1:(a - 1)) { h1[[s]] <- i[1:s] } vi <- unlist(h1) j <- a:2 h2 <- list() for (s in 1:(a - 1)) { h2[[s]] <- j[s:1] } vj <- unlist(h2) h3 <- list() h4 <- list() for (s in 1:(a - 1)) { h3[[s]] <- rep(j[s], s) h4[[s]] <- rep(i[s], s) } Nmean <- unlist(h3) Step <- unlist(h4) mean.difference <- sapply(1:nc, function(arg) { i <- vi[arg] j <- vj[arg] (ordered$Means[j] - ordered$Means[i]) }) T <- sapply(1:nc, function(arg) { i <- vi[arg] j <- vj[arg] (ordered$Means[j] - ordered$Means[i])/sqrt(MSE * (1/ordered$Size[i] + 1/ordered$Size[j])) }) pvalues <- ptukey(T*sqrt(2), Nmean, df, lower.tail = FALSE) alpha.level <- 1 - (1 - alpha)^(Nmean/a) level1 <- (Nmean == a) level2 <- (Nmean == a - 1) level3 <- level1 + level2 alpha.level[level3 == 1] <- alpha quantiles <- qtukey(1 - alpha.level, Nmean, df) for (h in 1:(nc - 1)) { if (quantiles[h + 1] >= quantiles[h]) { quantiles[h + 1] <- quantiles[h] } } Rejected1 <- (pvalues < alpha.level) names.ordered <- sapply(1:nc, function(arg) { i <- vi[arg] j <- vj[arg] paste(ordered$Sample[j], "-", ordered$Sample[i], sep = "") }) for (s in 1:nc) { if (Rejected1[s] == FALSE) { Under1 <- (vj[s] >= vj) Under2 <- (vi[s] <= vi) Under3 <- Under1 * Under2 Under4 <- which(Under3 == 1) Rejected1[Under4] <- FALSE } } # add code here to put rows in standard order and flip diff and T if necessary # first build a matrix that will contain the desired row numbers rowOrderMat <- matrix(0,a,a) rowOrderMat[lower.tri(rowOrderMat)]<-1:nc rownames(rowOrderMat) <- fl colnames(rowOrderMat) <- fl rowOrderVec <- numeric(nc) signVec <- rep(1,nc) for (s in 1:nc){ i <- vi[s] j <- vj[s] si <- ordered$SampleNum[i] sj <- ordered$SampleNum[j] if (si<sj){ rowOrderVec[s] <- rowOrderMat[sj,si] } else{ rowOrderVec[s] <- rowOrderMat[si,sj] names.ordered[s] <- paste(ordered$Sample[i], "-", ordered$Sample[j], sep = "") mean.difference[s] <- -mean.difference[s] T[s] <- -T[s] } } ind <- order(rowOrderVec) pvalues <- pvalues[ind] mean.difference <- mean.difference[ind] T <- T[ind] names.ordered <- names.ordered[ind] Rejected1 <- Rejected1[ind] alpha.level <- alpha.level[ind] pv <- 2*pt(-abs(T),df=N-a) comp.matrix <- cbind(mean.difference,T,pv,pvalues,alpha.level,as.numeric(Rejected1)) dimnames(comp.matrix) <- list(names.ordered,c("diff","t","p","p adj","alpha adj","rej H_0")) return(comp.matrix) }
/R/regwqComp.R
no_license
DataScienceUWL/DS705data
R
false
false
4,060
r
regwqComp <- function (formula, data, alpha=.05) { # this is a reworked version of regwq.R from the mutoss package # rounding is removed # output is reordered in a standard order # sqrt(2) factor removed from test statistic (and adjusted elsewhere) # # important - the adjusted p values are compared to the adjusted alphas # it is NOT enough to compare adjusted p to the original alpha # # no guarantees on the procedure itself as that is preserved from mutoss if (missing(data)) { dat <- model.frame(formula) } else { dat <- model.frame(formula, data) } if (ncol(dat) != 2) { stop("Specify one response and only one class variable in the formula") } if (is.numeric(dat[, 1]) == FALSE) { stop("Response variable must be numeric") } response <- dat[, 1] group <- as.factor(dat[, 2]) fl <- levels(group) a <- nlevels(group) N <- length(response) samples <- split(response, group) n <- sapply(samples, "length") mm <- sapply(samples, "mean") vv <- sapply(samples, "var") MSE <- sum((n - 1) * vv)/(N - a) df <- N - a nc <- a * (a - 1)/2 order.h1 <- data.frame(Sample = fl, SampleNum = 1:a, Size = n, Means = mm, Variance = vv) ordered <- order.h1[order(order.h1$Means, decreasing = FALSE), ] rownames(ordered) <- 1:a i <- 1:(a - 1) h1 <- list() for (s in 1:(a - 1)) { h1[[s]] <- i[1:s] } vi <- unlist(h1) j <- a:2 h2 <- list() for (s in 1:(a - 1)) { h2[[s]] <- j[s:1] } vj <- unlist(h2) h3 <- list() h4 <- list() for (s in 1:(a - 1)) { h3[[s]] <- rep(j[s], s) h4[[s]] <- rep(i[s], s) } Nmean <- unlist(h3) Step <- unlist(h4) mean.difference <- sapply(1:nc, function(arg) { i <- vi[arg] j <- vj[arg] (ordered$Means[j] - ordered$Means[i]) }) T <- sapply(1:nc, function(arg) { i <- vi[arg] j <- vj[arg] (ordered$Means[j] - ordered$Means[i])/sqrt(MSE * (1/ordered$Size[i] + 1/ordered$Size[j])) }) pvalues <- ptukey(T*sqrt(2), Nmean, df, lower.tail = FALSE) alpha.level <- 1 - (1 - alpha)^(Nmean/a) level1 <- (Nmean == a) level2 <- (Nmean == a - 1) level3 <- level1 + level2 alpha.level[level3 == 1] <- alpha quantiles <- qtukey(1 - alpha.level, Nmean, df) for (h in 1:(nc - 1)) { if (quantiles[h + 1] >= quantiles[h]) { quantiles[h + 1] <- quantiles[h] } } Rejected1 <- (pvalues < alpha.level) names.ordered <- sapply(1:nc, function(arg) { i <- vi[arg] j <- vj[arg] paste(ordered$Sample[j], "-", ordered$Sample[i], sep = "") }) for (s in 1:nc) { if (Rejected1[s] == FALSE) { Under1 <- (vj[s] >= vj) Under2 <- (vi[s] <= vi) Under3 <- Under1 * Under2 Under4 <- which(Under3 == 1) Rejected1[Under4] <- FALSE } } # add code here to put rows in standard order and flip diff and T if necessary # first build a matrix that will contain the desired row numbers rowOrderMat <- matrix(0,a,a) rowOrderMat[lower.tri(rowOrderMat)]<-1:nc rownames(rowOrderMat) <- fl colnames(rowOrderMat) <- fl rowOrderVec <- numeric(nc) signVec <- rep(1,nc) for (s in 1:nc){ i <- vi[s] j <- vj[s] si <- ordered$SampleNum[i] sj <- ordered$SampleNum[j] if (si<sj){ rowOrderVec[s] <- rowOrderMat[sj,si] } else{ rowOrderVec[s] <- rowOrderMat[si,sj] names.ordered[s] <- paste(ordered$Sample[i], "-", ordered$Sample[j], sep = "") mean.difference[s] <- -mean.difference[s] T[s] <- -T[s] } } ind <- order(rowOrderVec) pvalues <- pvalues[ind] mean.difference <- mean.difference[ind] T <- T[ind] names.ordered <- names.ordered[ind] Rejected1 <- Rejected1[ind] alpha.level <- alpha.level[ind] pv <- 2*pt(-abs(T),df=N-a) comp.matrix <- cbind(mean.difference,T,pv,pvalues,alpha.level,as.numeric(Rejected1)) dimnames(comp.matrix) <- list(names.ordered,c("diff","t","p","p adj","alpha adj","rej H_0")) return(comp.matrix) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/CINNA.R \name{print.visualize.heatmap} \alias{print.visualize.heatmap} \title{Print the heatmap plot of centrality measures} \usage{ \method{print}{visualize.heatmap}(x, scale = TRUE, file = NULL) } \arguments{ \item{x}{a list indicating calculated centrality measures} \item{scale}{Whether the centrality values should be scaled or not(default=TRUE)} \item{file}{A character string naming the .pdf file to print into. If NULL the result would be printed to the exist directory.(default=NULL)} } \value{ The resulted plot of \code{ \link[CINNA]{visualize_heatmap}}function will be saved in the given directory. } \description{ This function prints the heatmap plot } \author{ Minoo Ashtiani, Mohieddin Jafari }
/man/print.visualize.heatmap.Rd
no_license
jafarilab/CINNA
R
false
true
791
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/CINNA.R \name{print.visualize.heatmap} \alias{print.visualize.heatmap} \title{Print the heatmap plot of centrality measures} \usage{ \method{print}{visualize.heatmap}(x, scale = TRUE, file = NULL) } \arguments{ \item{x}{a list indicating calculated centrality measures} \item{scale}{Whether the centrality values should be scaled or not(default=TRUE)} \item{file}{A character string naming the .pdf file to print into. If NULL the result would be printed to the exist directory.(default=NULL)} } \value{ The resulted plot of \code{ \link[CINNA]{visualize_heatmap}}function will be saved in the given directory. } \description{ This function prints the heatmap plot } \author{ Minoo Ashtiani, Mohieddin Jafari }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/methods-SingleBatchModel.R \name{MarginalModelList} \alias{MarginalModelList} \title{Constructor for list of single-batch models} \usage{ MarginalModelList(data = numeric(), k = numeric(), mcmc.params = McmcParams(), ...) } \arguments{ \item{data}{numeric vector of average log R ratios} \item{k}{numeric vector indicating the number of mixture components for each model} \item{mcmc.params}{an object of class \code{McmcParams}} \item{...}{additional arguments passed to \code{Hyperparameters}} } \value{ a list. Each element of the list is a \code{BatchModel} } \description{ An object of class MarginalModel is constructed for each k, creating a list of MarginalModels. } \examples{ mlist <- MarginalModelList(data=y(MarginalModelExample), k=1:4) mcmcParams(mlist) <- McmcParams(iter=1, burnin=1, nStarts=0) mlist2 <- posteriorSimulation(mlist) } \seealso{ \code{\link{MarginalModel}} \code{\link{BatchModelList}} }
/man/MarginalModelList.Rd
no_license
muschellij2/CNPBayes
R
false
true
1,001
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/methods-SingleBatchModel.R \name{MarginalModelList} \alias{MarginalModelList} \title{Constructor for list of single-batch models} \usage{ MarginalModelList(data = numeric(), k = numeric(), mcmc.params = McmcParams(), ...) } \arguments{ \item{data}{numeric vector of average log R ratios} \item{k}{numeric vector indicating the number of mixture components for each model} \item{mcmc.params}{an object of class \code{McmcParams}} \item{...}{additional arguments passed to \code{Hyperparameters}} } \value{ a list. Each element of the list is a \code{BatchModel} } \description{ An object of class MarginalModel is constructed for each k, creating a list of MarginalModels. } \examples{ mlist <- MarginalModelList(data=y(MarginalModelExample), k=1:4) mcmcParams(mlist) <- McmcParams(iter=1, burnin=1, nStarts=0) mlist2 <- posteriorSimulation(mlist) } \seealso{ \code{\link{MarginalModel}} \code{\link{BatchModelList}} }
#' Plots an FFTrees object. #' #' @description Plots an FFTrees object created by the FFTrees() function. #' @param x A FFTrees object created from \code{"FFTrees()"} #' @param data One of two strings 'train' or 'test'. In this case, the corresponding dataset in the x object will be used. #' @param what string. What should be plotted? \code{'tree'} (the default) shows one tree (specified by \code{'tree'}). \code{'cues'} shows the marginal accuracy of cues in an ROC space, \code{"roc"} shows an roc curve of the tree(s) #' @param tree integer. An integer indicating which tree to plot (only valid when the tree argument is non-empty). To plot the best training (or test) tree with respect to the \code{goal} specified during FFT construction, use "best.train" or "best.test" #' @param main character. The main plot label. #' @param hlines logical. Should horizontal panel separation lines be shown? #' @param cue.labels character. An optional string of labels for the cues / nodes. #' @param decision.labels character. A string vector of length 2 indicating the content-specific name for noise and signal cases. #' @param cue.cex numeric. The size of the cue labels. #' @param threshold.cex numeric. The size of the threshold labels. #' @param decision.cex numeric. The size of the decision labels. #' @param comp logical. Should the performance of competitive algorithms (e.g.; logistic regression, random forests etc.) be shown in the ROC plot (if available?) #' @param stats logical. Should statistical information be plotted? If \code{FALSE}, then only the tree (without any reference to statistics) will be plotted. #' @param show.header,show.tree,show.confusion,show.levels,show.roc,show.icons,show.iconguide logical. Logical arguments indicating which specific elements of the plot to show. #' @param label.tree,label.performance string. Optional arguments to define lables for the tree and performance section(s). #' @param n.per.icon Number of cases per icon #' @param which.tree deprecated argument, only for backwards compatibility, use \code{"tree"} instead. #' @param level.type string. How should bottom levels be drawn? Can be \code{"bar"} or \code{"line"} #' @param decision.names deprecated arguments. #' @param ... Currently ignored. #' @importFrom stats anova predict formula model.frame #' @importFrom graphics text points abline legend mtext segments rect arrows axis par layout plot #' @importFrom grDevices gray col2rgb rgb #' @importFrom yarrr transparent piratepal #' @export #' @examples #' #' # Create FFTrees of the heart disease data #' heart.fft <- FFTrees(formula = diagnosis ~., #' data = heartdisease) #' #' # Visualise the tree #' plot(heart.fft, #' main = "Heart Disease Diagnosis", #' decision.labels = c("Absent", "Present")) #' #' #' # See the vignette for more details #' vignette("FFTrees_plot", package = "FFTrees") #' #' #' plot.FFTrees <- function( x = NULL, data = "train", what = 'tree', tree = "best.train", main = NULL, hlines = TRUE, cue.labels = NULL, decision.labels = NULL, cue.cex = NULL, threshold.cex = NULL, decision.cex = 1, comp = TRUE, stats = TRUE, show.header = NULL, show.tree = NULL, show.confusion = NULL, show.levels = NULL, show.roc = NULL, show.icons = NULL, show.iconguide = NULL, label.tree = NULL, label.performance = NULL, n.per.icon = NULL, which.tree = NULL, level.type = "bar", decision.names = NULL, ... ) { # # # # # data = "train" # what = 'tree' # tree = "best.train" # main = NULL # hlines = TRUE # cue.labels = NULL # decision.labels = NULL # cue.cex = NULL # threshold.cex = NULL # decision.cex = 1 # comp = TRUE # stats = TRUE # show.header = NULL # show.tree = NULL # show.confusion = NULL # show.levels = NULL # show.roc = NULL # show.icons = NULL # show.iconguide = NULL # label.tree = NULL # label.performance = NULL # n.per.icon = NULL # which.tree = NULL # level.type = "bar" # decision.names = NULL # Check for invalid or missing arguments # Input validation { if(what %in% c("cues", "tree", "roc") == FALSE) { stop("what must be either 'cues', 'tree', or 'roc'") } if(is.null(decision.names) == FALSE) { message("decision.names is deprecated, use decision.lables instead") decision.labels <- decision.names } } # If what == cues, then send inputs to showcues() if(what == 'cues') {showcues(x = x, data = data, main = main)} if(what != 'cues') { # Determine layout { if(what == "tree") { if(stats == TRUE) { if(is.null(show.header)) {show.header <- TRUE} if(is.null(show.tree)) {show.tree <- TRUE} if(is.null(show.confusion)) {show.confusion <- TRUE} if(is.null(show.levels)) {show.levels <- TRUE} if(is.null(show.roc)) {show.roc <- TRUE} if(is.null(show.icons)) {show.icons <- TRUE} if(is.null(show.iconguide)) {show.iconguide <- TRUE} } if(stats == FALSE) { if(is.null(show.header)) {show.header <- FALSE} if(is.null(show.tree)) {show.tree <- TRUE} if(is.null(show.confusion)) {show.confusion <- FALSE} if(is.null(show.levels)) {show.levels <- FALSE} if(is.null(show.roc)) {show.roc <- FALSE} if(is.null(show.icons)) {show.icons <- FALSE} if(is.null(show.iconguide)) {show.iconguide <- FALSE} } } if(what == "roc") { show.header <- FALSE show.tree <- FALSE show.confusion <- FALSE show.levels <- FALSE show.roc <- TRUE show.icons <- FALSE show.top <- FALSE } # Top, middle, bottom if(show.header & show.tree & (show.confusion | show.levels | show.roc)) { show.top <- TRUE show.middle <- TRUE show.bottom <- TRUE layout(matrix(1:3, nrow = 3, ncol = 1), widths = c(6), heights = c(1.2, 3, 1.8)) } # Top and middle if(show.header & show.tree & (show.confusion == FALSE & show.levels == FALSE & show.roc == FALSE)) { show.top <- TRUE show.middle <- TRUE show.bottom <- FALSE layout(matrix(1:2, nrow = 2, ncol = 1), widths = c(6), heights = c(1.2, 3)) } # Middle and bottom if(show.header == FALSE & show.tree & (show.confusion | show.levels | show.roc)) { show.top <- FALSE show.middle <- TRUE show.bottom <- TRUE layout(matrix(1:2, nrow = 2, ncol = 1), widths = c(6), heights = c(3, 1.8)) } # Middle if(show.header == FALSE & show.tree & (show.confusion == FALSE & show.levels == FALSE & show.roc == FALSE)) { show.top <- FALSE show.middle <- TRUE show.bottom <- FALSE layout(matrix(1:1, nrow = 1, ncol = 1), widths = c(6), heights = c(3)) } # Bottom if(show.header == FALSE & show.tree == FALSE) { show.top <- FALSE show.middle <- FALSE show.bottom <- TRUE nplots <- show.confusion + show.levels + show.roc layout(matrix(1:nplots, nrow = 1, ncol = nplots), widths = c(3 * nplots), heights = c(3)) } } # ------------------------- # Setup data # -------------------------- { # Extract important parameters from x goal <- x$params$goal if(is.null(decision.labels)) { if(("decision.labels" %in% names(x$params))) { decision.labels <- x$params$decision.labels } else {decision.labels <- c(0, 1)} } if(is.null(main)) { if(("main" %in% names(x$params))) { if(is.null(x$params$main)) { if(show.header) { main <- "Data" } else {main <- ""} } else { main <- x$params$main } } else { if(class(data) == "character") { if(data == "train") {main <- "Data (Training)"} if(data == "test") {main <- "Data (Testing)"} } if(class(data) == "data.frame") {main <- "Test Data"} } } # Check for problems and depreciated arguments { if(is.null(which.tree) == FALSE) { message("The which.tree argument is depreciated and is now just called tree. Please use tree from now on to avoid this message.") tree <- which.tree } if(class(x) != "FFTrees") { stop("You did not include a valid FFTrees class object or specify the tree directly with level.names, level.classes (etc.). Either create a valid FFTrees object with FFTrees() or specify the tree directly.") } if(tree == "best.test" & is.null(x$tree.stats$test)) { print("You wanted to plot the best test tree (tree = 'best.test') but there were no test data, I'll plot the best training tree instead") tree <- "best.train" } if(is.numeric(tree) & (tree %in% 1:x$trees$n) == F) { stop(paste("You asked for a tree that does not exist. This object has", x$trees$n, "trees")) } if(class(data) == "character") { if(data == "test" & is.null(x$trees$results$test$stats)) {stop("You asked to plot the test data but there are no test data in the FFTrees object")} } } # DEFINE PLOTTING TREE if(tree == "best.train") { tree <- x$trees$best$train } if(tree == "best.test") { tree <- x$trees$best$test } # DEFINE CRITICAL OBJECTS lr.stats <- NULL cart.stats <- NULL rf.stats <- NULL svm.stats <- NULL decision.v <- x$trees$results[[data]]$decisions[,tree] tree.stats <- x$trees$results[[data]]$stats level.stats <- x$trees$results[[data]]$level_stats[x$trees$results[[data]]$level_stats$tree == tree,] if(comp == TRUE) { if(is.null(x$comp$lr$results) == FALSE) { lr.stats <- data.frame("sens" = x$comp$lr$results[[data]]$sens, "spec" = x$comp$lr$results[[data]]$spec) } if(is.null(x$comp$cart$results) == FALSE) { lcart.stats <- data.frame("sens" = x$comp$cart$results[[data]]$sens, "spec" = x$comp$cart$results[[data]]$spec) } if(is.null(x$comp$rf$results) == FALSE) { rf.stats <- data.frame("sens" = x$comp$rf$results[[data]]$sens, "spec" = x$comp$rf$results[[data]]$spec) } if(is.null(x$comp$svm$results) == FALSE) { svm.stats <- data.frame("sens" = x$comp$svm$results[[data]]$sens, "spec" = x$comp$svm$results[[data]]$spec) } } n.exemplars <- nrow(x$data[[data]]) n.pos <- sum(x$data[[data]][[x$metadata$criterion_name]]) n.neg <- sum(x$data[[data]][[x$metadata$criterion_name]] == FALSE) mcu <- x$trees$results[[data]]$stats$mcu[tree] crit.br <- mean(x$data[[data]][[x$metadata$criterion_name]]) final.stats <- tree.stats[tree,] # ADD LEVEL STATISTICS n.levels <- nrow(level.stats) # Add marginal classification statistics to level.stats level.stats[c("hi.m", "mi.m", "fa.m", "cr.m")] <- NA for(i in 1:n.levels) { if(i == 1) { level.stats[1, c("hi.m", "mi.m", "fa.m", "cr.m")] <- level.stats[1, c("hi", "mi", "fa", "cr")] } if(i > 1) { level.stats[i, c("hi.m", "mi.m", "fa.m", "cr.m")] <- level.stats[i, c("hi", "mi", "fa", "cr")] - level.stats[i - 1, c("hi", "mi", "fa", "cr")] } } } # ------------------------- # Define plotting parameters # -------------------------- { { # Panels panel.line.lwd <- 1 panel.line.col <- gray(0) panel.line.lty <- 1 # Some general parameters ball.col = c(gray(0), gray(0)) ball.bg = c(gray(1), gray(1)) ball.pch = c(21, 24) ball.cex = c(1, 1) error.col <- "red" correct.col <- "green" max.label.length <- 100 def.par <- par(no.readonly = TRUE) ball.box.width <- 10 label.box.height <- 2 label.box.width <- 5 # Define cue labels { if(is.null(cue.labels)) { cue.labels <- level.stats$cue } # Trim labels cue.labels <- strtrim(cue.labels, max.label.length) } # Node Segments segment.lty <- 1 segment.lwd <- 1 continue.segment.lwd <- 1 continue.segment.lty <- 1 exit.segment.lwd <- 1 exit.segment.lty <- 1 decision.node.cex <- 4 exit.node.cex <- 4 panel.title.cex <- 2 # Classification table classtable.lwd <- 1 # ROC roc.lwd <- 1 roc.border.col <- gray(0) # Label sizes { # Set cue label size if(is.null(cue.cex)) { cue.cex <- c(1.5, 1.5, 1.25, 1, 1, 1) } else { if(length(cue.cex) < 6) {cue.cex <- rep(cue.cex, length.out = 6)} } # Set break label size if(is.null(threshold.cex)) { threshold.cex <- c(1.5, 1.5, 1.25, 1, 1, 1) } else { if(length(threshold.cex) < 6) {threshold.cex <- rep(threshold.cex, length.out = 6)} } } if(show.top & show.middle & show.bottom) { plotting.parameters.df <- data.frame( n.levels = 1:6, plot.height = c(10, 12, 15, 19, 23, 27), plot.width = c(14, 16, 20, 24, 28, 34), label.box.text.cex = cue.cex, break.label.cex = threshold.cex ) } else if (show.top == FALSE & show.middle & show.bottom == FALSE) { plotting.parameters.df <- data.frame( n.levels = 1:6, plot.height = c(10, 12, 15, 19, 23, 25), plot.width = c(14, 16, 20, 24, 28, 32) * 1, label.box.text.cex = cue.cex, break.label.cex = threshold.cex ) } else { plotting.parameters.df <- data.frame( n.levels = 1:6, plot.height = c(10, 12, 15, 19, 23, 25), plot.width = c(14, 16, 20, 24, 28, 32) * 1, label.box.text.cex = cue.cex, break.label.cex = threshold.cex ) } if(n.levels < 6) { label.box.text.cex <- plotting.parameters.df$label.box.text.cex[n.levels] break.label.cex <- plotting.parameters.df$break.label.cex[n.levels] plot.height <- plotting.parameters.df$plot.height[n.levels] plot.width <- plotting.parameters.df$plot.width[n.levels] } if(n.levels >= 6) { label.box.text.cex <- plotting.parameters.df$label.box.text.cex[6] break.label.cex <- plotting.parameters.df$break.label.cex[6] plot.height <- plotting.parameters.df$plot.height[6] plot.width <- plotting.parameters.df$plot.width[6] } # Colors exit.node.bg <- "white" error.colfun <- circlize::colorRamp2(c(0, 50, 100), colors = c("white", "red", "black")) correct.colfun <- circlize::colorRamp2(c(0, 50, 100), colors = c("white", "green", "black")) error.bg <- yarrr::transparent(error.colfun(35), .2) error.border <- yarrr::transparent(error.colfun(65), .1) correct.bg <- yarrr::transparent(correct.colfun(35), .2) correct.border <- yarrr::transparent(correct.colfun(65), .1) max.cex <- 6 min.cex <- 1 exit.node.pch <- 21 decision.node.pch <- NA_integer_ # balls ball.loc <- "variable" if(n.levels == 3) {ball.box.width <- 14} if(n.levels == 4) {ball.box.width <- 18} ball.box.height <- 2.5 ball.box.horiz.shift <- 10 ball.box.vert.shift <- -1 ball.box.max.shift.p <- .9 ball.box.min.shift.p <- .4 ball.box.fixed.x.shift <- c(ball.box.min.shift.p * plot.width, ball.box.max.shift.p * plot.width) # Determine N per ball if(is.null(n.per.icon)) { max.n.side <- max(c(n.pos, n.neg)) i <- max.n.side / c(1, 5, 10^(1:10)) i[i > 50] <- 0 n.per.icon <- c(1, 5, 10^(1:10))[which(i == max(i))] } noise.ball.pch <- ball.pch[1] signal.ball.pch <- ball.pch[2] noise.ball.col <- ball.col[1] signal.ball.col <- ball.col[2] noise.ball.bg <- ball.bg[1] signal.ball.bg <- ball.bg[2] # arrows arrow.lty <- 1 arrow.lwd <- 1 arrow.length <- 2.5 arrow.head.length <- .08 arrow.col <- gray(0) # Final stats spec.circle.x <- .4 dprime.circle.x <- .5 sens.circle.x <- .6 stat.circle.y <- .3 sens.circle.col <- "green" spec.circle.col <- "red" dprime.circle.col <- "blue" stat.outer.circle.col <- gray(.5) } # add.balls.fun() adds balls to the plot add.balls.fun <- function(x.lim = c(-10, 0), y.lim = c(-2, 0), n.vec = c(20, 10), pch.vec = c(21, 21), ball.cex = 1, bg.vec = ball.bg, col.vec = ball.col, ball.lwd = .7, freq.text = TRUE, freq.text.cex = 1.2, upper.text = "", upper.text.cex = 1, upper.text.adj = 0, rev.order = F, box.col = NULL, box.bg = NULL, n.per.icon = NULL ) { # Add box if(is.null(box.col) == FALSE | is.null(box.bg) == FALSE) { rect(x.lim[1], y.lim[1], x.lim[2], y.lim[2], col = box.bg, border = box.col) } # add upper text text(mean(x.lim), y.lim[2] + upper.text.adj, label = upper.text, cex = upper.text.cex ) a.n <- n.vec[1] b.n <- n.vec[2] a.p <- n.vec[1] / sum(n.vec) box.x.center <- sum(x.lim) / 2 box.y.center <- sum(y.lim) / 2 box.x.width <- x.lim[2] - x.lim[1] # Determine cases per ball if(is.null(n.per.icon)) { max.n.side <- max(c(a.n, b.n)) i <- max.n.side / c(1, 5, 10, 50, 100, 1000, 10000) i[i > 50] <- 0 n.per.icon <- c(1, 5, 10, 50, 100, 1000, 10000)[which(i == max(i))] } # Determine general ball locations a.balls <- ceiling(a.n / n.per.icon) b.balls <- ceiling(b.n / n.per.icon) n.balls <- a.balls + b.balls a.ball.x.loc <- 0 a.ball.y.loc <- 0 b.ball.x.loc <- 0 b.ball.y.loc <- 0 if(a.balls > 0) { a.ball.x.loc <- rep(-1:-10, each = 5, length.out = 50)[1:a.balls] a.ball.y.loc <- rep(1:5, times = 10, length.out = 50)[1:a.balls] a.ball.x.loc <- a.ball.x.loc * (x.lim[2] - box.x.center) / 10 + box.x.center a.ball.y.loc <- a.ball.y.loc * (y.lim[2] - y.lim[1]) / 5 + y.lim[1] } if(b.balls > 0) { b.ball.x.loc <- rep(1:10, each = 5, length.out = 50)[1:b.balls] b.ball.y.loc <- rep(1:5, times = 10, length.out = 50)[1:b.balls] b.ball.x.loc <- b.ball.x.loc * (x.lim[2] - box.x.center) / 10 + box.x.center b.ball.y.loc <- b.ball.y.loc * (y.lim[2] - y.lim[1]) / 5 + y.lim[1] } # if(rev.order) { # # x <- b.ball.x.loc # y <- b.ball.y.loc # # b.ball.x.loc <- a.x.loc # b.ball.y.loc <- a.y.loc # # a.ball.x.loc <- x # a.ball.y.loc <- y # # } # Add frequency text if(freq.text) { text(box.x.center, y.lim[1] - 1 * (y.lim[2] - y.lim[1]) / 5, prettyNum(b.n, big.mark = ","), pos = 4, cex = freq.text.cex) text(box.x.center, y.lim[1] - 1 * (y.lim[2] - y.lim[1]) / 5, prettyNum(a.n, big.mark = ","), pos = 2, cex = freq.text.cex) } # Draw balls # Noise suppressWarnings(if(a.balls > 0) { points(x = a.ball.x.loc, y = a.ball.y.loc, pch = pch.vec[1], bg = bg.vec[1], col = col.vec[1], cex = ball.cex, lwd = ball.lwd) } ) # Signal suppressWarnings(if(b.balls > 0) { points(x = b.ball.x.loc, y = b.ball.y.loc, pch = pch.vec[2], bg = bg.vec[2], col = col.vec[2], cex = ball.cex, lwd = ball.lwd ) } ) } label.cex.fun <- function(i, label.box.text.cex = 2) { i <- nchar(i) label.box.text.cex * i ^ -.25 } } # ------------------------- # 1: Initial Frequencies # -------------------------- if(show.top) { par(mar = c(0, 0, 1, 0)) plot(1, xlim = c(0, 1), ylim = c(0, 1), bty = "n", type = "n", xlab = "", ylab = "", yaxt = "n", xaxt = "n") if(hlines) { segments(0, .95, 1, .95, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) } rect(.33, .8, .67, 1.2, col = "white", border = NA) text(x = .5, y = .95, main, cex = panel.title.cex) text(x = .5, y = .80, paste("N = ", prettyNum(n.exemplars, big.mark = ","), "", sep = ""), cex = 1.25) n.trueneg <- with(final.stats, cr + fa) n.truepos <- with(final.stats, hi + mi) text(.5, .65, paste(decision.labels[1], sep = ""), pos = 2, cex = 1.2, adj = 1) text(.5, .65, paste(decision.labels[2], sep = ""), pos = 4, cex = 1.2, adj = 0) #points(.9, .8, pch = 1, cex = 1.2) #text(.9, .8, labels = paste(" = ", n.per.icon, " cases", sep = ""), pos = 4) # Show ball examples par(xpd = T) add.balls.fun(x.lim = c(.35, .65), y.lim = c(.1, .5), n.vec = c(final.stats$fa + final.stats$cr, final.stats$hi + final.stats$mi), pch.vec = c(noise.ball.pch, signal.ball.pch), bg.vec = c(noise.ball.bg, signal.ball.bg), col.vec = c(noise.ball.col, signal.ball.col), ball.cex = ball.cex, upper.text.adj = 2, n.per.icon = n.per.icon ) par(xpd = F) # Add p.signal and p.noise levels signal.p <- mean(x$data[[data]][[x$metadata$criterion_name]]) noise.p <- 1 - signal.p p.rect.ylim <- c(.1, .6) # p.signal level text(x = .8, y = p.rect.ylim[2], labels = paste("p(", decision.labels[2], ")", sep = ""), pos = 3, cex = 1.2) #Filling rect(.775, p.rect.ylim[1], .825, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), col = gray(.5, .25), border = NA) # Filltop segments(.775, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), .825, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), lwd = 1) #Outline rect(.775, p.rect.ylim[1], .825, p.rect.ylim[2], lwd = 1) if(signal.p < .0001) {signal.p.text <- "<1%"} else { signal.p.text <- paste(round(signal.p * 100, 0), "%", sep = "") } text(.825, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), labels = signal.p.text, pos = 4, cex = 1.2) #p.noise level text(x = .2, y = p.rect.ylim[2], labels = paste("p(", decision.labels[1], ")", sep = ""), pos = 3, cex = 1.2) rect(.175, p.rect.ylim[1], .225, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), col = gray(.5, .25), border = NA) # Filltop segments(.175, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), .225, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), lwd = 1) # outline rect(.175, p.rect.ylim[1], .225, p.rect.ylim[2], lwd = 1) if(noise.p < .0001) {noise.p.text <- "<0.01%"} else { noise.p.text <- paste(round(noise.p * 100, 0), "%", sep = "") } text(.175, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), labels = noise.p.text, pos = 2, cex = 1.2) } # ------------------------- # 2. TREE # -------------------------- if(show.middle) { if(show.top == FALSE & show.bottom == FALSE) { par(mar = c(3, 3, 3, 3) + .1) } else {par(mar = c(0, 0, 0, 0)) } # Setup plotting space plot(1, xlim = c(-plot.width, plot.width), ylim = c(-plot.height, 0), type = "n", bty = "n", xaxt = "n", yaxt = "n", ylab = "", xlab = "" ) # Add frame par(xpd = TRUE) if(show.top | show.bottom) { if(hlines) { segments(-plot.width, 0, - plot.width * .3, 0, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) segments(plot.width, 0, plot.width * .3, 0, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) } if(is.null(label.tree)) {label.tree <- paste("FFT #", tree, " (of ", x$trees$n, ")", sep = "")} text(x = 0, y = 0, label.tree, cex = panel.title.cex) } if(show.top == FALSE & show.bottom == FALSE) { if(is.null(main) & is.null(x$params$main)) {main <- ""} mtext(text = main, side = 3, cex = 2) } par(xpd = FALSE) # Create Noise and Signal panels if(show.iconguide) { # Noise Balls points(c(- plot.width * .7, - plot.width * .5), c(-plot.height * .125, -plot.height * .125), pch = c(noise.ball.pch, signal.ball.pch), bg = c(correct.bg, error.bg), col = c(correct.border, error.border), cex = ball.cex * 1.5 ) text(c(- plot.width * .7, - plot.width * .5), c(-plot.height * .125, -plot.height * .125), labels = c("Correct\nRejection", "Miss"), pos = c(2, 4), offset = 1) # Noise Panel text(- plot.width * .6, -plot.height * .05, paste("Decide ", decision.labels[1], sep = ""), cex = 1.2, font = 3 ) # Signal panel text(plot.width * .6, -plot.height * .05, paste("Decide ", decision.labels[2], sep = ""), cex = 1.2, font = 3 ) points(c(plot.width * .5, plot.width * .7), c(-plot.height * .125, -plot.height * .125), pch = c(noise.ball.pch, signal.ball.pch), bg = c(error.bg, correct.bg), col = c(error.border, correct.border), cex = ball.cex * 1.5 ) text(c(plot.width * .5, plot.width * .7), c(-plot.height * .125, -plot.height * .125), labels = c("False\nAlarm", "Hit"), pos = c(2, 4), offset = 1) } # Set initial subplot center subplot.center <- c(0, -4) # Loop over levels for(level.i in 1:min(c(n.levels, 6))) { current.cue <- cue.labels[level.i] # Get stats for current level { hi.i <- level.stats$hi.m[level.i] mi.i <- level.stats$mi.m[level.i] fa.i <- level.stats$fa.m[level.i] cr.i <- level.stats$cr.m[level.i] } # If level.i == 1, draw top textbox { if(level.i == 1) { rect(subplot.center[1] - label.box.width / 2, subplot.center[2] + 2 - label.box.height / 2, subplot.center[1] + label.box.width / 2, subplot.center[2] + 2 + label.box.height / 2, col = "white", border = "black" ) points(x = subplot.center[1], y = subplot.center[2] + 2, cex = decision.node.cex, pch = decision.node.pch ) text(x = subplot.center[1], y = subplot.center[2] + 2, labels = current.cue, cex = label.box.text.cex#label.cex.fun(current.cue, label.box.text.cex = label.box.text.cex) ) } } # ----------------------- # Left (Noise) Classification / New Level # ----------------------- { # Exit node on left if(level.stats$exit[level.i] %in% c(0, .5) | paste(level.stats$exit[level.i]) %in% c("0", ".5")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] - 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) arrows(x0 = subplot.center[1] - 2, y0 = subplot.center[2] - 2, x1 = subplot.center[1] - 2 - arrow.length, y1 = subplot.center[2] - 2, lty = arrow.lty, lwd = arrow.lwd, col = arrow.col, length = arrow.head.length ) # Decision text if(decision.cex > 0) { text(x = subplot.center[1] - 2 - arrow.length * .7, y = subplot.center[2] - 2.2, labels = decision.labels[1], pos = 1, font = 3, cex = decision.cex) } if(ball.loc == "fixed") { ball.x.lim <- c(-max(ball.box.fixed.x.shift), -min(ball.box.fixed.x.shift)) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(ball.loc == "variable") { ball.x.lim <- c(subplot.center[1] - ball.box.horiz.shift - ball.box.width / 2, subplot.center[1] - ball.box.horiz.shift + ball.box.width / 2) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(max(c(cr.i, mi.i), na.rm = TRUE) > 0 & show.icons == TRUE) { add.balls.fun(x.lim = ball.x.lim, y.lim = ball.y.lim, n.vec = c(cr.i, mi.i), pch.vec = c(noise.ball.pch, signal.ball.pch), # bg.vec = c(noise.ball.bg, signal.ball.bg), bg.vec = c(correct.bg, error.bg), col.vec = c(correct.border, error.border), freq.text = TRUE, n.per.icon = n.per.icon, ball.cex = ball.cex ) } # level break label pos.direction.symbol <- c("<=", "<", "=", "!=", ">", ">=")[which(level.stats$direction[level.i] == c(">", ">=", "!=", "=", "<=", "<"))] neg.direction.symbol <- c("<=", "<", "=", "!=", ">", ">=")[which(level.stats$direction[level.i] == c("<=", "<", "=", "!=", ">", ">="))] text.outline(x = subplot.center[1] - 1, y = subplot.center[2], labels = paste(pos.direction.symbol, " ", level.stats$threshold[level.i], sep = ""), pos = 2, cex = break.label.cex, r = .1 ) points(x = subplot.center[1] - 2, y = subplot.center[2] - 2, pch = exit.node.pch, cex = exit.node.cex, bg = exit.node.bg ) text(x = subplot.center[1] - 2, y = subplot.center[2] - 2, labels = substr(decision.labels[1], 1, 1) ) } # New level on left if(level.stats$exit[level.i] %in% c(1) | paste(level.stats$exit[level.i]) %in% c("1")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] - 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) rect(subplot.center[1] - 2 - label.box.width / 2, subplot.center[2] - 2 - label.box.height / 2, subplot.center[1] - 2 + label.box.width / 2, subplot.center[2] - 2 + label.box.height / 2, col = "white", border = "black" ) if(level.i < 6) {text(x = subplot.center[1] - 2, y = subplot.center[2] - 2, labels = cue.labels[level.i + 1], cex = label.box.text.cex )} else { text(x = subplot.center[1] - 2, y = subplot.center[2] - 2, labels = paste0("+ ", n.levels - 6, " More"), cex = label.box.text.cex, font = 3 ) } } } # ----------------------- # Right (Signal) Classification / New Level # ----------------------- { # Exit node on right if(level.stats$exit[level.i] %in% c(1, .5) | paste(level.stats$exit[level.i]) %in% c("1", ".5")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] + 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) arrows(x0 = subplot.center[1] + 2, y0 = subplot.center[2] - 2, x1 = subplot.center[1] + 2 + arrow.length, y1 = subplot.center[2] - 2, lty = arrow.lty, lwd = arrow.lwd, col = arrow.col, length = arrow.head.length ) # Decision text if(decision.cex > 0) { text(x = subplot.center[1] + 2 + arrow.length * .7, y = subplot.center[2] - 2.2, labels = decision.labels[2], pos = 1, font = 3, cex = decision.cex) } if(ball.loc == "fixed") { ball.x.lim <- c(min(ball.box.fixed.x.shift), max(ball.box.fixed.x.shift)) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(ball.loc == "variable") { ball.x.lim <- c(subplot.center[1] + ball.box.horiz.shift - ball.box.width / 2, subplot.center[1] + ball.box.horiz.shift + ball.box.width / 2) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(max(c(fa.i, hi.i), na.rm = TRUE) > 0 & show.icons == TRUE) { add.balls.fun(x.lim = ball.x.lim, y.lim = ball.y.lim, n.vec = c(fa.i, hi.i), pch.vec = c(noise.ball.pch, signal.ball.pch), # bg.vec = c(noise.ball.bg, signal.ball.bg), bg.vec = c(error.bg, correct.bg), col.vec = c(error.border, correct.border), freq.text = TRUE, n.per.icon = n.per.icon, ball.cex = ball.cex ) } # level break label dir.symbols <- c("<=", "<", "=", "!=", ">", ">=") pos.direction.symbol <- dir.symbols[which(level.stats$direction[level.i] == c("<=", "<", "=", "!=", ">", ">="))] neg.direction.symbol <- dir.symbols[which(level.stats$direction[level.i] == rev(c("<=", "<", "=", "!=", ">", ">=")))] text.outline(subplot.center[1] + 1, subplot.center[2], labels = paste(pos.direction.symbol, " ", level.stats$threshold[level.i], sep = ""), pos = 4, cex = break.label.cex, r = .1 ) points(x = subplot.center[1] + 2, y = subplot.center[2] - 2, pch = exit.node.pch, cex = exit.node.cex, bg = exit.node.bg ) text(x = subplot.center[1] + 2, y = subplot.center[2] - 2, labels = substr(decision.labels[2], 1, 1) ) } # New level on right if(level.stats$exit[level.i] %in% 0 | paste(level.stats$exit[level.i]) %in% c("0")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] + 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) if(level.i < 6) { rect(subplot.center[1] + 2 - label.box.width / 2, subplot.center[2] - 2 - label.box.height / 2, subplot.center[1] + 2 + label.box.width / 2, subplot.center[2] - 2 + label.box.height / 2, col = "white", border = "black") text(x = subplot.center[1] + 2, y = subplot.center[2] - 2, labels = cue.labels[level.i + 1], cex = label.box.text.cex) } else { rect(subplot.center[1] + 2 - label.box.width / 2, subplot.center[2] - 2 - label.box.height / 2, subplot.center[1] + 2 + label.box.width / 2, subplot.center[2] - 2 + label.box.height / 2, col = "white", border = "black", lty = 2) text(x = subplot.center[1] + 2, y = subplot.center[2] - 2, labels = paste0("+ ", n.levels - 6, " More"), cex = label.box.text.cex, font = 3 ) } } } # ----------------------- # Update plot center # ----------------------- { if(level.stats$exit[level.i] == 0) { subplot.center <- c(subplot.center[1] + 2, subplot.center[2] - 4) } if(level.stats$exit[level.i] == 1) { subplot.center <- c(subplot.center[1] - 2, subplot.center[2] - 4) } } } } # ----------------------- # 3. CUMULATIVE PERFORMANCE # ----------------------- if(show.bottom == TRUE) { { # OBTAIN FINAL STATISTICS fft.sens.vec <- tree.stats$sens fft.spec.vec <- tree.stats$spec # General plotting space { # PLOTTING PARAMETERS header.y.loc <- 1.0 subheader.y.loc <- .925 header.cex <- 1.1 subheader.cex <- .9 par(mar = c(0, 0, 2, 0)) plot(1, xlim = c(0, 1), ylim = c(0, 1), bty = "n", type = "n", xlab = "", ylab = "", yaxt = "n", xaxt = "n") par(xpd = T) if(hlines) { segments(0, 1.1, 1, 1.1, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) rect(.25, 1, .75, 1.2, col = "white", border = NA) } if(is.null(label.performance)) { if(data == "train") {label.performance <- "Accuracy (Training)"} if(data == "test") {label.performance <- "Accuracy (Testing)"} } text(.5, 1.1, label.performance, cex = panel.title.cex) par(xpd = FALSE) pretty.dec <- function(x) {return(paste(round(x, 2) * 100, sep = ""))} level.max.height <- .65 level.width <- .05 level.center.y <- .45 #level.bottom <- .1 level.bottom <- level.center.y - level.max.height / 2 level.top <- level.center.y + level.max.height / 2 lloc <- data.frame( element = c("classtable", "mcu", "pci", "sens", "spec", "acc", "bacc", "roc"), long.name = c("Classification Table", "mcu", "pci", "sens", "spec", "acc", "bacc", "ROC"), center.x = c(.18, seq(.35, .65, length.out = 6), .85), center.y = rep(level.center.y, 8), width = c(.2, rep(level.width, 6), .2), height = c(.65, rep(level.max.height, 6), .65), value = c(NA, abs(final.stats$mcu - 5) / (abs(1 - 5)), final.stats$pci, final.stats$sens, final.stats$spec, with(final.stats, (cr + hi) / n), final.stats$bacc, NA), value.name = c(NA, round(final.stats$mcu, 1), pretty.dec(final.stats$pci), pretty.dec(final.stats$sens), pretty.dec(final.stats$spec), pretty.dec(final.stats$acc), pretty.dec(final.stats$bacc), NA ) ) } # Classification table if(show.confusion) { final.classtable.x.loc <- c(lloc$center.x[lloc$element == "classtable"] - lloc$width[lloc$element == "classtable"] / 2, lloc$center.x[lloc$element == "classtable"] + lloc$width[lloc$element == "classtable"] / 2) final.classtable.y.loc <- c(lloc$center.y[lloc$element == "classtable"] - lloc$height[lloc$element == "classtable"] / 2, lloc$center.y[lloc$element == "classtable"] + lloc$height[lloc$element == "classtable"] / 2) rect(final.classtable.x.loc[1], final.classtable.y.loc[1], final.classtable.x.loc[2], final.classtable.y.loc[2], lwd = classtable.lwd ) segments(mean(final.classtable.x.loc), final.classtable.y.loc[1], mean(final.classtable.x.loc), final.classtable.y.loc[2], col = gray(0), lwd = classtable.lwd) segments(final.classtable.x.loc[1], mean(final.classtable.y.loc), final.classtable.x.loc[2], mean(final.classtable.y.loc), col = gray(0), lwd = classtable.lwd) # Column titles text(x = mean(mean(final.classtable.x.loc)), y = header.y.loc, "Truth", pos = 1, cex = header.cex) text(x = final.classtable.x.loc[1] + .25 * diff(final.classtable.x.loc), y = subheader.y.loc, pos = 1, cex = subheader.cex, decision.labels[2]) text(x = final.classtable.x.loc[1] + .75 * diff(final.classtable.x.loc), y = subheader.y.loc, pos = 1, cex = subheader.cex, decision.labels[1]) # Row titles text(x = final.classtable.x.loc[1] - .01, y = final.classtable.y.loc[1] + .75 * diff(final.classtable.y.loc), cex = subheader.cex, decision.labels[2], adj = 1) text(x = final.classtable.x.loc[1] - .01, y = final.classtable.y.loc[1] + .25 * diff(final.classtable.y.loc), cex = subheader.cex, decision.labels[1], adj = 1) text(x = final.classtable.x.loc[1] - .065, y = mean(final.classtable.y.loc), cex = header.cex, "Decision") # text(x = final.classtable.x.loc[1] - .05, # y = mean(final.classtable.y.loc), cex = header.cex, # "Decision", srt = 90, pos = 3) # Add final frequencies text(final.classtable.x.loc[1] + .75 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .25 * diff(final.classtable.y.loc), prettyNum(final.stats$cr, big.mark = ","), cex = 1.5) text(final.classtable.x.loc[1] + .25 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .25 * diff(final.classtable.y.loc), prettyNum(final.stats$mi, big.mark = ","), cex = 1.5) text(final.classtable.x.loc[1] + .75 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .75 * diff(final.classtable.y.loc), prettyNum(final.stats$fa, big.mark = ","), cex = 1.5) text(final.classtable.x.loc[1] + .25 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .75 * diff(final.classtable.y.loc), prettyNum(final.stats$hi, big.mark = ","), cex = 1.5) # Add symbols points(final.classtable.x.loc[1] + .55 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .05 * diff(final.classtable.y.loc), pch = noise.ball.pch, bg = correct.bg, col = correct.border, cex = ball.cex) points(final.classtable.x.loc[1] + .05 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .55 * diff(final.classtable.y.loc), pch = signal.ball.pch, bg = correct.bg, cex = ball.cex, col = correct.border) points(final.classtable.x.loc[1] + .55 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .55 * diff(final.classtable.y.loc), pch = noise.ball.pch, bg = error.bg, col = error.border, cex = ball.cex) points(final.classtable.x.loc[1] + .05 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .05 * diff(final.classtable.y.loc), pch = signal.ball.pch, bg = error.bg, col = error.border, cex = ball.cex) # Labels text(final.classtable.x.loc[1] + .62 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .07 * diff(final.classtable.y.loc), "cr", cex = 1, font = 3, adj = 0) text(final.classtable.x.loc[1] + .12 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .07 * diff(final.classtable.y.loc), "mi", cex = 1, font = 3, adj = 0) text(final.classtable.x.loc[1] + .62 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .57 * diff(final.classtable.y.loc), "fa", cex = 1, font = 3, adj = 0) text(final.classtable.x.loc[1] + .12 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .57 * diff(final.classtable.y.loc), "hi", cex = 1, font = 3, adj = 0) } # Levels if(show.levels) { if(level.type %in% c("line", "bar")) { # Color function (taken from colorRamp2 function in circlize package) col.fun <- circlize::colorRamp2(c(0, .75, 1), c("red", "yellow", "green"), transparency = .1) add.level.fun <- function(name, sub = "", max.val = 1, min.val = 0, ok.val = .5, bottom.text = "", level.type = "line") { rect.center.x <- lloc$center.x[lloc$element == name] rect.center.y <- lloc$center.y[lloc$element == name] rect.height <- lloc$height[lloc$element == name] rect.width <- lloc$width[lloc$element == name] rect.bottom.y <- rect.center.y - rect.height / 2 rect.top.y <- rect.center.y + rect.height / 2 rect.left.x <- rect.center.x - rect.width / 2 rect.right.x <- rect.center.x + rect.width / 2 long.name <- lloc$long.name[lloc$element == name] value <- lloc$value[lloc$element == name] value.name <- lloc$value.name[lloc$element == name] # # level.col.fun <- circlize::colorRamp2(c(min.val, ok.val, max.val), # colors = c("firebrick2", "yellow", "green4"), # transparency = .1) text(x = rect.center.x, y = header.y.loc, labels = long.name, pos = 1, cex = header.cex) # # text.outline(x = rect.center.x, # y = header.y.loc, # labels = long.name, # pos = 1, cex = header.cex, r = .02 # ) value.height <- rect.bottom.y + min(c(1, ((value - min.val) / (max.val - min.val)))) * rect.height # Add filling value.s <- min(value / max.val, 1) delta <- 1 gamma <- .5 value.col.scale <- delta * value.s ^ gamma / (delta * value.s ^ gamma + (1 - value.s) ^ gamma) # value.col <- gray(1 - value.col.scale * .5) value.col <- gray(1, .25) #plot(seq(0, 1, .01), delta * seq(0, 1, .01) ^ gamma / (delta * seq(0, 1, .01) ^ gamma + (1 - seq(0, 1, .01)) ^ gamma)) if(level.type == "bar") { rect(rect.left.x, rect.bottom.y, rect.right.x, value.height, #col = level.col.fun(value.s), col = value.col, # col = spec.level.fun(lloc$value[lloc$element == name]), border = "black" ) text.outline(x = rect.center.x, y = value.height, labels = lloc$value.name[lloc$element == name], cex = 1.5, r = .008, pos = 3 ) # Add level border # rect(rect.left.x, # rect.bottom.y, # rect.right.x, # rect.top.y, # border = gray(.5, .5)) } if(level.type == "line") { # Stem segments(rect.center.x, rect.bottom.y, rect.center.x, value.height, lty = 3) # Horizontal platform platform.width <- .02 segments(rect.center.x - platform.width, value.height, rect.center.x + platform.width, value.height) # Text label text.outline(x = rect.center.x, y = value.height, labels = lloc$value.name[lloc$element == name], cex = 1.5, r = 0, pos = 3 ) # points(rect.center.x, # value.height, # cex = 5.5, # pch = 21, # bg = "white", # col = "black", lwd = .5) } # Add subtext text(x = rect.center.x, y = rect.center.y - .05, labels = sub, cex = .8, font = 1, pos = 1) # Add bottom text text(x = rect.center.x, y = rect.bottom.y, labels = bottom.text, pos = 1) } paste(final.stats$cr, "/", 1, collapse = "") #Add 100% reference line # segments(x0 = lloc$center.x[lloc$element == "mcu"] - lloc$width[lloc$element == "mcu"] * .8, # y0 = level.top, # x1 = lloc$center.x[lloc$element == "bacc"] + lloc$width[lloc$element == "bacc"] * .8, # y1 = level.top, # lty = 3, lwd = .75) add.level.fun("mcu", ok.val = .75, max.val = 1, min.val = 0, level.type = level.type) #, sub = paste(c(final.stats$cr, "/", final.stats$cr + final.stats$fa), collapse = "")) add.level.fun("pci", ok.val = .75, level.type = level.type) #, sub = paste(c(final.stats$cr, "/", final.stats$cr + final.stats$fa), collapse = "")) # text(lloc$center.x[lloc$element == "pci"], # lloc$center.y[lloc$element == "pci"], # labels = paste0("mcu\n", round(mcu, 2))) add.level.fun("spec", ok.val = .75, level.type = level.type) #, sub = paste(c(final.stats$cr, "/", final.stats$cr + final.stats$fa), collapse = "")) add.level.fun("sens", ok.val = .75, level.type = level.type) #, sub = paste(c(final.stats$hi, "/", final.stats$hi + final.stats$mi), collapse = "")) # Min acc min.acc <- max(crit.br, 1 - crit.br) add.level.fun("acc", min.val = 0, ok.val = .5, level.type = level.type) #, sub = paste(c(final.stats$hi + final.stats$cr, "/", final.stats$n), collapse = "")) # Add baseline to acc level segments(x0 = lloc$center.x[lloc$element == "acc"] - lloc$width[lloc$element == "acc"] / 2, y0 = (lloc$center.y[lloc$element == "acc"] - lloc$height[lloc$element == "acc"] / 2) + lloc$height[lloc$element == "acc"] * min.acc, x1 = lloc$center.x[lloc$element == "acc"] + lloc$width[lloc$element == "acc"] / 2, y1 = (lloc$center.y[lloc$element == "acc"] - lloc$height[lloc$element == "acc"] / 2) + lloc$height[lloc$element == "acc"] * min.acc, lty = 3) text(x = lloc$center.x[lloc$element == "acc"], y =(lloc$center.y[lloc$element == "acc"] - lloc$height[lloc$element == "acc"] / 2) + lloc$height[lloc$element == "acc"] * min.acc, labels = "BL", pos = 1) # paste("BL = ", pretty.dec(min.acc), sep = ""), pos = 1) add.level.fun("bacc", min.val = 0, max.val = 1, ok.val = .5, level.type = level.type) # baseline # segments(x0 = mean(lloc$center.x[2]), # y0 = lloc$center.y[1] - lloc$height[1] / 2, # x1 = mean(lloc$center.x[7]), # y1 = lloc$center.y[1] - lloc$height[1] / 2, lend = 1, # lwd = .5, # col = gray(0)) } } # MiniROC if(show.roc) { text(lloc$center.x[lloc$element == "roc"], header.y.loc, "ROC", pos = 1, cex = header.cex) # text(final.roc.center[1], subheader.y.loc, paste("AUC =", round(final.auc, 2)), pos = 1) final.roc.x.loc <- c(lloc$center.x[lloc$element == "roc"] - lloc$width[lloc$element == "roc"] / 2,lloc$center.x[lloc$element == "roc"] + lloc$width[lloc$element == "roc"] / 2) final.roc.y.loc <- c(lloc$center.y[lloc$element == "roc"] - lloc$height[lloc$element == "roc"] / 2,lloc$center.y[lloc$element == "roc"] + lloc$height[lloc$element == "roc"] / 2) # Plot bg # # rect(final.roc.x.loc[1], # final.roc.y.loc[1], # final.roc.x.loc[2], # final.roc.y.loc[2], # col = gray(1), lwd = .5) # Gridlines # # Horizontal # segments(x0 = rep(final.roc.x.loc[1], 9), # y0 = seq(final.roc.y.loc[1], final.roc.y.loc[2], length.out = 5)[2:10], # x1 = rep(final.roc.x.loc[2], 9), # y1 = seq(final.roc.y.loc[1], final.roc.y.loc[2], length.out = 5)[2:10], # lty = 1, col = gray(.8), lwd = c(.5), lend = 3 # ) # # # Vertical # segments(y0 = rep(final.roc.y.loc[1], 9), # x0 = seq(final.roc.x.loc[1], final.roc.x.loc[2], length.out = 5)[2:10], # y1 = rep(final.roc.y.loc[2], 9), # x1 = seq(final.roc.x.loc[1], final.roc.x.loc[2], length.out = 5)[2:10], # lty = 1, col = gray(.8), lwd = c(.5), lend = 3 # ) # Plot border rect(final.roc.x.loc[1], final.roc.y.loc[1], final.roc.x.loc[2], final.roc.y.loc[2], border = roc.border.col, lwd = roc.lwd) # Axis labels text(c(final.roc.x.loc[1], final.roc.x.loc[2]), c(final.roc.y.loc[1], final.roc.y.loc[1]) - .05, labels = c(0, 1)) text(c(final.roc.x.loc[1], final.roc.x.loc[1], final.roc.x.loc[1]) - .02, c(final.roc.y.loc[1], mean(final.roc.y.loc[1:2]), final.roc.y.loc[2]), labels = c(0,.5, 1)) text(mean(final.roc.x.loc), final.roc.y.loc[1] - .08, "1 - Specificity (FAR)") text(final.roc.x.loc[1] - .04, mean(final.roc.y.loc), "Sensitivity (HR)", srt = 90) # Diagonal segments(final.roc.x.loc[1], final.roc.y.loc[1], final.roc.x.loc[2], final.roc.y.loc[2], lty = 3) label.loc <- c(.1, .3, .5, .7, .9) ## COMPETITIVE ALGORITHMS if(comp == TRUE) { # CART if(is.null(x$comp$cart$results) == FALSE) { cart.spec <- x$comp$cart$results[[data]]$spec cart.sens <- x$comp$cart$results[[data]]$sens points(final.roc.x.loc[1] + (1 - cart.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + cart.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("red", .1), bg = yarrr::transparent("red", .9), lwd = 1) points(final.roc.x.loc[1] + (1 - cart.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + cart.sens * lloc$height[lloc$element == "roc"], pch = "C", cex = .7, col = gray(.2), lwd = 1) par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[4] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("red", .1), bg = yarrr::transparent("red", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[4] * lloc$height[lloc$element == "roc"], pch = "C", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[4] * lloc$height[lloc$element == "roc"], labels = " CART", adj = 0, cex = .9) par("xpd" = TRUE) } ## LR if(is.null(x$comp$lr$results) == FALSE) { lr.spec <- x$comp$lr$results[[data]]$spec lr.sens <- x$comp$lr$results[[data]]$sens points(final.roc.x.loc[1] + (1 - lr.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + lr.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("blue", .1), bg = yarrr::transparent("blue", .9)) points(final.roc.x.loc[1] + (1 - lr.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + lr.sens * lloc$height[lloc$element == "roc"], pch = "L", cex = .7, col = gray(.2)) par("xpd" = F) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[3] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("blue", .1), bg = yarrr::transparent("blue", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[3] * lloc$height[lloc$element == "roc"], pch = "L", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[3] * lloc$height[lloc$element == "roc"], labels = " LR", adj = 0, cex = .9) par("xpd" = T) } ## rf if(is.null(x$comp$rf$results) == FALSE) { rf.spec <- x$comp$rf$results[[data]]$spec rf.sens <- x$comp$rf$results[[data]]$sens points(final.roc.x.loc[1] + (1 - rf.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + rf.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("purple", .1), bg = yarrr::transparent("purple", .9), lwd = 1) points(final.roc.x.loc[1] + (1 - rf.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + rf.sens * lloc$height[lloc$element == "roc"], pch = "C", cex = .7, col = gray(.2), lwd = 1) par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[2] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("purple", .1), bg = yarrr::transparent("purple", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[2] * lloc$height[lloc$element == "roc"], pch = "R", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[2] * lloc$height[lloc$element == "roc"], labels = " RF", adj = 0, cex = .9) par("xpd" = TRUE) } ## svm ## svm if(is.null(x$comp$svm$results) == FALSE) { svm.spec <- x$comp$svm$results[[data]]$spec svm.sens <- x$comp$svm$results[[data]]$sens points(final.roc.x.loc[1] + (1 - svm.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + svm.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("orange", .1), bg = yarrr::transparent("orange", .9), lwd = 1) points(final.roc.x.loc[1] + (1 - svm.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + svm.sens * lloc$height[lloc$element == "roc"], pch = "C", cex = .7, col = gray(.2), lwd = 1) par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[1] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("orange", .1), bg = yarrr::transparent("orange", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[1] * lloc$height[lloc$element == "roc"], pch = "S", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[1] * lloc$height[lloc$element == "roc"], labels = " SVM", adj = 0, cex = .9) par("xpd" = TRUE) } } ## FFT { roc.order <- order(fft.spec.vec, decreasing = TRUE) # roc.order <- 1:x$trees$n fft.sens.vec.ord <- fft.sens.vec[roc.order] fft.spec.vec.ord <- fft.spec.vec[roc.order] # Add segments and points for all trees but tree if(length(roc.order) > 1) { segments(final.roc.x.loc[1] + c(0, 1 - fft.spec.vec.ord) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + c(0, fft.sens.vec.ord) * lloc$height[lloc$element == "roc"], final.roc.x.loc[1] + c(1 - fft.spec.vec.ord, 1) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + c(fft.sens.vec.ord, 1) * lloc$height[lloc$element == "roc"], lwd = 1, col = gray(0)) points(final.roc.x.loc[1] + (1 - fft.spec.vec.ord[-(which(roc.order == tree))]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec.ord[-(which(roc.order == tree))] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("green", .3), bg = yarrr::transparent("white", .1)) text(final.roc.x.loc[1] + (1 - fft.spec.vec.ord[-(which(roc.order == tree))]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec.ord[-(which(roc.order == tree))] * lloc$height[lloc$element == "roc"], labels = roc.order[which(roc.order != tree)], cex = 1, col = gray(.2)) } # Add large point for plotted tree points(final.roc.x.loc[1] + (1 - fft.spec.vec[tree]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec[tree] * lloc$height[lloc$element == "roc"], pch = 21, cex = 3, col = gray(1), #col = yarrr::transparent("green", .3), bg = yarrr::transparent("green", .3), lwd = 1) text(final.roc.x.loc[1] + (1 - fft.spec.vec[tree]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec[tree] * lloc$height[lloc$element == "roc"], labels = tree, cex = 1.25, col = gray(.2), font = 2) # Labels if(comp == TRUE & any(is.null(x$comp$lr$results) == FALSE, is.null(x$comp$cart$results) == FALSE, is.null(x$comp$svm$results) == FALSE, is.null(x$comp$rf$results) == FALSE )) { par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[5] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("green", .3), bg = yarrr::transparent("green", .7)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[5] * lloc$height[lloc$element == "roc"], pch = "#", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[5] * lloc$height[lloc$element == "roc"], labels = " FFT", adj = 0, cex = .9) par("xpd" = TRUE) } } } } } # Reset plotting space par(mfrow = c(1, 1)) par(mar = c(5, 4, 4, 1) + .1) } }
/R/plotFFTrees_function.R
no_license
guhjy/FFTrees
R
false
false
57,366
r
#' Plots an FFTrees object. #' #' @description Plots an FFTrees object created by the FFTrees() function. #' @param x A FFTrees object created from \code{"FFTrees()"} #' @param data One of two strings 'train' or 'test'. In this case, the corresponding dataset in the x object will be used. #' @param what string. What should be plotted? \code{'tree'} (the default) shows one tree (specified by \code{'tree'}). \code{'cues'} shows the marginal accuracy of cues in an ROC space, \code{"roc"} shows an roc curve of the tree(s) #' @param tree integer. An integer indicating which tree to plot (only valid when the tree argument is non-empty). To plot the best training (or test) tree with respect to the \code{goal} specified during FFT construction, use "best.train" or "best.test" #' @param main character. The main plot label. #' @param hlines logical. Should horizontal panel separation lines be shown? #' @param cue.labels character. An optional string of labels for the cues / nodes. #' @param decision.labels character. A string vector of length 2 indicating the content-specific name for noise and signal cases. #' @param cue.cex numeric. The size of the cue labels. #' @param threshold.cex numeric. The size of the threshold labels. #' @param decision.cex numeric. The size of the decision labels. #' @param comp logical. Should the performance of competitive algorithms (e.g.; logistic regression, random forests etc.) be shown in the ROC plot (if available?) #' @param stats logical. Should statistical information be plotted? If \code{FALSE}, then only the tree (without any reference to statistics) will be plotted. #' @param show.header,show.tree,show.confusion,show.levels,show.roc,show.icons,show.iconguide logical. Logical arguments indicating which specific elements of the plot to show. #' @param label.tree,label.performance string. Optional arguments to define lables for the tree and performance section(s). #' @param n.per.icon Number of cases per icon #' @param which.tree deprecated argument, only for backwards compatibility, use \code{"tree"} instead. #' @param level.type string. How should bottom levels be drawn? Can be \code{"bar"} or \code{"line"} #' @param decision.names deprecated arguments. #' @param ... Currently ignored. #' @importFrom stats anova predict formula model.frame #' @importFrom graphics text points abline legend mtext segments rect arrows axis par layout plot #' @importFrom grDevices gray col2rgb rgb #' @importFrom yarrr transparent piratepal #' @export #' @examples #' #' # Create FFTrees of the heart disease data #' heart.fft <- FFTrees(formula = diagnosis ~., #' data = heartdisease) #' #' # Visualise the tree #' plot(heart.fft, #' main = "Heart Disease Diagnosis", #' decision.labels = c("Absent", "Present")) #' #' #' # See the vignette for more details #' vignette("FFTrees_plot", package = "FFTrees") #' #' #' plot.FFTrees <- function( x = NULL, data = "train", what = 'tree', tree = "best.train", main = NULL, hlines = TRUE, cue.labels = NULL, decision.labels = NULL, cue.cex = NULL, threshold.cex = NULL, decision.cex = 1, comp = TRUE, stats = TRUE, show.header = NULL, show.tree = NULL, show.confusion = NULL, show.levels = NULL, show.roc = NULL, show.icons = NULL, show.iconguide = NULL, label.tree = NULL, label.performance = NULL, n.per.icon = NULL, which.tree = NULL, level.type = "bar", decision.names = NULL, ... ) { # # # # # data = "train" # what = 'tree' # tree = "best.train" # main = NULL # hlines = TRUE # cue.labels = NULL # decision.labels = NULL # cue.cex = NULL # threshold.cex = NULL # decision.cex = 1 # comp = TRUE # stats = TRUE # show.header = NULL # show.tree = NULL # show.confusion = NULL # show.levels = NULL # show.roc = NULL # show.icons = NULL # show.iconguide = NULL # label.tree = NULL # label.performance = NULL # n.per.icon = NULL # which.tree = NULL # level.type = "bar" # decision.names = NULL # Check for invalid or missing arguments # Input validation { if(what %in% c("cues", "tree", "roc") == FALSE) { stop("what must be either 'cues', 'tree', or 'roc'") } if(is.null(decision.names) == FALSE) { message("decision.names is deprecated, use decision.lables instead") decision.labels <- decision.names } } # If what == cues, then send inputs to showcues() if(what == 'cues') {showcues(x = x, data = data, main = main)} if(what != 'cues') { # Determine layout { if(what == "tree") { if(stats == TRUE) { if(is.null(show.header)) {show.header <- TRUE} if(is.null(show.tree)) {show.tree <- TRUE} if(is.null(show.confusion)) {show.confusion <- TRUE} if(is.null(show.levels)) {show.levels <- TRUE} if(is.null(show.roc)) {show.roc <- TRUE} if(is.null(show.icons)) {show.icons <- TRUE} if(is.null(show.iconguide)) {show.iconguide <- TRUE} } if(stats == FALSE) { if(is.null(show.header)) {show.header <- FALSE} if(is.null(show.tree)) {show.tree <- TRUE} if(is.null(show.confusion)) {show.confusion <- FALSE} if(is.null(show.levels)) {show.levels <- FALSE} if(is.null(show.roc)) {show.roc <- FALSE} if(is.null(show.icons)) {show.icons <- FALSE} if(is.null(show.iconguide)) {show.iconguide <- FALSE} } } if(what == "roc") { show.header <- FALSE show.tree <- FALSE show.confusion <- FALSE show.levels <- FALSE show.roc <- TRUE show.icons <- FALSE show.top <- FALSE } # Top, middle, bottom if(show.header & show.tree & (show.confusion | show.levels | show.roc)) { show.top <- TRUE show.middle <- TRUE show.bottom <- TRUE layout(matrix(1:3, nrow = 3, ncol = 1), widths = c(6), heights = c(1.2, 3, 1.8)) } # Top and middle if(show.header & show.tree & (show.confusion == FALSE & show.levels == FALSE & show.roc == FALSE)) { show.top <- TRUE show.middle <- TRUE show.bottom <- FALSE layout(matrix(1:2, nrow = 2, ncol = 1), widths = c(6), heights = c(1.2, 3)) } # Middle and bottom if(show.header == FALSE & show.tree & (show.confusion | show.levels | show.roc)) { show.top <- FALSE show.middle <- TRUE show.bottom <- TRUE layout(matrix(1:2, nrow = 2, ncol = 1), widths = c(6), heights = c(3, 1.8)) } # Middle if(show.header == FALSE & show.tree & (show.confusion == FALSE & show.levels == FALSE & show.roc == FALSE)) { show.top <- FALSE show.middle <- TRUE show.bottom <- FALSE layout(matrix(1:1, nrow = 1, ncol = 1), widths = c(6), heights = c(3)) } # Bottom if(show.header == FALSE & show.tree == FALSE) { show.top <- FALSE show.middle <- FALSE show.bottom <- TRUE nplots <- show.confusion + show.levels + show.roc layout(matrix(1:nplots, nrow = 1, ncol = nplots), widths = c(3 * nplots), heights = c(3)) } } # ------------------------- # Setup data # -------------------------- { # Extract important parameters from x goal <- x$params$goal if(is.null(decision.labels)) { if(("decision.labels" %in% names(x$params))) { decision.labels <- x$params$decision.labels } else {decision.labels <- c(0, 1)} } if(is.null(main)) { if(("main" %in% names(x$params))) { if(is.null(x$params$main)) { if(show.header) { main <- "Data" } else {main <- ""} } else { main <- x$params$main } } else { if(class(data) == "character") { if(data == "train") {main <- "Data (Training)"} if(data == "test") {main <- "Data (Testing)"} } if(class(data) == "data.frame") {main <- "Test Data"} } } # Check for problems and depreciated arguments { if(is.null(which.tree) == FALSE) { message("The which.tree argument is depreciated and is now just called tree. Please use tree from now on to avoid this message.") tree <- which.tree } if(class(x) != "FFTrees") { stop("You did not include a valid FFTrees class object or specify the tree directly with level.names, level.classes (etc.). Either create a valid FFTrees object with FFTrees() or specify the tree directly.") } if(tree == "best.test" & is.null(x$tree.stats$test)) { print("You wanted to plot the best test tree (tree = 'best.test') but there were no test data, I'll plot the best training tree instead") tree <- "best.train" } if(is.numeric(tree) & (tree %in% 1:x$trees$n) == F) { stop(paste("You asked for a tree that does not exist. This object has", x$trees$n, "trees")) } if(class(data) == "character") { if(data == "test" & is.null(x$trees$results$test$stats)) {stop("You asked to plot the test data but there are no test data in the FFTrees object")} } } # DEFINE PLOTTING TREE if(tree == "best.train") { tree <- x$trees$best$train } if(tree == "best.test") { tree <- x$trees$best$test } # DEFINE CRITICAL OBJECTS lr.stats <- NULL cart.stats <- NULL rf.stats <- NULL svm.stats <- NULL decision.v <- x$trees$results[[data]]$decisions[,tree] tree.stats <- x$trees$results[[data]]$stats level.stats <- x$trees$results[[data]]$level_stats[x$trees$results[[data]]$level_stats$tree == tree,] if(comp == TRUE) { if(is.null(x$comp$lr$results) == FALSE) { lr.stats <- data.frame("sens" = x$comp$lr$results[[data]]$sens, "spec" = x$comp$lr$results[[data]]$spec) } if(is.null(x$comp$cart$results) == FALSE) { lcart.stats <- data.frame("sens" = x$comp$cart$results[[data]]$sens, "spec" = x$comp$cart$results[[data]]$spec) } if(is.null(x$comp$rf$results) == FALSE) { rf.stats <- data.frame("sens" = x$comp$rf$results[[data]]$sens, "spec" = x$comp$rf$results[[data]]$spec) } if(is.null(x$comp$svm$results) == FALSE) { svm.stats <- data.frame("sens" = x$comp$svm$results[[data]]$sens, "spec" = x$comp$svm$results[[data]]$spec) } } n.exemplars <- nrow(x$data[[data]]) n.pos <- sum(x$data[[data]][[x$metadata$criterion_name]]) n.neg <- sum(x$data[[data]][[x$metadata$criterion_name]] == FALSE) mcu <- x$trees$results[[data]]$stats$mcu[tree] crit.br <- mean(x$data[[data]][[x$metadata$criterion_name]]) final.stats <- tree.stats[tree,] # ADD LEVEL STATISTICS n.levels <- nrow(level.stats) # Add marginal classification statistics to level.stats level.stats[c("hi.m", "mi.m", "fa.m", "cr.m")] <- NA for(i in 1:n.levels) { if(i == 1) { level.stats[1, c("hi.m", "mi.m", "fa.m", "cr.m")] <- level.stats[1, c("hi", "mi", "fa", "cr")] } if(i > 1) { level.stats[i, c("hi.m", "mi.m", "fa.m", "cr.m")] <- level.stats[i, c("hi", "mi", "fa", "cr")] - level.stats[i - 1, c("hi", "mi", "fa", "cr")] } } } # ------------------------- # Define plotting parameters # -------------------------- { { # Panels panel.line.lwd <- 1 panel.line.col <- gray(0) panel.line.lty <- 1 # Some general parameters ball.col = c(gray(0), gray(0)) ball.bg = c(gray(1), gray(1)) ball.pch = c(21, 24) ball.cex = c(1, 1) error.col <- "red" correct.col <- "green" max.label.length <- 100 def.par <- par(no.readonly = TRUE) ball.box.width <- 10 label.box.height <- 2 label.box.width <- 5 # Define cue labels { if(is.null(cue.labels)) { cue.labels <- level.stats$cue } # Trim labels cue.labels <- strtrim(cue.labels, max.label.length) } # Node Segments segment.lty <- 1 segment.lwd <- 1 continue.segment.lwd <- 1 continue.segment.lty <- 1 exit.segment.lwd <- 1 exit.segment.lty <- 1 decision.node.cex <- 4 exit.node.cex <- 4 panel.title.cex <- 2 # Classification table classtable.lwd <- 1 # ROC roc.lwd <- 1 roc.border.col <- gray(0) # Label sizes { # Set cue label size if(is.null(cue.cex)) { cue.cex <- c(1.5, 1.5, 1.25, 1, 1, 1) } else { if(length(cue.cex) < 6) {cue.cex <- rep(cue.cex, length.out = 6)} } # Set break label size if(is.null(threshold.cex)) { threshold.cex <- c(1.5, 1.5, 1.25, 1, 1, 1) } else { if(length(threshold.cex) < 6) {threshold.cex <- rep(threshold.cex, length.out = 6)} } } if(show.top & show.middle & show.bottom) { plotting.parameters.df <- data.frame( n.levels = 1:6, plot.height = c(10, 12, 15, 19, 23, 27), plot.width = c(14, 16, 20, 24, 28, 34), label.box.text.cex = cue.cex, break.label.cex = threshold.cex ) } else if (show.top == FALSE & show.middle & show.bottom == FALSE) { plotting.parameters.df <- data.frame( n.levels = 1:6, plot.height = c(10, 12, 15, 19, 23, 25), plot.width = c(14, 16, 20, 24, 28, 32) * 1, label.box.text.cex = cue.cex, break.label.cex = threshold.cex ) } else { plotting.parameters.df <- data.frame( n.levels = 1:6, plot.height = c(10, 12, 15, 19, 23, 25), plot.width = c(14, 16, 20, 24, 28, 32) * 1, label.box.text.cex = cue.cex, break.label.cex = threshold.cex ) } if(n.levels < 6) { label.box.text.cex <- plotting.parameters.df$label.box.text.cex[n.levels] break.label.cex <- plotting.parameters.df$break.label.cex[n.levels] plot.height <- plotting.parameters.df$plot.height[n.levels] plot.width <- plotting.parameters.df$plot.width[n.levels] } if(n.levels >= 6) { label.box.text.cex <- plotting.parameters.df$label.box.text.cex[6] break.label.cex <- plotting.parameters.df$break.label.cex[6] plot.height <- plotting.parameters.df$plot.height[6] plot.width <- plotting.parameters.df$plot.width[6] } # Colors exit.node.bg <- "white" error.colfun <- circlize::colorRamp2(c(0, 50, 100), colors = c("white", "red", "black")) correct.colfun <- circlize::colorRamp2(c(0, 50, 100), colors = c("white", "green", "black")) error.bg <- yarrr::transparent(error.colfun(35), .2) error.border <- yarrr::transparent(error.colfun(65), .1) correct.bg <- yarrr::transparent(correct.colfun(35), .2) correct.border <- yarrr::transparent(correct.colfun(65), .1) max.cex <- 6 min.cex <- 1 exit.node.pch <- 21 decision.node.pch <- NA_integer_ # balls ball.loc <- "variable" if(n.levels == 3) {ball.box.width <- 14} if(n.levels == 4) {ball.box.width <- 18} ball.box.height <- 2.5 ball.box.horiz.shift <- 10 ball.box.vert.shift <- -1 ball.box.max.shift.p <- .9 ball.box.min.shift.p <- .4 ball.box.fixed.x.shift <- c(ball.box.min.shift.p * plot.width, ball.box.max.shift.p * plot.width) # Determine N per ball if(is.null(n.per.icon)) { max.n.side <- max(c(n.pos, n.neg)) i <- max.n.side / c(1, 5, 10^(1:10)) i[i > 50] <- 0 n.per.icon <- c(1, 5, 10^(1:10))[which(i == max(i))] } noise.ball.pch <- ball.pch[1] signal.ball.pch <- ball.pch[2] noise.ball.col <- ball.col[1] signal.ball.col <- ball.col[2] noise.ball.bg <- ball.bg[1] signal.ball.bg <- ball.bg[2] # arrows arrow.lty <- 1 arrow.lwd <- 1 arrow.length <- 2.5 arrow.head.length <- .08 arrow.col <- gray(0) # Final stats spec.circle.x <- .4 dprime.circle.x <- .5 sens.circle.x <- .6 stat.circle.y <- .3 sens.circle.col <- "green" spec.circle.col <- "red" dprime.circle.col <- "blue" stat.outer.circle.col <- gray(.5) } # add.balls.fun() adds balls to the plot add.balls.fun <- function(x.lim = c(-10, 0), y.lim = c(-2, 0), n.vec = c(20, 10), pch.vec = c(21, 21), ball.cex = 1, bg.vec = ball.bg, col.vec = ball.col, ball.lwd = .7, freq.text = TRUE, freq.text.cex = 1.2, upper.text = "", upper.text.cex = 1, upper.text.adj = 0, rev.order = F, box.col = NULL, box.bg = NULL, n.per.icon = NULL ) { # Add box if(is.null(box.col) == FALSE | is.null(box.bg) == FALSE) { rect(x.lim[1], y.lim[1], x.lim[2], y.lim[2], col = box.bg, border = box.col) } # add upper text text(mean(x.lim), y.lim[2] + upper.text.adj, label = upper.text, cex = upper.text.cex ) a.n <- n.vec[1] b.n <- n.vec[2] a.p <- n.vec[1] / sum(n.vec) box.x.center <- sum(x.lim) / 2 box.y.center <- sum(y.lim) / 2 box.x.width <- x.lim[2] - x.lim[1] # Determine cases per ball if(is.null(n.per.icon)) { max.n.side <- max(c(a.n, b.n)) i <- max.n.side / c(1, 5, 10, 50, 100, 1000, 10000) i[i > 50] <- 0 n.per.icon <- c(1, 5, 10, 50, 100, 1000, 10000)[which(i == max(i))] } # Determine general ball locations a.balls <- ceiling(a.n / n.per.icon) b.balls <- ceiling(b.n / n.per.icon) n.balls <- a.balls + b.balls a.ball.x.loc <- 0 a.ball.y.loc <- 0 b.ball.x.loc <- 0 b.ball.y.loc <- 0 if(a.balls > 0) { a.ball.x.loc <- rep(-1:-10, each = 5, length.out = 50)[1:a.balls] a.ball.y.loc <- rep(1:5, times = 10, length.out = 50)[1:a.balls] a.ball.x.loc <- a.ball.x.loc * (x.lim[2] - box.x.center) / 10 + box.x.center a.ball.y.loc <- a.ball.y.loc * (y.lim[2] - y.lim[1]) / 5 + y.lim[1] } if(b.balls > 0) { b.ball.x.loc <- rep(1:10, each = 5, length.out = 50)[1:b.balls] b.ball.y.loc <- rep(1:5, times = 10, length.out = 50)[1:b.balls] b.ball.x.loc <- b.ball.x.loc * (x.lim[2] - box.x.center) / 10 + box.x.center b.ball.y.loc <- b.ball.y.loc * (y.lim[2] - y.lim[1]) / 5 + y.lim[1] } # if(rev.order) { # # x <- b.ball.x.loc # y <- b.ball.y.loc # # b.ball.x.loc <- a.x.loc # b.ball.y.loc <- a.y.loc # # a.ball.x.loc <- x # a.ball.y.loc <- y # # } # Add frequency text if(freq.text) { text(box.x.center, y.lim[1] - 1 * (y.lim[2] - y.lim[1]) / 5, prettyNum(b.n, big.mark = ","), pos = 4, cex = freq.text.cex) text(box.x.center, y.lim[1] - 1 * (y.lim[2] - y.lim[1]) / 5, prettyNum(a.n, big.mark = ","), pos = 2, cex = freq.text.cex) } # Draw balls # Noise suppressWarnings(if(a.balls > 0) { points(x = a.ball.x.loc, y = a.ball.y.loc, pch = pch.vec[1], bg = bg.vec[1], col = col.vec[1], cex = ball.cex, lwd = ball.lwd) } ) # Signal suppressWarnings(if(b.balls > 0) { points(x = b.ball.x.loc, y = b.ball.y.loc, pch = pch.vec[2], bg = bg.vec[2], col = col.vec[2], cex = ball.cex, lwd = ball.lwd ) } ) } label.cex.fun <- function(i, label.box.text.cex = 2) { i <- nchar(i) label.box.text.cex * i ^ -.25 } } # ------------------------- # 1: Initial Frequencies # -------------------------- if(show.top) { par(mar = c(0, 0, 1, 0)) plot(1, xlim = c(0, 1), ylim = c(0, 1), bty = "n", type = "n", xlab = "", ylab = "", yaxt = "n", xaxt = "n") if(hlines) { segments(0, .95, 1, .95, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) } rect(.33, .8, .67, 1.2, col = "white", border = NA) text(x = .5, y = .95, main, cex = panel.title.cex) text(x = .5, y = .80, paste("N = ", prettyNum(n.exemplars, big.mark = ","), "", sep = ""), cex = 1.25) n.trueneg <- with(final.stats, cr + fa) n.truepos <- with(final.stats, hi + mi) text(.5, .65, paste(decision.labels[1], sep = ""), pos = 2, cex = 1.2, adj = 1) text(.5, .65, paste(decision.labels[2], sep = ""), pos = 4, cex = 1.2, adj = 0) #points(.9, .8, pch = 1, cex = 1.2) #text(.9, .8, labels = paste(" = ", n.per.icon, " cases", sep = ""), pos = 4) # Show ball examples par(xpd = T) add.balls.fun(x.lim = c(.35, .65), y.lim = c(.1, .5), n.vec = c(final.stats$fa + final.stats$cr, final.stats$hi + final.stats$mi), pch.vec = c(noise.ball.pch, signal.ball.pch), bg.vec = c(noise.ball.bg, signal.ball.bg), col.vec = c(noise.ball.col, signal.ball.col), ball.cex = ball.cex, upper.text.adj = 2, n.per.icon = n.per.icon ) par(xpd = F) # Add p.signal and p.noise levels signal.p <- mean(x$data[[data]][[x$metadata$criterion_name]]) noise.p <- 1 - signal.p p.rect.ylim <- c(.1, .6) # p.signal level text(x = .8, y = p.rect.ylim[2], labels = paste("p(", decision.labels[2], ")", sep = ""), pos = 3, cex = 1.2) #Filling rect(.775, p.rect.ylim[1], .825, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), col = gray(.5, .25), border = NA) # Filltop segments(.775, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), .825, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), lwd = 1) #Outline rect(.775, p.rect.ylim[1], .825, p.rect.ylim[2], lwd = 1) if(signal.p < .0001) {signal.p.text <- "<1%"} else { signal.p.text <- paste(round(signal.p * 100, 0), "%", sep = "") } text(.825, p.rect.ylim[1] + signal.p * diff(p.rect.ylim), labels = signal.p.text, pos = 4, cex = 1.2) #p.noise level text(x = .2, y = p.rect.ylim[2], labels = paste("p(", decision.labels[1], ")", sep = ""), pos = 3, cex = 1.2) rect(.175, p.rect.ylim[1], .225, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), col = gray(.5, .25), border = NA) # Filltop segments(.175, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), .225, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), lwd = 1) # outline rect(.175, p.rect.ylim[1], .225, p.rect.ylim[2], lwd = 1) if(noise.p < .0001) {noise.p.text <- "<0.01%"} else { noise.p.text <- paste(round(noise.p * 100, 0), "%", sep = "") } text(.175, p.rect.ylim[1] + noise.p * diff(p.rect.ylim), labels = noise.p.text, pos = 2, cex = 1.2) } # ------------------------- # 2. TREE # -------------------------- if(show.middle) { if(show.top == FALSE & show.bottom == FALSE) { par(mar = c(3, 3, 3, 3) + .1) } else {par(mar = c(0, 0, 0, 0)) } # Setup plotting space plot(1, xlim = c(-plot.width, plot.width), ylim = c(-plot.height, 0), type = "n", bty = "n", xaxt = "n", yaxt = "n", ylab = "", xlab = "" ) # Add frame par(xpd = TRUE) if(show.top | show.bottom) { if(hlines) { segments(-plot.width, 0, - plot.width * .3, 0, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) segments(plot.width, 0, plot.width * .3, 0, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) } if(is.null(label.tree)) {label.tree <- paste("FFT #", tree, " (of ", x$trees$n, ")", sep = "")} text(x = 0, y = 0, label.tree, cex = panel.title.cex) } if(show.top == FALSE & show.bottom == FALSE) { if(is.null(main) & is.null(x$params$main)) {main <- ""} mtext(text = main, side = 3, cex = 2) } par(xpd = FALSE) # Create Noise and Signal panels if(show.iconguide) { # Noise Balls points(c(- plot.width * .7, - plot.width * .5), c(-plot.height * .125, -plot.height * .125), pch = c(noise.ball.pch, signal.ball.pch), bg = c(correct.bg, error.bg), col = c(correct.border, error.border), cex = ball.cex * 1.5 ) text(c(- plot.width * .7, - plot.width * .5), c(-plot.height * .125, -plot.height * .125), labels = c("Correct\nRejection", "Miss"), pos = c(2, 4), offset = 1) # Noise Panel text(- plot.width * .6, -plot.height * .05, paste("Decide ", decision.labels[1], sep = ""), cex = 1.2, font = 3 ) # Signal panel text(plot.width * .6, -plot.height * .05, paste("Decide ", decision.labels[2], sep = ""), cex = 1.2, font = 3 ) points(c(plot.width * .5, plot.width * .7), c(-plot.height * .125, -plot.height * .125), pch = c(noise.ball.pch, signal.ball.pch), bg = c(error.bg, correct.bg), col = c(error.border, correct.border), cex = ball.cex * 1.5 ) text(c(plot.width * .5, plot.width * .7), c(-plot.height * .125, -plot.height * .125), labels = c("False\nAlarm", "Hit"), pos = c(2, 4), offset = 1) } # Set initial subplot center subplot.center <- c(0, -4) # Loop over levels for(level.i in 1:min(c(n.levels, 6))) { current.cue <- cue.labels[level.i] # Get stats for current level { hi.i <- level.stats$hi.m[level.i] mi.i <- level.stats$mi.m[level.i] fa.i <- level.stats$fa.m[level.i] cr.i <- level.stats$cr.m[level.i] } # If level.i == 1, draw top textbox { if(level.i == 1) { rect(subplot.center[1] - label.box.width / 2, subplot.center[2] + 2 - label.box.height / 2, subplot.center[1] + label.box.width / 2, subplot.center[2] + 2 + label.box.height / 2, col = "white", border = "black" ) points(x = subplot.center[1], y = subplot.center[2] + 2, cex = decision.node.cex, pch = decision.node.pch ) text(x = subplot.center[1], y = subplot.center[2] + 2, labels = current.cue, cex = label.box.text.cex#label.cex.fun(current.cue, label.box.text.cex = label.box.text.cex) ) } } # ----------------------- # Left (Noise) Classification / New Level # ----------------------- { # Exit node on left if(level.stats$exit[level.i] %in% c(0, .5) | paste(level.stats$exit[level.i]) %in% c("0", ".5")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] - 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) arrows(x0 = subplot.center[1] - 2, y0 = subplot.center[2] - 2, x1 = subplot.center[1] - 2 - arrow.length, y1 = subplot.center[2] - 2, lty = arrow.lty, lwd = arrow.lwd, col = arrow.col, length = arrow.head.length ) # Decision text if(decision.cex > 0) { text(x = subplot.center[1] - 2 - arrow.length * .7, y = subplot.center[2] - 2.2, labels = decision.labels[1], pos = 1, font = 3, cex = decision.cex) } if(ball.loc == "fixed") { ball.x.lim <- c(-max(ball.box.fixed.x.shift), -min(ball.box.fixed.x.shift)) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(ball.loc == "variable") { ball.x.lim <- c(subplot.center[1] - ball.box.horiz.shift - ball.box.width / 2, subplot.center[1] - ball.box.horiz.shift + ball.box.width / 2) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(max(c(cr.i, mi.i), na.rm = TRUE) > 0 & show.icons == TRUE) { add.balls.fun(x.lim = ball.x.lim, y.lim = ball.y.lim, n.vec = c(cr.i, mi.i), pch.vec = c(noise.ball.pch, signal.ball.pch), # bg.vec = c(noise.ball.bg, signal.ball.bg), bg.vec = c(correct.bg, error.bg), col.vec = c(correct.border, error.border), freq.text = TRUE, n.per.icon = n.per.icon, ball.cex = ball.cex ) } # level break label pos.direction.symbol <- c("<=", "<", "=", "!=", ">", ">=")[which(level.stats$direction[level.i] == c(">", ">=", "!=", "=", "<=", "<"))] neg.direction.symbol <- c("<=", "<", "=", "!=", ">", ">=")[which(level.stats$direction[level.i] == c("<=", "<", "=", "!=", ">", ">="))] text.outline(x = subplot.center[1] - 1, y = subplot.center[2], labels = paste(pos.direction.symbol, " ", level.stats$threshold[level.i], sep = ""), pos = 2, cex = break.label.cex, r = .1 ) points(x = subplot.center[1] - 2, y = subplot.center[2] - 2, pch = exit.node.pch, cex = exit.node.cex, bg = exit.node.bg ) text(x = subplot.center[1] - 2, y = subplot.center[2] - 2, labels = substr(decision.labels[1], 1, 1) ) } # New level on left if(level.stats$exit[level.i] %in% c(1) | paste(level.stats$exit[level.i]) %in% c("1")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] - 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) rect(subplot.center[1] - 2 - label.box.width / 2, subplot.center[2] - 2 - label.box.height / 2, subplot.center[1] - 2 + label.box.width / 2, subplot.center[2] - 2 + label.box.height / 2, col = "white", border = "black" ) if(level.i < 6) {text(x = subplot.center[1] - 2, y = subplot.center[2] - 2, labels = cue.labels[level.i + 1], cex = label.box.text.cex )} else { text(x = subplot.center[1] - 2, y = subplot.center[2] - 2, labels = paste0("+ ", n.levels - 6, " More"), cex = label.box.text.cex, font = 3 ) } } } # ----------------------- # Right (Signal) Classification / New Level # ----------------------- { # Exit node on right if(level.stats$exit[level.i] %in% c(1, .5) | paste(level.stats$exit[level.i]) %in% c("1", ".5")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] + 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) arrows(x0 = subplot.center[1] + 2, y0 = subplot.center[2] - 2, x1 = subplot.center[1] + 2 + arrow.length, y1 = subplot.center[2] - 2, lty = arrow.lty, lwd = arrow.lwd, col = arrow.col, length = arrow.head.length ) # Decision text if(decision.cex > 0) { text(x = subplot.center[1] + 2 + arrow.length * .7, y = subplot.center[2] - 2.2, labels = decision.labels[2], pos = 1, font = 3, cex = decision.cex) } if(ball.loc == "fixed") { ball.x.lim <- c(min(ball.box.fixed.x.shift), max(ball.box.fixed.x.shift)) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(ball.loc == "variable") { ball.x.lim <- c(subplot.center[1] + ball.box.horiz.shift - ball.box.width / 2, subplot.center[1] + ball.box.horiz.shift + ball.box.width / 2) ball.y.lim <- c(subplot.center[2] + ball.box.vert.shift - ball.box.height / 2, subplot.center[2] + ball.box.vert.shift + ball.box.height / 2) } if(max(c(fa.i, hi.i), na.rm = TRUE) > 0 & show.icons == TRUE) { add.balls.fun(x.lim = ball.x.lim, y.lim = ball.y.lim, n.vec = c(fa.i, hi.i), pch.vec = c(noise.ball.pch, signal.ball.pch), # bg.vec = c(noise.ball.bg, signal.ball.bg), bg.vec = c(error.bg, correct.bg), col.vec = c(error.border, correct.border), freq.text = TRUE, n.per.icon = n.per.icon, ball.cex = ball.cex ) } # level break label dir.symbols <- c("<=", "<", "=", "!=", ">", ">=") pos.direction.symbol <- dir.symbols[which(level.stats$direction[level.i] == c("<=", "<", "=", "!=", ">", ">="))] neg.direction.symbol <- dir.symbols[which(level.stats$direction[level.i] == rev(c("<=", "<", "=", "!=", ">", ">=")))] text.outline(subplot.center[1] + 1, subplot.center[2], labels = paste(pos.direction.symbol, " ", level.stats$threshold[level.i], sep = ""), pos = 4, cex = break.label.cex, r = .1 ) points(x = subplot.center[1] + 2, y = subplot.center[2] - 2, pch = exit.node.pch, cex = exit.node.cex, bg = exit.node.bg ) text(x = subplot.center[1] + 2, y = subplot.center[2] - 2, labels = substr(decision.labels[2], 1, 1) ) } # New level on right if(level.stats$exit[level.i] %in% 0 | paste(level.stats$exit[level.i]) %in% c("0")) { segments(subplot.center[1], subplot.center[2] + 1, subplot.center[1] + 2, subplot.center[2] - 2, lty = segment.lty, lwd = segment.lwd ) if(level.i < 6) { rect(subplot.center[1] + 2 - label.box.width / 2, subplot.center[2] - 2 - label.box.height / 2, subplot.center[1] + 2 + label.box.width / 2, subplot.center[2] - 2 + label.box.height / 2, col = "white", border = "black") text(x = subplot.center[1] + 2, y = subplot.center[2] - 2, labels = cue.labels[level.i + 1], cex = label.box.text.cex) } else { rect(subplot.center[1] + 2 - label.box.width / 2, subplot.center[2] - 2 - label.box.height / 2, subplot.center[1] + 2 + label.box.width / 2, subplot.center[2] - 2 + label.box.height / 2, col = "white", border = "black", lty = 2) text(x = subplot.center[1] + 2, y = subplot.center[2] - 2, labels = paste0("+ ", n.levels - 6, " More"), cex = label.box.text.cex, font = 3 ) } } } # ----------------------- # Update plot center # ----------------------- { if(level.stats$exit[level.i] == 0) { subplot.center <- c(subplot.center[1] + 2, subplot.center[2] - 4) } if(level.stats$exit[level.i] == 1) { subplot.center <- c(subplot.center[1] - 2, subplot.center[2] - 4) } } } } # ----------------------- # 3. CUMULATIVE PERFORMANCE # ----------------------- if(show.bottom == TRUE) { { # OBTAIN FINAL STATISTICS fft.sens.vec <- tree.stats$sens fft.spec.vec <- tree.stats$spec # General plotting space { # PLOTTING PARAMETERS header.y.loc <- 1.0 subheader.y.loc <- .925 header.cex <- 1.1 subheader.cex <- .9 par(mar = c(0, 0, 2, 0)) plot(1, xlim = c(0, 1), ylim = c(0, 1), bty = "n", type = "n", xlab = "", ylab = "", yaxt = "n", xaxt = "n") par(xpd = T) if(hlines) { segments(0, 1.1, 1, 1.1, col = panel.line.col, lwd = panel.line.lwd, lty = panel.line.lty) rect(.25, 1, .75, 1.2, col = "white", border = NA) } if(is.null(label.performance)) { if(data == "train") {label.performance <- "Accuracy (Training)"} if(data == "test") {label.performance <- "Accuracy (Testing)"} } text(.5, 1.1, label.performance, cex = panel.title.cex) par(xpd = FALSE) pretty.dec <- function(x) {return(paste(round(x, 2) * 100, sep = ""))} level.max.height <- .65 level.width <- .05 level.center.y <- .45 #level.bottom <- .1 level.bottom <- level.center.y - level.max.height / 2 level.top <- level.center.y + level.max.height / 2 lloc <- data.frame( element = c("classtable", "mcu", "pci", "sens", "spec", "acc", "bacc", "roc"), long.name = c("Classification Table", "mcu", "pci", "sens", "spec", "acc", "bacc", "ROC"), center.x = c(.18, seq(.35, .65, length.out = 6), .85), center.y = rep(level.center.y, 8), width = c(.2, rep(level.width, 6), .2), height = c(.65, rep(level.max.height, 6), .65), value = c(NA, abs(final.stats$mcu - 5) / (abs(1 - 5)), final.stats$pci, final.stats$sens, final.stats$spec, with(final.stats, (cr + hi) / n), final.stats$bacc, NA), value.name = c(NA, round(final.stats$mcu, 1), pretty.dec(final.stats$pci), pretty.dec(final.stats$sens), pretty.dec(final.stats$spec), pretty.dec(final.stats$acc), pretty.dec(final.stats$bacc), NA ) ) } # Classification table if(show.confusion) { final.classtable.x.loc <- c(lloc$center.x[lloc$element == "classtable"] - lloc$width[lloc$element == "classtable"] / 2, lloc$center.x[lloc$element == "classtable"] + lloc$width[lloc$element == "classtable"] / 2) final.classtable.y.loc <- c(lloc$center.y[lloc$element == "classtable"] - lloc$height[lloc$element == "classtable"] / 2, lloc$center.y[lloc$element == "classtable"] + lloc$height[lloc$element == "classtable"] / 2) rect(final.classtable.x.loc[1], final.classtable.y.loc[1], final.classtable.x.loc[2], final.classtable.y.loc[2], lwd = classtable.lwd ) segments(mean(final.classtable.x.loc), final.classtable.y.loc[1], mean(final.classtable.x.loc), final.classtable.y.loc[2], col = gray(0), lwd = classtable.lwd) segments(final.classtable.x.loc[1], mean(final.classtable.y.loc), final.classtable.x.loc[2], mean(final.classtable.y.loc), col = gray(0), lwd = classtable.lwd) # Column titles text(x = mean(mean(final.classtable.x.loc)), y = header.y.loc, "Truth", pos = 1, cex = header.cex) text(x = final.classtable.x.loc[1] + .25 * diff(final.classtable.x.loc), y = subheader.y.loc, pos = 1, cex = subheader.cex, decision.labels[2]) text(x = final.classtable.x.loc[1] + .75 * diff(final.classtable.x.loc), y = subheader.y.loc, pos = 1, cex = subheader.cex, decision.labels[1]) # Row titles text(x = final.classtable.x.loc[1] - .01, y = final.classtable.y.loc[1] + .75 * diff(final.classtable.y.loc), cex = subheader.cex, decision.labels[2], adj = 1) text(x = final.classtable.x.loc[1] - .01, y = final.classtable.y.loc[1] + .25 * diff(final.classtable.y.loc), cex = subheader.cex, decision.labels[1], adj = 1) text(x = final.classtable.x.loc[1] - .065, y = mean(final.classtable.y.loc), cex = header.cex, "Decision") # text(x = final.classtable.x.loc[1] - .05, # y = mean(final.classtable.y.loc), cex = header.cex, # "Decision", srt = 90, pos = 3) # Add final frequencies text(final.classtable.x.loc[1] + .75 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .25 * diff(final.classtable.y.loc), prettyNum(final.stats$cr, big.mark = ","), cex = 1.5) text(final.classtable.x.loc[1] + .25 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .25 * diff(final.classtable.y.loc), prettyNum(final.stats$mi, big.mark = ","), cex = 1.5) text(final.classtable.x.loc[1] + .75 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .75 * diff(final.classtable.y.loc), prettyNum(final.stats$fa, big.mark = ","), cex = 1.5) text(final.classtable.x.loc[1] + .25 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .75 * diff(final.classtable.y.loc), prettyNum(final.stats$hi, big.mark = ","), cex = 1.5) # Add symbols points(final.classtable.x.loc[1] + .55 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .05 * diff(final.classtable.y.loc), pch = noise.ball.pch, bg = correct.bg, col = correct.border, cex = ball.cex) points(final.classtable.x.loc[1] + .05 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .55 * diff(final.classtable.y.loc), pch = signal.ball.pch, bg = correct.bg, cex = ball.cex, col = correct.border) points(final.classtable.x.loc[1] + .55 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .55 * diff(final.classtable.y.loc), pch = noise.ball.pch, bg = error.bg, col = error.border, cex = ball.cex) points(final.classtable.x.loc[1] + .05 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .05 * diff(final.classtable.y.loc), pch = signal.ball.pch, bg = error.bg, col = error.border, cex = ball.cex) # Labels text(final.classtable.x.loc[1] + .62 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .07 * diff(final.classtable.y.loc), "cr", cex = 1, font = 3, adj = 0) text(final.classtable.x.loc[1] + .12 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .07 * diff(final.classtable.y.loc), "mi", cex = 1, font = 3, adj = 0) text(final.classtable.x.loc[1] + .62 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .57 * diff(final.classtable.y.loc), "fa", cex = 1, font = 3, adj = 0) text(final.classtable.x.loc[1] + .12 * diff(final.classtable.x.loc), final.classtable.y.loc[1] + .57 * diff(final.classtable.y.loc), "hi", cex = 1, font = 3, adj = 0) } # Levels if(show.levels) { if(level.type %in% c("line", "bar")) { # Color function (taken from colorRamp2 function in circlize package) col.fun <- circlize::colorRamp2(c(0, .75, 1), c("red", "yellow", "green"), transparency = .1) add.level.fun <- function(name, sub = "", max.val = 1, min.val = 0, ok.val = .5, bottom.text = "", level.type = "line") { rect.center.x <- lloc$center.x[lloc$element == name] rect.center.y <- lloc$center.y[lloc$element == name] rect.height <- lloc$height[lloc$element == name] rect.width <- lloc$width[lloc$element == name] rect.bottom.y <- rect.center.y - rect.height / 2 rect.top.y <- rect.center.y + rect.height / 2 rect.left.x <- rect.center.x - rect.width / 2 rect.right.x <- rect.center.x + rect.width / 2 long.name <- lloc$long.name[lloc$element == name] value <- lloc$value[lloc$element == name] value.name <- lloc$value.name[lloc$element == name] # # level.col.fun <- circlize::colorRamp2(c(min.val, ok.val, max.val), # colors = c("firebrick2", "yellow", "green4"), # transparency = .1) text(x = rect.center.x, y = header.y.loc, labels = long.name, pos = 1, cex = header.cex) # # text.outline(x = rect.center.x, # y = header.y.loc, # labels = long.name, # pos = 1, cex = header.cex, r = .02 # ) value.height <- rect.bottom.y + min(c(1, ((value - min.val) / (max.val - min.val)))) * rect.height # Add filling value.s <- min(value / max.val, 1) delta <- 1 gamma <- .5 value.col.scale <- delta * value.s ^ gamma / (delta * value.s ^ gamma + (1 - value.s) ^ gamma) # value.col <- gray(1 - value.col.scale * .5) value.col <- gray(1, .25) #plot(seq(0, 1, .01), delta * seq(0, 1, .01) ^ gamma / (delta * seq(0, 1, .01) ^ gamma + (1 - seq(0, 1, .01)) ^ gamma)) if(level.type == "bar") { rect(rect.left.x, rect.bottom.y, rect.right.x, value.height, #col = level.col.fun(value.s), col = value.col, # col = spec.level.fun(lloc$value[lloc$element == name]), border = "black" ) text.outline(x = rect.center.x, y = value.height, labels = lloc$value.name[lloc$element == name], cex = 1.5, r = .008, pos = 3 ) # Add level border # rect(rect.left.x, # rect.bottom.y, # rect.right.x, # rect.top.y, # border = gray(.5, .5)) } if(level.type == "line") { # Stem segments(rect.center.x, rect.bottom.y, rect.center.x, value.height, lty = 3) # Horizontal platform platform.width <- .02 segments(rect.center.x - platform.width, value.height, rect.center.x + platform.width, value.height) # Text label text.outline(x = rect.center.x, y = value.height, labels = lloc$value.name[lloc$element == name], cex = 1.5, r = 0, pos = 3 ) # points(rect.center.x, # value.height, # cex = 5.5, # pch = 21, # bg = "white", # col = "black", lwd = .5) } # Add subtext text(x = rect.center.x, y = rect.center.y - .05, labels = sub, cex = .8, font = 1, pos = 1) # Add bottom text text(x = rect.center.x, y = rect.bottom.y, labels = bottom.text, pos = 1) } paste(final.stats$cr, "/", 1, collapse = "") #Add 100% reference line # segments(x0 = lloc$center.x[lloc$element == "mcu"] - lloc$width[lloc$element == "mcu"] * .8, # y0 = level.top, # x1 = lloc$center.x[lloc$element == "bacc"] + lloc$width[lloc$element == "bacc"] * .8, # y1 = level.top, # lty = 3, lwd = .75) add.level.fun("mcu", ok.val = .75, max.val = 1, min.val = 0, level.type = level.type) #, sub = paste(c(final.stats$cr, "/", final.stats$cr + final.stats$fa), collapse = "")) add.level.fun("pci", ok.val = .75, level.type = level.type) #, sub = paste(c(final.stats$cr, "/", final.stats$cr + final.stats$fa), collapse = "")) # text(lloc$center.x[lloc$element == "pci"], # lloc$center.y[lloc$element == "pci"], # labels = paste0("mcu\n", round(mcu, 2))) add.level.fun("spec", ok.val = .75, level.type = level.type) #, sub = paste(c(final.stats$cr, "/", final.stats$cr + final.stats$fa), collapse = "")) add.level.fun("sens", ok.val = .75, level.type = level.type) #, sub = paste(c(final.stats$hi, "/", final.stats$hi + final.stats$mi), collapse = "")) # Min acc min.acc <- max(crit.br, 1 - crit.br) add.level.fun("acc", min.val = 0, ok.val = .5, level.type = level.type) #, sub = paste(c(final.stats$hi + final.stats$cr, "/", final.stats$n), collapse = "")) # Add baseline to acc level segments(x0 = lloc$center.x[lloc$element == "acc"] - lloc$width[lloc$element == "acc"] / 2, y0 = (lloc$center.y[lloc$element == "acc"] - lloc$height[lloc$element == "acc"] / 2) + lloc$height[lloc$element == "acc"] * min.acc, x1 = lloc$center.x[lloc$element == "acc"] + lloc$width[lloc$element == "acc"] / 2, y1 = (lloc$center.y[lloc$element == "acc"] - lloc$height[lloc$element == "acc"] / 2) + lloc$height[lloc$element == "acc"] * min.acc, lty = 3) text(x = lloc$center.x[lloc$element == "acc"], y =(lloc$center.y[lloc$element == "acc"] - lloc$height[lloc$element == "acc"] / 2) + lloc$height[lloc$element == "acc"] * min.acc, labels = "BL", pos = 1) # paste("BL = ", pretty.dec(min.acc), sep = ""), pos = 1) add.level.fun("bacc", min.val = 0, max.val = 1, ok.val = .5, level.type = level.type) # baseline # segments(x0 = mean(lloc$center.x[2]), # y0 = lloc$center.y[1] - lloc$height[1] / 2, # x1 = mean(lloc$center.x[7]), # y1 = lloc$center.y[1] - lloc$height[1] / 2, lend = 1, # lwd = .5, # col = gray(0)) } } # MiniROC if(show.roc) { text(lloc$center.x[lloc$element == "roc"], header.y.loc, "ROC", pos = 1, cex = header.cex) # text(final.roc.center[1], subheader.y.loc, paste("AUC =", round(final.auc, 2)), pos = 1) final.roc.x.loc <- c(lloc$center.x[lloc$element == "roc"] - lloc$width[lloc$element == "roc"] / 2,lloc$center.x[lloc$element == "roc"] + lloc$width[lloc$element == "roc"] / 2) final.roc.y.loc <- c(lloc$center.y[lloc$element == "roc"] - lloc$height[lloc$element == "roc"] / 2,lloc$center.y[lloc$element == "roc"] + lloc$height[lloc$element == "roc"] / 2) # Plot bg # # rect(final.roc.x.loc[1], # final.roc.y.loc[1], # final.roc.x.loc[2], # final.roc.y.loc[2], # col = gray(1), lwd = .5) # Gridlines # # Horizontal # segments(x0 = rep(final.roc.x.loc[1], 9), # y0 = seq(final.roc.y.loc[1], final.roc.y.loc[2], length.out = 5)[2:10], # x1 = rep(final.roc.x.loc[2], 9), # y1 = seq(final.roc.y.loc[1], final.roc.y.loc[2], length.out = 5)[2:10], # lty = 1, col = gray(.8), lwd = c(.5), lend = 3 # ) # # # Vertical # segments(y0 = rep(final.roc.y.loc[1], 9), # x0 = seq(final.roc.x.loc[1], final.roc.x.loc[2], length.out = 5)[2:10], # y1 = rep(final.roc.y.loc[2], 9), # x1 = seq(final.roc.x.loc[1], final.roc.x.loc[2], length.out = 5)[2:10], # lty = 1, col = gray(.8), lwd = c(.5), lend = 3 # ) # Plot border rect(final.roc.x.loc[1], final.roc.y.loc[1], final.roc.x.loc[2], final.roc.y.loc[2], border = roc.border.col, lwd = roc.lwd) # Axis labels text(c(final.roc.x.loc[1], final.roc.x.loc[2]), c(final.roc.y.loc[1], final.roc.y.loc[1]) - .05, labels = c(0, 1)) text(c(final.roc.x.loc[1], final.roc.x.loc[1], final.roc.x.loc[1]) - .02, c(final.roc.y.loc[1], mean(final.roc.y.loc[1:2]), final.roc.y.loc[2]), labels = c(0,.5, 1)) text(mean(final.roc.x.loc), final.roc.y.loc[1] - .08, "1 - Specificity (FAR)") text(final.roc.x.loc[1] - .04, mean(final.roc.y.loc), "Sensitivity (HR)", srt = 90) # Diagonal segments(final.roc.x.loc[1], final.roc.y.loc[1], final.roc.x.loc[2], final.roc.y.loc[2], lty = 3) label.loc <- c(.1, .3, .5, .7, .9) ## COMPETITIVE ALGORITHMS if(comp == TRUE) { # CART if(is.null(x$comp$cart$results) == FALSE) { cart.spec <- x$comp$cart$results[[data]]$spec cart.sens <- x$comp$cart$results[[data]]$sens points(final.roc.x.loc[1] + (1 - cart.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + cart.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("red", .1), bg = yarrr::transparent("red", .9), lwd = 1) points(final.roc.x.loc[1] + (1 - cart.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + cart.sens * lloc$height[lloc$element == "roc"], pch = "C", cex = .7, col = gray(.2), lwd = 1) par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[4] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("red", .1), bg = yarrr::transparent("red", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[4] * lloc$height[lloc$element == "roc"], pch = "C", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[4] * lloc$height[lloc$element == "roc"], labels = " CART", adj = 0, cex = .9) par("xpd" = TRUE) } ## LR if(is.null(x$comp$lr$results) == FALSE) { lr.spec <- x$comp$lr$results[[data]]$spec lr.sens <- x$comp$lr$results[[data]]$sens points(final.roc.x.loc[1] + (1 - lr.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + lr.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("blue", .1), bg = yarrr::transparent("blue", .9)) points(final.roc.x.loc[1] + (1 - lr.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + lr.sens * lloc$height[lloc$element == "roc"], pch = "L", cex = .7, col = gray(.2)) par("xpd" = F) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[3] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("blue", .1), bg = yarrr::transparent("blue", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[3] * lloc$height[lloc$element == "roc"], pch = "L", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[3] * lloc$height[lloc$element == "roc"], labels = " LR", adj = 0, cex = .9) par("xpd" = T) } ## rf if(is.null(x$comp$rf$results) == FALSE) { rf.spec <- x$comp$rf$results[[data]]$spec rf.sens <- x$comp$rf$results[[data]]$sens points(final.roc.x.loc[1] + (1 - rf.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + rf.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("purple", .1), bg = yarrr::transparent("purple", .9), lwd = 1) points(final.roc.x.loc[1] + (1 - rf.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + rf.sens * lloc$height[lloc$element == "roc"], pch = "C", cex = .7, col = gray(.2), lwd = 1) par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[2] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("purple", .1), bg = yarrr::transparent("purple", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[2] * lloc$height[lloc$element == "roc"], pch = "R", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[2] * lloc$height[lloc$element == "roc"], labels = " RF", adj = 0, cex = .9) par("xpd" = TRUE) } ## svm ## svm if(is.null(x$comp$svm$results) == FALSE) { svm.spec <- x$comp$svm$results[[data]]$spec svm.sens <- x$comp$svm$results[[data]]$sens points(final.roc.x.loc[1] + (1 - svm.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + svm.sens * lloc$height[lloc$element == "roc"], pch = 21, cex = 1.75, col = yarrr::transparent("orange", .1), bg = yarrr::transparent("orange", .9), lwd = 1) points(final.roc.x.loc[1] + (1 - svm.spec) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + svm.sens * lloc$height[lloc$element == "roc"], pch = "C", cex = .7, col = gray(.2), lwd = 1) par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[1] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("orange", .1), bg = yarrr::transparent("orange", .9)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[1] * lloc$height[lloc$element == "roc"], pch = "S", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[1] * lloc$height[lloc$element == "roc"], labels = " SVM", adj = 0, cex = .9) par("xpd" = TRUE) } } ## FFT { roc.order <- order(fft.spec.vec, decreasing = TRUE) # roc.order <- 1:x$trees$n fft.sens.vec.ord <- fft.sens.vec[roc.order] fft.spec.vec.ord <- fft.spec.vec[roc.order] # Add segments and points for all trees but tree if(length(roc.order) > 1) { segments(final.roc.x.loc[1] + c(0, 1 - fft.spec.vec.ord) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + c(0, fft.sens.vec.ord) * lloc$height[lloc$element == "roc"], final.roc.x.loc[1] + c(1 - fft.spec.vec.ord, 1) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + c(fft.sens.vec.ord, 1) * lloc$height[lloc$element == "roc"], lwd = 1, col = gray(0)) points(final.roc.x.loc[1] + (1 - fft.spec.vec.ord[-(which(roc.order == tree))]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec.ord[-(which(roc.order == tree))] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("green", .3), bg = yarrr::transparent("white", .1)) text(final.roc.x.loc[1] + (1 - fft.spec.vec.ord[-(which(roc.order == tree))]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec.ord[-(which(roc.order == tree))] * lloc$height[lloc$element == "roc"], labels = roc.order[which(roc.order != tree)], cex = 1, col = gray(.2)) } # Add large point for plotted tree points(final.roc.x.loc[1] + (1 - fft.spec.vec[tree]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec[tree] * lloc$height[lloc$element == "roc"], pch = 21, cex = 3, col = gray(1), #col = yarrr::transparent("green", .3), bg = yarrr::transparent("green", .3), lwd = 1) text(final.roc.x.loc[1] + (1 - fft.spec.vec[tree]) * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + fft.sens.vec[tree] * lloc$height[lloc$element == "roc"], labels = tree, cex = 1.25, col = gray(.2), font = 2) # Labels if(comp == TRUE & any(is.null(x$comp$lr$results) == FALSE, is.null(x$comp$cart$results) == FALSE, is.null(x$comp$svm$results) == FALSE, is.null(x$comp$rf$results) == FALSE )) { par("xpd" = FALSE) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[5] * lloc$height[lloc$element == "roc"], pch = 21, cex = 2.5, col = yarrr::transparent("green", .3), bg = yarrr::transparent("green", .7)) points(final.roc.x.loc[1] + 1.1 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[5] * lloc$height[lloc$element == "roc"], pch = "#", cex = .9, col = gray(.2)) text(final.roc.x.loc[1] + 1.13 * lloc$width[lloc$element == "roc"], final.roc.y.loc[1] + label.loc[5] * lloc$height[lloc$element == "roc"], labels = " FFT", adj = 0, cex = .9) par("xpd" = TRUE) } } } } } # Reset plotting space par(mfrow = c(1, 1)) par(mar = c(5, 4, 4, 1) + .1) } }
if(FALSE) { getIfValue(findIfInFun(foo)[[1]]) i = findIfInFun(foo)[[1]] } foo = function(x) { y = 2 if(length(x)) y = y + 3 else y = 10 y } foo2 = function(x) { y = 2L names(y) = "a" y[2] = 11 # changes to numeric. if(length(x)) y = y + 3 else y = 10 y } bar = function(x) { if(length(x)) x + 3 else 10 }
/explorations/ifAnalysis/egIf.R
no_license
duncantl/CodeAnalysis
R
false
false
415
r
if(FALSE) { getIfValue(findIfInFun(foo)[[1]]) i = findIfInFun(foo)[[1]] } foo = function(x) { y = 2 if(length(x)) y = y + 3 else y = 10 y } foo2 = function(x) { y = 2L names(y) = "a" y[2] = 11 # changes to numeric. if(length(x)) y = y + 3 else y = 10 y } bar = function(x) { if(length(x)) x + 3 else 10 }
# --- # title: "1" # objective: "Function as tangents" # author: "Daniel Resende" # date: "January 24, 2015" # output: html_document # --- # Always loads source('~/workspace/math/constants.R') cat("\014") # Chart pallete <- c('1B305D', '32557B', 'A59750', '6B7D31', '3B461B') pallete <- paste('#', pallete, sep='') gray <- '#000000' # Function f <- function(x) { (-4/3*x^2 - 2*x + 5) * sin(x) } xDomain <- seq(-4, 4, by=.02) # yDomain <- range(y) xRange <- range(xDomain) # yRange <- yDomain par(mfrow=c(1,1)) curve(f, xlim=xRange, n=201, main="Tangents: x^3 + x^2 - x") abline(h = 0, v = 0, col = "gray30") # png("derivatives.png", width=960, height=590) x <- sapply(xDomain, function(x, n=.1) { slope <- (f(x + n) - f(x - n)) / (2*n) intercept <- f(x) - slope*x abline(a=intercept, b=slope, col=gray) }) # dev.off()
/002-drawing-tangents/main.R
no_license
resendedaniel/math2
R
false
false
841
r
# --- # title: "1" # objective: "Function as tangents" # author: "Daniel Resende" # date: "January 24, 2015" # output: html_document # --- # Always loads source('~/workspace/math/constants.R') cat("\014") # Chart pallete <- c('1B305D', '32557B', 'A59750', '6B7D31', '3B461B') pallete <- paste('#', pallete, sep='') gray <- '#000000' # Function f <- function(x) { (-4/3*x^2 - 2*x + 5) * sin(x) } xDomain <- seq(-4, 4, by=.02) # yDomain <- range(y) xRange <- range(xDomain) # yRange <- yDomain par(mfrow=c(1,1)) curve(f, xlim=xRange, n=201, main="Tangents: x^3 + x^2 - x") abline(h = 0, v = 0, col = "gray30") # png("derivatives.png", width=960, height=590) x <- sapply(xDomain, function(x, n=.1) { slope <- (f(x + n) - f(x - n)) / (2*n) intercept <- f(x) - slope*x abline(a=intercept, b=slope, col=gray) }) # dev.off()
#source("http://bioconductor.org/biocLite.R") #biocLite("ShortRead") library(reshape) library(stringr) library(plyr) library(ShortRead) require(RMySQL) session <- dbConnect(MySQL(), host="XXX", db="YYY",user="ZZZ", password="QQQ") reads=readFastq("reads.out.fq") filenames=list.files(".",pattern="*.table") samples=str_extract(filenames, "^(.*?)\\.") samples=str_replace_all(samples,"R\\d|_|_\\d|\\.","") classes_files=cbind(samples,filenames) get_reads = function(row){ sample = row[1] filename = row[2] if( file.info(filename)$size < 10 ){ print(paste("! Skipping",sample, filename)) NA }else{ print(paste(sample, filename)) dat=read.table(filename,as.is=T) dat=cbind(rep(sample,length(dat$V1)),dat) names(dat) = c("sample","read_id","reference","identity","score") dat=data.frame(lapply(dat, as.character), stringsAsFactors=FALSE) dat$identity=as.numeric(dat$identity) dat$score=as.numeric(dat$score) dat } } dd=get_reads(classes_files[1,]) for(i in c(2:(length(classes_files[,1])))){ row=classes_files[i,] tmp=get_reads(row) if(is.data.frame(tmp)){ dd=rbind(dd,get_reads(row)) } } ids=as.vector(reads@id) ids=str_replace_all(str_extract(ids, "^(.*?)\\t"), "\\t","") seqs=as.vector(as.character(reads@sread)) rr=data.frame(read_id=ids,sequence=seqs, stringsAsFactors=FALSE) res=merge(dd,rr,by=c("read_id"),all=T) write.table(res,file="merA.csv", quote=T, col.names=T, row.names=F, sep="\t") # saving the table # session <- dbConnect(MySQL(), host="test-mysql.toulouse.inra.fr", db="funnymat",user="funnymat", password="XXX") # sql_load_table2=cbind(dd$sample,dd$read_id,dd$reference,dd$identity,dd$score) write.table(sql_load_table2,file="merA.load2.txt", quote=F, col.names=F, row.names=F, sep="\t") #LOAD DATA LOCAL INFILE '/work/psenin/fm/KEGG_works/marisol/merB/merB.load2.txt' INTO table merB_hits FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'; # # sql_load_table1=unique(cbind(dd$reference)) sql_load_table1=cbind(seq(1:length(sql_load_table1)),sql_load_table1) write.table(sql_load_table1,file="merB.load1.txt", quote=F, col.names=F, row.names=F, sep="\t") #LOAD DATA LOCAL INFILE '/work/psenin/fm/KEGG_works/marisol/merB/merB.load1.txt' INTO table merB FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'; references <- dbGetQuery(session, "select distinct(name) from merA") samples <- dbGetQuery(session, "select distinct(tag) from merA_hits") grid <- expand.grid(sample=as.character(unlist(samples)), reference=as.character(unlist(references))) grid <- cbind(as.character(grid$sample), as.character(grid$reference)) sample_summary = function(X) { sample = X[1] reference = X[2] res = dbGetQuery(session, paste("select count(*) from merA_hits where tag=",shQuote(sample), " AND subject_id=",shQuote(reference),";",sep="")) as.numeric(res) } dd=apply(grid,1,sample_summary) res=data.frame(sample=grid[,1],col=grid[,2],value=as.numeric(dd),stringsAsFactors=F) ft=cast(res,col~sample) names(ft)=c("reference",as.character(unlist(samples))) write.table(ft,file="merA_table.csv", quote=F, col.names=T, row.names=F, sep="\t")
/RCode/merA.R
no_license
seninp-bioinfo/jKEGG
R
false
false
3,137
r
#source("http://bioconductor.org/biocLite.R") #biocLite("ShortRead") library(reshape) library(stringr) library(plyr) library(ShortRead) require(RMySQL) session <- dbConnect(MySQL(), host="XXX", db="YYY",user="ZZZ", password="QQQ") reads=readFastq("reads.out.fq") filenames=list.files(".",pattern="*.table") samples=str_extract(filenames, "^(.*?)\\.") samples=str_replace_all(samples,"R\\d|_|_\\d|\\.","") classes_files=cbind(samples,filenames) get_reads = function(row){ sample = row[1] filename = row[2] if( file.info(filename)$size < 10 ){ print(paste("! Skipping",sample, filename)) NA }else{ print(paste(sample, filename)) dat=read.table(filename,as.is=T) dat=cbind(rep(sample,length(dat$V1)),dat) names(dat) = c("sample","read_id","reference","identity","score") dat=data.frame(lapply(dat, as.character), stringsAsFactors=FALSE) dat$identity=as.numeric(dat$identity) dat$score=as.numeric(dat$score) dat } } dd=get_reads(classes_files[1,]) for(i in c(2:(length(classes_files[,1])))){ row=classes_files[i,] tmp=get_reads(row) if(is.data.frame(tmp)){ dd=rbind(dd,get_reads(row)) } } ids=as.vector(reads@id) ids=str_replace_all(str_extract(ids, "^(.*?)\\t"), "\\t","") seqs=as.vector(as.character(reads@sread)) rr=data.frame(read_id=ids,sequence=seqs, stringsAsFactors=FALSE) res=merge(dd,rr,by=c("read_id"),all=T) write.table(res,file="merA.csv", quote=T, col.names=T, row.names=F, sep="\t") # saving the table # session <- dbConnect(MySQL(), host="test-mysql.toulouse.inra.fr", db="funnymat",user="funnymat", password="XXX") # sql_load_table2=cbind(dd$sample,dd$read_id,dd$reference,dd$identity,dd$score) write.table(sql_load_table2,file="merA.load2.txt", quote=F, col.names=F, row.names=F, sep="\t") #LOAD DATA LOCAL INFILE '/work/psenin/fm/KEGG_works/marisol/merB/merB.load2.txt' INTO table merB_hits FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'; # # sql_load_table1=unique(cbind(dd$reference)) sql_load_table1=cbind(seq(1:length(sql_load_table1)),sql_load_table1) write.table(sql_load_table1,file="merB.load1.txt", quote=F, col.names=F, row.names=F, sep="\t") #LOAD DATA LOCAL INFILE '/work/psenin/fm/KEGG_works/marisol/merB/merB.load1.txt' INTO table merB FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'; references <- dbGetQuery(session, "select distinct(name) from merA") samples <- dbGetQuery(session, "select distinct(tag) from merA_hits") grid <- expand.grid(sample=as.character(unlist(samples)), reference=as.character(unlist(references))) grid <- cbind(as.character(grid$sample), as.character(grid$reference)) sample_summary = function(X) { sample = X[1] reference = X[2] res = dbGetQuery(session, paste("select count(*) from merA_hits where tag=",shQuote(sample), " AND subject_id=",shQuote(reference),";",sep="")) as.numeric(res) } dd=apply(grid,1,sample_summary) res=data.frame(sample=grid[,1],col=grid[,2],value=as.numeric(dd),stringsAsFactors=F) ft=cast(res,col~sample) names(ft)=c("reference",as.character(unlist(samples))) write.table(ft,file="merA_table.csv", quote=F, col.names=T, row.names=F, sep="\t")
library(testthat) library(TimeWindowMaker2) test_check("TimeWindowMaker2")
/tests/testthat.R
no_license
itsaquestion/TimeWindowMaker2
R
false
false
76
r
library(testthat) library(TimeWindowMaker2) test_check("TimeWindowMaker2")
#' Change the absolute path of a file #' #' \code{convertPaths} is simply a wrapper around \code{gsub} for changing the #' first part of a path. #' \code{convertRasterPaths} is useful for changing the path to a file-backed #' raster (e.g., after copying the file to a new location). #' #' @param x For \code{convertPaths}, a character vector of file paths. #' For \code{convertRasterPaths}, a disk-backed \code{RasterLayer} #' object, or a list of such rasters. #' @param patterns Character vector containing a pattern to match (see \code{?gsub}). #' @param replacements Character vector of the same length of \code{patterns} #' containing replacement text (see \code{?gsub}). #' #' @author Eliot McIntire and Alex Chubaty #' @export #' @rdname convertPaths #' #' @examples #' filenames <- c("/home/user1/Documents/file.txt", "/Users/user1/Documents/file.txt") #' oldPaths <- dirname(filenames) #' newPaths <- c("/home/user2/Desktop", "/Users/user2/Desktop") #' convertPaths(filenames, oldPaths, newPaths) #' #' r1 <- raster::raster(system.file("external/test.grd", package = "raster")) #' r2 <- raster::raster(system.file("external/rlogo.grd", package = "raster")) #' rasters <- list(r1, r2) #' oldPaths <- system.file("external", package = "raster") #' newPaths <- file.path("~/rasters") #' rasters <- convertRasterPaths(rasters, oldPaths, newPaths) #' lapply(rasters, raster::filename) #' convertPaths <- function(x, patterns, replacements) { stopifnot(is(x, "character")) stopifnot(length(patterns) == length(replacements)) patterns <- normPath(patterns) replacements <- normPath(replacements) x <- normPath(x) for (i in seq_along(patterns)) { x <- gsub(x = x, pattern = patterns[i], replacement = replacements[i]) } normPath(x) } #' @author Eliot McIntire and Alex Chubaty #' @export #' @importFrom raster filename raster #' @rdname convertPaths convertRasterPaths <- function(x, patterns, replacements) { if (is.list(x)) { x <- lapply(x, convertRasterPaths, patterns, replacements) } else if (!is.null(x)) { if (is.character(x)) { if (length(x) > 1) { x <- lapply(x, convertRasterPaths, patterns, replacements) } else { x <- raster(x) } } x@file@name <- convertPaths(filename(x), patterns, replacements) } x # handles null case } #' Return the filename(s) from a \code{Raster*} object #' #' This is mostly just a wrapper around \code{filename} from the \pkg{raster} package, except that #' instead of returning an empty string for a \code{RasterStack} object, it will return a vector of #' length >1 for \code{RasterStack}. #' #' @param obj A \code{Raster*} object (i.e., \code{RasterLayer}, \code{RasterStack}, \code{RasterBrick}) #' @param allowMultiple Logical. If \code{TRUE}, the default, then all relevant #' filenames will be returned, i.e., in cases such as \code{.grd} where multiple files #' are required. If \code{FALSE}, then only the first file will be returned, #' e.g., \code{filename.grd}, in the case of default Raster format in R. #' #' @author Eliot McIntire #' @export #' @rdname Filenames setGeneric("Filenames", function(obj, allowMultiple = TRUE) { standardGeneric("Filenames") }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "ANY", definition = function(obj, allowMultiple) { NULL }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "Raster", definition = function(obj, allowMultiple = TRUE) { fn <- filename(obj) browser(expr = exists("._Filenames_1")) if (isTRUE(allowMultiple)) if (endsWith(fn, suffix = "grd")) fn <- c(fn, gsub("grd$", "gri", fn)) normPath(fn) }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "RasterStack", definition = function(obj, allowMultiple = TRUE) { fn <- unlist(lapply(seq_along(names(obj)), function(index) Filenames(obj[[index]], allowMultiple = allowMultiple))) dups <- duplicated(fn) if (any(dups)) { theNames <- names(fn) fn <- fn[!dups] names(fn) <- theNames[!dups] } return(fn) }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "environment", definition = function(obj, allowMultiple = TRUE) { rastersLogical <- isOrHasRaster(obj) rasterFilename <- NULL if (any(rastersLogical)) { rasterNames <- names(rastersLogical)[rastersLogical] if (!is.null(rasterNames)) { no <- names(obj); names(no) <- no; nestedOnes <- lapply(no, function(rn) grep(paste0("^", rn, "\\."), rasterNames, value = TRUE)) nestedOnes1 <- nestedOnes[sapply(nestedOnes, function(x) length(x) > 0)] nonNested <- nestedOnes[sapply(nestedOnes, function(x) length(x) == 0)] nonNestedRasterNames <- rasterNames[rasterNames %in% names(nonNested)] diskBacked <- sapply(mget(nonNestedRasterNames, envir = obj), fromDisk) names(rasterNames) <- rasterNames rasterFilename <- if (sum(diskBacked) > 0) { lapply(mget(rasterNames[diskBacked], envir = obj), Filenames, allowMultiple = allowMultiple) } else { NULL } if (length(nestedOnes1) > 0) { rasterFilename2 <- sapply(mget(names(nestedOnes1), envir = obj), Filenames, allowMultiple = allowMultiple) rasterFilename <- c(rasterFilename, rasterFilename2) } } } rasterFilenameDups <- lapply(rasterFilename, duplicated) rasterFilename <- lapply(names(rasterFilenameDups), function(nam) rasterFilename[[nam]][!rasterFilenameDups[[nam]]]) return(rasterFilename) }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "list", definition = function(obj, allowMultiple = TRUE) { ## convert a list to an environment -- this is to align it with a simList and environment Filenames(as.environment(obj), allowMultiple = allowMultiple) })
/R/convertPaths.R
no_license
mdsumner/reproducible
R
false
false
6,066
r
#' Change the absolute path of a file #' #' \code{convertPaths} is simply a wrapper around \code{gsub} for changing the #' first part of a path. #' \code{convertRasterPaths} is useful for changing the path to a file-backed #' raster (e.g., after copying the file to a new location). #' #' @param x For \code{convertPaths}, a character vector of file paths. #' For \code{convertRasterPaths}, a disk-backed \code{RasterLayer} #' object, or a list of such rasters. #' @param patterns Character vector containing a pattern to match (see \code{?gsub}). #' @param replacements Character vector of the same length of \code{patterns} #' containing replacement text (see \code{?gsub}). #' #' @author Eliot McIntire and Alex Chubaty #' @export #' @rdname convertPaths #' #' @examples #' filenames <- c("/home/user1/Documents/file.txt", "/Users/user1/Documents/file.txt") #' oldPaths <- dirname(filenames) #' newPaths <- c("/home/user2/Desktop", "/Users/user2/Desktop") #' convertPaths(filenames, oldPaths, newPaths) #' #' r1 <- raster::raster(system.file("external/test.grd", package = "raster")) #' r2 <- raster::raster(system.file("external/rlogo.grd", package = "raster")) #' rasters <- list(r1, r2) #' oldPaths <- system.file("external", package = "raster") #' newPaths <- file.path("~/rasters") #' rasters <- convertRasterPaths(rasters, oldPaths, newPaths) #' lapply(rasters, raster::filename) #' convertPaths <- function(x, patterns, replacements) { stopifnot(is(x, "character")) stopifnot(length(patterns) == length(replacements)) patterns <- normPath(patterns) replacements <- normPath(replacements) x <- normPath(x) for (i in seq_along(patterns)) { x <- gsub(x = x, pattern = patterns[i], replacement = replacements[i]) } normPath(x) } #' @author Eliot McIntire and Alex Chubaty #' @export #' @importFrom raster filename raster #' @rdname convertPaths convertRasterPaths <- function(x, patterns, replacements) { if (is.list(x)) { x <- lapply(x, convertRasterPaths, patterns, replacements) } else if (!is.null(x)) { if (is.character(x)) { if (length(x) > 1) { x <- lapply(x, convertRasterPaths, patterns, replacements) } else { x <- raster(x) } } x@file@name <- convertPaths(filename(x), patterns, replacements) } x # handles null case } #' Return the filename(s) from a \code{Raster*} object #' #' This is mostly just a wrapper around \code{filename} from the \pkg{raster} package, except that #' instead of returning an empty string for a \code{RasterStack} object, it will return a vector of #' length >1 for \code{RasterStack}. #' #' @param obj A \code{Raster*} object (i.e., \code{RasterLayer}, \code{RasterStack}, \code{RasterBrick}) #' @param allowMultiple Logical. If \code{TRUE}, the default, then all relevant #' filenames will be returned, i.e., in cases such as \code{.grd} where multiple files #' are required. If \code{FALSE}, then only the first file will be returned, #' e.g., \code{filename.grd}, in the case of default Raster format in R. #' #' @author Eliot McIntire #' @export #' @rdname Filenames setGeneric("Filenames", function(obj, allowMultiple = TRUE) { standardGeneric("Filenames") }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "ANY", definition = function(obj, allowMultiple) { NULL }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "Raster", definition = function(obj, allowMultiple = TRUE) { fn <- filename(obj) browser(expr = exists("._Filenames_1")) if (isTRUE(allowMultiple)) if (endsWith(fn, suffix = "grd")) fn <- c(fn, gsub("grd$", "gri", fn)) normPath(fn) }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "RasterStack", definition = function(obj, allowMultiple = TRUE) { fn <- unlist(lapply(seq_along(names(obj)), function(index) Filenames(obj[[index]], allowMultiple = allowMultiple))) dups <- duplicated(fn) if (any(dups)) { theNames <- names(fn) fn <- fn[!dups] names(fn) <- theNames[!dups] } return(fn) }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "environment", definition = function(obj, allowMultiple = TRUE) { rastersLogical <- isOrHasRaster(obj) rasterFilename <- NULL if (any(rastersLogical)) { rasterNames <- names(rastersLogical)[rastersLogical] if (!is.null(rasterNames)) { no <- names(obj); names(no) <- no; nestedOnes <- lapply(no, function(rn) grep(paste0("^", rn, "\\."), rasterNames, value = TRUE)) nestedOnes1 <- nestedOnes[sapply(nestedOnes, function(x) length(x) > 0)] nonNested <- nestedOnes[sapply(nestedOnes, function(x) length(x) == 0)] nonNestedRasterNames <- rasterNames[rasterNames %in% names(nonNested)] diskBacked <- sapply(mget(nonNestedRasterNames, envir = obj), fromDisk) names(rasterNames) <- rasterNames rasterFilename <- if (sum(diskBacked) > 0) { lapply(mget(rasterNames[diskBacked], envir = obj), Filenames, allowMultiple = allowMultiple) } else { NULL } if (length(nestedOnes1) > 0) { rasterFilename2 <- sapply(mget(names(nestedOnes1), envir = obj), Filenames, allowMultiple = allowMultiple) rasterFilename <- c(rasterFilename, rasterFilename2) } } } rasterFilenameDups <- lapply(rasterFilename, duplicated) rasterFilename <- lapply(names(rasterFilenameDups), function(nam) rasterFilename[[nam]][!rasterFilenameDups[[nam]]]) return(rasterFilename) }) #' @export #' @rdname Filenames setMethod( "Filenames", signature = "list", definition = function(obj, allowMultiple = TRUE) { ## convert a list to an environment -- this is to align it with a simList and environment Filenames(as.environment(obj), allowMultiple = allowMultiple) })
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bar.R \name{bar} \alias{bar} \title{Bar Plot data file} \usage{ bar(data, map, value = c("count", "identity")) } \arguments{ \item{data}{data.frame to make plot-ready data for} \item{map}{data.frame with at least two columns (id, plotRef) indicating a variable sourceId and its position in the plot} \item{value}{String indicating how to calculate y-values ('identity', 'count')} } \value{ character name of json file containing plot-ready data } \description{ This function returns the name of a json file containing plot-ready data with one row per group (per panel). Columns 'label' and 'value' contain the raw data for plotting. Column 'group' and 'panel' specify the group the series data belongs to. There are two options to calculate y-values for plotting. 1) raw 'identity' of values from data.table input 2) 'count' occurances of values from data.table input }
/man/bar.Rd
no_license
d-callan/plot.data
R
false
true
953
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bar.R \name{bar} \alias{bar} \title{Bar Plot data file} \usage{ bar(data, map, value = c("count", "identity")) } \arguments{ \item{data}{data.frame to make plot-ready data for} \item{map}{data.frame with at least two columns (id, plotRef) indicating a variable sourceId and its position in the plot} \item{value}{String indicating how to calculate y-values ('identity', 'count')} } \value{ character name of json file containing plot-ready data } \description{ This function returns the name of a json file containing plot-ready data with one row per group (per panel). Columns 'label' and 'value' contain the raw data for plotting. Column 'group' and 'panel' specify the group the series data belongs to. There are two options to calculate y-values for plotting. 1) raw 'identity' of values from data.table input 2) 'count' occurances of values from data.table input }
# Master File library(dplyr) library(ggplot2) library(shiny) library(leaflet) library(mapview) library(rsconnect) library(geojsonio) library(htmltools) library(reshape2) source("code.R") source("EmanHardcode.R") # Define server logic required to draw a histogram shinyServer(function(input, output) { # Home Tab # Map Tab output$mymap <- renderLeaflet({ #You input a state and you get the percentage as an output for speeding, not distracted, alcohol impaired, and not involved in if(input$states == "Speeding") { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Were.Speeding } else if(input$states == "Not distracted") { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Were.Not.Distracted } else if(input$states == "Alcohol impaired") { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Were.Alcohol.Impaired } else { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Had.Not.Been.Involved.In.Any.Previous.Accidents } #For the display of the markers string1 <- paste(strong(span("State:", style = "color:#0083C4")), full_data$State) #String of the state name, "State:" is bold and colored to match the color of the marker string2 <- paste("The percentage is:", states, "%") #String of the percentage of the options for that specific state popup <- paste(sep = "<br/>", string1, string2) #Line break of both strings leaflet(state_data) %>% setView(-96, 37.8, 4) %>% #Lat and long coordinates for the map boundaries addProviderTiles("MapBox", options = providerTileOptions( id = "mapbox.light", #This creates an outline of every state in the United States accessToken = Sys.getenv('pk.eyJ1IjoiaHdhaGVlZWQiLCJhIjoiY2phc21jYnY1NHNibjJxcGxseG9vMzl4cSJ9.xTnmU0DdOSrPePsTnlRdgg'))) %>% addTiles() %>% #Adds the background of all continents, makes it look like an actual map rather than just the outline addPolygons(weight = 2, opacity = 1, color = "black", #Outline adjustments dashArray = "1", fillOpacity = 0.2) %>% addMarkers(data = full_data, lng = full_data$lng, lat = full_data$lat, popup=popup) %>% #The markers placed on the map setView(lng = -95.85, lat = 38.75, zoom = 5) #The boundary that is first displayed when opened }) # Car Insurance Tab output$Information <- renderPlot({ State_Names <- rep(c("Alabama", "California", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Kansas", "Louisiana", "Maine", "Nebraska", "Ohio", "Pennsylvania", "Tennessee", "Utah", "Vermont", "Washington"), 2) Car_Insurance_and_Losses <- rep(c(Specific_States_melt$variable)) Colors <- c(rep("Car Insurance Premiums", 1), rep("Losses incurred by insurance companies for collisions per insured driver", 1)) Insurance_Losses_Data <- data.frame( # create dataframe to select variable states, and costs for ggplot Variable <- factor(c(Car_Insurance_and_Losses)), States <- factor(c(State_Names)), costs <- c(Specific_States_melt$value) ) data <- filter(Insurance_Losses_Data, States == input$State) # filters the specific state in the datatable ggplot(data, aes(x = data$State, y = data$costs, fill = Colors)) + # creates ggplot geom_bar(colour = "Black", stat = "identity", position=position_dodge(), size=.3) + # Thinner lines xlab("Name of State") + ylab("Premium and Losses costs") + # labels the x and y axis ggtitle("Car Insurance Premiums vs Losses incurred by insurance companies for collisions per insured driver") + # Set title theme_dark() # gives dark background }) # Comparision Tab dataPlot <- read.csv(file = 'data/bad-drivers.csv', stringsAsFactors = FALSE) # Change column names of data frame colnames(dataPlot) <- c("State", "Number.Collisions", "Collisions.Speeding", "Collisions.Alcohol", "Collisions.Not.Distracted", "Collisions.No.Previous", "Car.Insurance", "Losses.By.Insurance") # Compute US average of fatal collisions per billion miles usMeanDataFrame <- summarize(dataPlot, mean = mean(Number.Collisions)) usMean <- usMeanDataFrame[1,1] output$higherAverage <- renderPlot({ # filter out data frame for states higher than US mean higherStates <- filter(dataPlot, Number.Collisions > usMean) # draw the histogram with the specified number of bins ggplot(higherStates) + geom_point(aes_string(x = "State", y = input$higherY, color = input$higherColorType)) + ggtitle("Analysis of States Data Higher than US Mean") + theme(axis.text.x=element_text(angle=90,hjust=1)) }) output$lowerAverage <- renderPlot({ # filter out data frame for states lower than US mean lowerStates <- filter(dataPlot, Number.Collisions < usMean) # draw the histogram with the specified number of bins ggplot(lowerStates) + geom_point(aes_string(x = "State", y = input$lowerY, color = input$lowerColorType)) + ggtitle("Analysis of States Data Lower than US Mean") + theme(axis.text.x=element_text(angle=90,hjust=1)) }) })
/server.R
no_license
nehay100/SHENFinalProject
R
false
false
5,450
r
# Master File library(dplyr) library(ggplot2) library(shiny) library(leaflet) library(mapview) library(rsconnect) library(geojsonio) library(htmltools) library(reshape2) source("code.R") source("EmanHardcode.R") # Define server logic required to draw a histogram shinyServer(function(input, output) { # Home Tab # Map Tab output$mymap <- renderLeaflet({ #You input a state and you get the percentage as an output for speeding, not distracted, alcohol impaired, and not involved in if(input$states == "Speeding") { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Were.Speeding } else if(input$states == "Not distracted") { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Were.Not.Distracted } else if(input$states == "Alcohol impaired") { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Were.Alcohol.Impaired } else { states = full_data$Percentage.Of.Drivers.Involved.In.Fatal.Collisions.Who.Had.Not.Been.Involved.In.Any.Previous.Accidents } #For the display of the markers string1 <- paste(strong(span("State:", style = "color:#0083C4")), full_data$State) #String of the state name, "State:" is bold and colored to match the color of the marker string2 <- paste("The percentage is:", states, "%") #String of the percentage of the options for that specific state popup <- paste(sep = "<br/>", string1, string2) #Line break of both strings leaflet(state_data) %>% setView(-96, 37.8, 4) %>% #Lat and long coordinates for the map boundaries addProviderTiles("MapBox", options = providerTileOptions( id = "mapbox.light", #This creates an outline of every state in the United States accessToken = Sys.getenv('pk.eyJ1IjoiaHdhaGVlZWQiLCJhIjoiY2phc21jYnY1NHNibjJxcGxseG9vMzl4cSJ9.xTnmU0DdOSrPePsTnlRdgg'))) %>% addTiles() %>% #Adds the background of all continents, makes it look like an actual map rather than just the outline addPolygons(weight = 2, opacity = 1, color = "black", #Outline adjustments dashArray = "1", fillOpacity = 0.2) %>% addMarkers(data = full_data, lng = full_data$lng, lat = full_data$lat, popup=popup) %>% #The markers placed on the map setView(lng = -95.85, lat = 38.75, zoom = 5) #The boundary that is first displayed when opened }) # Car Insurance Tab output$Information <- renderPlot({ State_Names <- rep(c("Alabama", "California", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Kansas", "Louisiana", "Maine", "Nebraska", "Ohio", "Pennsylvania", "Tennessee", "Utah", "Vermont", "Washington"), 2) Car_Insurance_and_Losses <- rep(c(Specific_States_melt$variable)) Colors <- c(rep("Car Insurance Premiums", 1), rep("Losses incurred by insurance companies for collisions per insured driver", 1)) Insurance_Losses_Data <- data.frame( # create dataframe to select variable states, and costs for ggplot Variable <- factor(c(Car_Insurance_and_Losses)), States <- factor(c(State_Names)), costs <- c(Specific_States_melt$value) ) data <- filter(Insurance_Losses_Data, States == input$State) # filters the specific state in the datatable ggplot(data, aes(x = data$State, y = data$costs, fill = Colors)) + # creates ggplot geom_bar(colour = "Black", stat = "identity", position=position_dodge(), size=.3) + # Thinner lines xlab("Name of State") + ylab("Premium and Losses costs") + # labels the x and y axis ggtitle("Car Insurance Premiums vs Losses incurred by insurance companies for collisions per insured driver") + # Set title theme_dark() # gives dark background }) # Comparision Tab dataPlot <- read.csv(file = 'data/bad-drivers.csv', stringsAsFactors = FALSE) # Change column names of data frame colnames(dataPlot) <- c("State", "Number.Collisions", "Collisions.Speeding", "Collisions.Alcohol", "Collisions.Not.Distracted", "Collisions.No.Previous", "Car.Insurance", "Losses.By.Insurance") # Compute US average of fatal collisions per billion miles usMeanDataFrame <- summarize(dataPlot, mean = mean(Number.Collisions)) usMean <- usMeanDataFrame[1,1] output$higherAverage <- renderPlot({ # filter out data frame for states higher than US mean higherStates <- filter(dataPlot, Number.Collisions > usMean) # draw the histogram with the specified number of bins ggplot(higherStates) + geom_point(aes_string(x = "State", y = input$higherY, color = input$higherColorType)) + ggtitle("Analysis of States Data Higher than US Mean") + theme(axis.text.x=element_text(angle=90,hjust=1)) }) output$lowerAverage <- renderPlot({ # filter out data frame for states lower than US mean lowerStates <- filter(dataPlot, Number.Collisions < usMean) # draw the histogram with the specified number of bins ggplot(lowerStates) + geom_point(aes_string(x = "State", y = input$lowerY, color = input$lowerColorType)) + ggtitle("Analysis of States Data Lower than US Mean") + theme(axis.text.x=element_text(angle=90,hjust=1)) }) })
# Demonstrating side effects x<-1 good <- function() { x <- 5} good() print(x) ## [1] 1 bad <- function() { x <<- 5} bad() print(x) ## [1] 5
/datascience_course/上θͺ²η¨‹εΌη’Ό/week_2/sideEff.R
no_license
bill0812/course_study
R
false
false
141
r
# Demonstrating side effects x<-1 good <- function() { x <- 5} good() print(x) ## [1] 1 bad <- function() { x <<- 5} bad() print(x) ## [1] 5
### ### imomknown.R.R ### imomknown <- function(theta1hat,V1,n,nuisance.theta,g=1,nu=1,theta0,sigma,method='adapt',B=10^5) { if (missing(sigma)) stop('sigma must be specified') if (missing(theta0)) theta0 <- rep(0,length(theta1hat)) f <- function(z) { ans <- (n*gi/z)^((nu+p1)/2) * exp(-n*gi/z); ans[z==0] <- 0; return(ans) } p1 <- length(theta1hat) l <- theta1hat-theta0; l <- matrix(l,nrow=1) %*% solve(V1) %*% matrix(l,ncol=1) / sigma^2 #noncentr param m <- double(length(g)) if (method=='MC') { z <- rchisq(B,df=p1,ncp=l) for (i in 1:length(m)) { gi <- g[i]; m[i] <- mean(f(z)) } } else if (method=='adapt') { f2 <- function(z) { return(f(z)*dchisq(z,df=p1,ncp=l)) } for (i in 1:length(m)) { gi <- g[i]; m[i] <- integrate(f2,0,Inf)$value } } else { stop('method must be adapt or MC') } bf <- exp((p1/2)*log(2/(n*g)) + lgamma(p1/2)-lgamma(nu/2) + .5*l) * m return(bf) }
/mombf/R/imomknown.R
no_license
ingted/R-Examples
R
false
false
886
r
### ### imomknown.R.R ### imomknown <- function(theta1hat,V1,n,nuisance.theta,g=1,nu=1,theta0,sigma,method='adapt',B=10^5) { if (missing(sigma)) stop('sigma must be specified') if (missing(theta0)) theta0 <- rep(0,length(theta1hat)) f <- function(z) { ans <- (n*gi/z)^((nu+p1)/2) * exp(-n*gi/z); ans[z==0] <- 0; return(ans) } p1 <- length(theta1hat) l <- theta1hat-theta0; l <- matrix(l,nrow=1) %*% solve(V1) %*% matrix(l,ncol=1) / sigma^2 #noncentr param m <- double(length(g)) if (method=='MC') { z <- rchisq(B,df=p1,ncp=l) for (i in 1:length(m)) { gi <- g[i]; m[i] <- mean(f(z)) } } else if (method=='adapt') { f2 <- function(z) { return(f(z)*dchisq(z,df=p1,ncp=l)) } for (i in 1:length(m)) { gi <- g[i]; m[i] <- integrate(f2,0,Inf)$value } } else { stop('method must be adapt or MC') } bf <- exp((p1/2)*log(2/(n*g)) + lgamma(p1/2)-lgamma(nu/2) + .5*l) * m return(bf) }
`mu.varknown` <- function(len,lambda,n0,level=0.95) { # Returns the minimal sample size to ensure an average prob. coverage of # 'level' with a symmetric region about the posterior mean # when sampling from a normal distribution with known variance (Adcock, 1988) # Using the same notation as Adcock var <- 1/lambda d <- len/2 m <- n0 m <- ceiling(((qnorm((level+1)/2)/d)^2)*var-m) max(0, m) }
/R/mu.varknown.R
no_license
cran/SampleSizeMeans
R
false
false
435
r
`mu.varknown` <- function(len,lambda,n0,level=0.95) { # Returns the minimal sample size to ensure an average prob. coverage of # 'level' with a symmetric region about the posterior mean # when sampling from a normal distribution with known variance (Adcock, 1988) # Using the same notation as Adcock var <- 1/lambda d <- len/2 m <- n0 m <- ceiling(((qnorm((level+1)/2)/d)^2)*var-m) max(0, m) }
## timestart timediff 2020-06-20 #' @title Collect the difftime between two events #' #' @description #' \code{timestart} starts the timer and saved the value in an object named #' \code{time0} stored in \code{.GlobalEnv}. #' #' \code{timediff} stops the timer, remove the \code{time0} objet from \code{.GlobalEnv} #' and prints the duration in seconds between the two events. #' #' \code{timestart} and \code{timediff} are fully independant from the R6 class #' \code{timeR} and the objects \code{createTimer} or \code{getTimer}. They use #' \code{\link{proc.time}} instead. #' #' @return #' A single numeric value that represents a duration in seconds. #' #' @examples #' timestart() #' Sys.sleep(2) #' timediff() #' #' @export #' @name timestart timestart <- function() { gc(FALSE) time0 <- proc.time()["elapsed"] time0 <<- time0 } #' @export #' @rdname timestart timediff <- function() { t1 <- proc.time()["elapsed"] t0 <- get("time0", envir = .GlobalEnv) # remove("time0", envir = .GlobalEnv) time0 <- NA time0 <<- time0 unname(t1 - t0) }
/R/timestart-timediff.R
no_license
cran/NNbenchmark
R
false
false
1,137
r
## timestart timediff 2020-06-20 #' @title Collect the difftime between two events #' #' @description #' \code{timestart} starts the timer and saved the value in an object named #' \code{time0} stored in \code{.GlobalEnv}. #' #' \code{timediff} stops the timer, remove the \code{time0} objet from \code{.GlobalEnv} #' and prints the duration in seconds between the two events. #' #' \code{timestart} and \code{timediff} are fully independant from the R6 class #' \code{timeR} and the objects \code{createTimer} or \code{getTimer}. They use #' \code{\link{proc.time}} instead. #' #' @return #' A single numeric value that represents a duration in seconds. #' #' @examples #' timestart() #' Sys.sleep(2) #' timediff() #' #' @export #' @name timestart timestart <- function() { gc(FALSE) time0 <- proc.time()["elapsed"] time0 <<- time0 } #' @export #' @rdname timestart timediff <- function() { t1 <- proc.time()["elapsed"] t0 <- get("time0", envir = .GlobalEnv) # remove("time0", envir = .GlobalEnv) time0 <- NA time0 <<- time0 unname(t1 - t0) }
# Coded by Anderson Borba data: 22/06/2020 version 1.0 # The total log-likelihood presented in equation (X) in the article # Article to appear # XXXXX # Anderson A. de Borba, Maurı́cio Marengoni, and Alejandro C Frery # # - The program reads an image of two halves 400 X 400 (channels hh, hv and vv) finds the parameters (rho) # by the BFGS method, and uses in function l(j) , calculating the point of max/min (edge evidence) by # the GenSA method. # - The output of the program is a 400 size vector with the edge evidence for each line # of the recorded image in a *.txt file # obs: 1) Change the channels in the input and output files. # 2) The code make to run samples in two halves with proposed sigmas in \cite{gamf} (see article). # 3) Disable the print in file after running the tests of interest in order not to modify files unduly. rm(list = ls()) require(ggplot2) require(latex2exp) require(GenSA) require(maxLik) # source("func_obj_l_prod_mag.r") source("loglike_prod_mag.r") source("loglikd_prod_mag.r") source("estima_L.r") # Programa principal setwd("../..") setwd("Data") # canais hh, hv, and vv # canais para a + bi mat1 <- scan('Phantom_gamf_0.000_1_2_1.txt') mat2 <- scan('Phantom_gamf_0.000_1_2_2.txt') mat3 <- scan('Phantom_gamf_0.000_1_2_4.txt') mat4 <- scan('Phantom_gamf_0.000_1_2_5.txt') setwd("..") setwd("Code/Code_art_rem_sen_2020") mat1 <- matrix(mat1, ncol = 400, byrow = TRUE) mat2 <- matrix(mat2, ncol = 400, byrow = TRUE) mat3 <- matrix(mat3, ncol = 400, byrow = TRUE) mat4 <- matrix(mat4, ncol = 400, byrow = TRUE) d <- dim(mat1) nrows <- d[1] ncols <- d[2] # Loop para toda a imagem evidencias <- rep(0, nrows) evidencias_valores <- rep(0, nrows) xev <- seq(1, nrows, 1 ) #L <- 4 #for (k in 1 : nrows){ for (k in 120 : 120){ print(k) N <- ncols z1 <- rep(0, N) z2 <- rep(0, N) z3 <- rep(0, N) z4 <- rep(0, N) zaux1 <- rep(0, N) z1 <- mat1[k,1:N] z2 <- mat2[k,1:N] z3 <- mat3[k,1:N] z4 <- mat4[k,1:N] conta = 0 for (i in 1 : N){ if (z1[i] > 0 && z2[i] > 0){ conta <- conta + 1 zaux1[conta] <- (z3[i]^2 + z4[i]^2)^0.5 / (z1[i] * z2[i])^0.5 } } indx <- which(zaux1 != 0) N <- length(indx) z <- rep(0, N) z[1: N] <- zaux1[1: N] matdf1 <- matrix(0, nrow = N, ncol = 1) matdf2 <- matrix(0, nrow = N, ncol = 1) L <- 4 for (j in 1 : (N - 1)){ r1 <- 0.01 res1 <- maxBFGS(loglike_prod_mag, start=c(r1)) matdf1[j, 1] <- res1$estimate[1] r1 <- 0.01 res2 <- maxBFGS(loglikd_prod_mag, start=c(r1)) matdf2[j, 1] <- res2$estimate[1] } cf <- 14 lower <- as.numeric(cf) upper <- as.numeric(N - cf) out <- GenSA(lower = lower, upper = upper, fn = func_obj_l_prod_mag, control=list(maxit = 100)) evidencias[k] <- out$par print(evidencias[k]) evidencias_valores[k] <- out$value } x <- seq(N - 1) lobj <- rep(0, N - 1) for (j in 1 : (N - 1)){ lobj[j] <- func_obj_l_prod_mag(j) } df <- data.frame(x, lobj) p <- ggplot(df, aes(x = x, y = lobj, color = 'darkred')) + geom_line() + xlab(TeX('Pixel $j$')) + ylab(TeX('$l(j)$')) + guides(color=guide_legend(title=NULL)) + scale_color_discrete(labels= lapply(sprintf('$\\sigma_{hh} = %2.0f$', NULL), TeX)) print(p) # imprime em arquivo no diretorio ~/Data/ #dfev <- data.frame(xev, evidencias) #names(dfev) <- NULL #setwd("../..") #setwd("Data") #sink("evid_real_flevoland_produto_mag_param_L_rho_1_3.txt") #print(dfev) #sink() #setwd("..") #setwd("Code/Code_art_rem_sen_2020")
/Code/Code_art_rem_sen_2020/evidencias_im_sim_param_prod_mag.R
no_license
c-l-k/ufal_mack
R
false
false
3,476
r
# Coded by Anderson Borba data: 22/06/2020 version 1.0 # The total log-likelihood presented in equation (X) in the article # Article to appear # XXXXX # Anderson A. de Borba, Maurı́cio Marengoni, and Alejandro C Frery # # - The program reads an image of two halves 400 X 400 (channels hh, hv and vv) finds the parameters (rho) # by the BFGS method, and uses in function l(j) , calculating the point of max/min (edge evidence) by # the GenSA method. # - The output of the program is a 400 size vector with the edge evidence for each line # of the recorded image in a *.txt file # obs: 1) Change the channels in the input and output files. # 2) The code make to run samples in two halves with proposed sigmas in \cite{gamf} (see article). # 3) Disable the print in file after running the tests of interest in order not to modify files unduly. rm(list = ls()) require(ggplot2) require(latex2exp) require(GenSA) require(maxLik) # source("func_obj_l_prod_mag.r") source("loglike_prod_mag.r") source("loglikd_prod_mag.r") source("estima_L.r") # Programa principal setwd("../..") setwd("Data") # canais hh, hv, and vv # canais para a + bi mat1 <- scan('Phantom_gamf_0.000_1_2_1.txt') mat2 <- scan('Phantom_gamf_0.000_1_2_2.txt') mat3 <- scan('Phantom_gamf_0.000_1_2_4.txt') mat4 <- scan('Phantom_gamf_0.000_1_2_5.txt') setwd("..") setwd("Code/Code_art_rem_sen_2020") mat1 <- matrix(mat1, ncol = 400, byrow = TRUE) mat2 <- matrix(mat2, ncol = 400, byrow = TRUE) mat3 <- matrix(mat3, ncol = 400, byrow = TRUE) mat4 <- matrix(mat4, ncol = 400, byrow = TRUE) d <- dim(mat1) nrows <- d[1] ncols <- d[2] # Loop para toda a imagem evidencias <- rep(0, nrows) evidencias_valores <- rep(0, nrows) xev <- seq(1, nrows, 1 ) #L <- 4 #for (k in 1 : nrows){ for (k in 120 : 120){ print(k) N <- ncols z1 <- rep(0, N) z2 <- rep(0, N) z3 <- rep(0, N) z4 <- rep(0, N) zaux1 <- rep(0, N) z1 <- mat1[k,1:N] z2 <- mat2[k,1:N] z3 <- mat3[k,1:N] z4 <- mat4[k,1:N] conta = 0 for (i in 1 : N){ if (z1[i] > 0 && z2[i] > 0){ conta <- conta + 1 zaux1[conta] <- (z3[i]^2 + z4[i]^2)^0.5 / (z1[i] * z2[i])^0.5 } } indx <- which(zaux1 != 0) N <- length(indx) z <- rep(0, N) z[1: N] <- zaux1[1: N] matdf1 <- matrix(0, nrow = N, ncol = 1) matdf2 <- matrix(0, nrow = N, ncol = 1) L <- 4 for (j in 1 : (N - 1)){ r1 <- 0.01 res1 <- maxBFGS(loglike_prod_mag, start=c(r1)) matdf1[j, 1] <- res1$estimate[1] r1 <- 0.01 res2 <- maxBFGS(loglikd_prod_mag, start=c(r1)) matdf2[j, 1] <- res2$estimate[1] } cf <- 14 lower <- as.numeric(cf) upper <- as.numeric(N - cf) out <- GenSA(lower = lower, upper = upper, fn = func_obj_l_prod_mag, control=list(maxit = 100)) evidencias[k] <- out$par print(evidencias[k]) evidencias_valores[k] <- out$value } x <- seq(N - 1) lobj <- rep(0, N - 1) for (j in 1 : (N - 1)){ lobj[j] <- func_obj_l_prod_mag(j) } df <- data.frame(x, lobj) p <- ggplot(df, aes(x = x, y = lobj, color = 'darkred')) + geom_line() + xlab(TeX('Pixel $j$')) + ylab(TeX('$l(j)$')) + guides(color=guide_legend(title=NULL)) + scale_color_discrete(labels= lapply(sprintf('$\\sigma_{hh} = %2.0f$', NULL), TeX)) print(p) # imprime em arquivo no diretorio ~/Data/ #dfev <- data.frame(xev, evidencias) #names(dfev) <- NULL #setwd("../..") #setwd("Data") #sink("evid_real_flevoland_produto_mag_param_L_rho_1_3.txt") #print(dfev) #sink() #setwd("..") #setwd("Code/Code_art_rem_sen_2020")
library(openxlsx) # This library is used to open xlsx files directly in R library(chron) # This library is used for time manipulation library(data.table) # Used to join rows one after another # file = "Tata.xlsx" # SUS_NO = "9058786086" # imp_row = 4 # raw_sheet = 1 infile = readline(prompt="Input file: ") SUS_NO = readline(prompt="Suspect number: ") imp_row = as.numeric(readline(prompt="Row no. containing headers: ")) raw_sheet = as.numeric(readline(prompt="Raw CDR Sheet number: ")) # Read particular sheet from excel workbook; adjust startRow as per the number of useless rows in the beginnig, remember to remove empty rows df = read.xlsx(xlsxFile=infile, sheet=raw_sheet, startRow=imp_row, colNames=TRUE, detectDates=TRUE, skipEmptyRows=FALSE) df <- df[!is.na(df$DURATION),] # remove useless rows from bottom names(df)[names(df) == 'Calling.No'] <- 'Calling_No' # Do this in case you want to change the header name of a particular column #Do this in case you want to change the names of all columns (more preferable) colnames(df) <- c("Calling_No", "Called_No", "Date", "Time", "Duration", "Cell_1", "Cell_2", "Communication_Type", "IMEI", "IMSI", "Type", "SMSC", "Roam", "Switch", "LRN") drops <- c("Type","SMSC","Switch","LRN") # These are the columns you want that may be removed, change them as per your will df = df[ , !(names(df) %in% drops)] # drop the columns from the dataframe # Make hyphens empty in Cell_1 and Cell_2 columns df$Cell_1[df$Cell_1 == "-"] <- "" df$Cell_2[df$Cell_2 == "-"] <- "" df$Roam[df$Roam == "-"] <- "" df$Time <- times(as.numeric(df$Time)) # Change time from default decimal format to proper HH::MM::SS format # Microsoft Excel date gives some offset, remove it using this and change format to proper DD/MM/YY format df$Date <- format(as.Date(df$Date), "%d/%m/%y") ######################################################################################################################################################## # Create a new dataframe for pivoting according to B_party # This function has two parameters -> x: phone numbers; t: communication type, supplied when calling this function f <- function(x, t) { return (sum( df$Communication_Type[df$Calling_No == x | df$Called_No == x] == t )) } J = rbind(as.matrix(df$Calling_No), as.matrix(df$Called_No)) # all numbers that communicated with our suspect U = as.matrix(unique(J[J != SUS_NO])) # the same in matrix format, to be used in apply function rm(J) # delete temporary J # Gets count of each communication type; MARGIN=1, function is applied for each row of matrix # x1 means first column of X=U SMS_IN_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="SMT")) SMS_OUT_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="SMO")) CALL_IN_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="MTC")) CALL_OUT_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="MOC")) # Total communication count between all B-parties TOTAL_List = SMS_IN_List+SMS_OUT_List+CALL_IN_List+CALL_OUT_List # Create pivot dataframe: B-Party and communication count details df_pivot <- data.frame(U,CALL_IN_List,CALL_OUT_List,SMS_IN_List,SMS_OUT_List,TOTAL_List) colnames(df_pivot) <- c("B_Party", "IN", "OUT", "SMS_IN", "SMS_OUT", "Total") # give column names df_pivot <- df_pivot[order(-df_pivot$Total),] # Note the (-) sign: sort in descending order of total communication # Output pivot details to a file outfile = readline(prompt="Output file: ") sheet = readline(prompt="Sheet name: ") hs <- createStyle(textDecoration = "BOLD", fontColour = "#FFFFFF", fontSize=12, fontName="Arial Narrow", fgFill = "#4F80BD") write.xlsx(x=df_pivot, file=outfile, sheetName = sheet, headerStyle=hs)
/Tata.R
no_license
aakanksha287/Cell-Phone-Theft-problem
R
false
false
3,793
r
library(openxlsx) # This library is used to open xlsx files directly in R library(chron) # This library is used for time manipulation library(data.table) # Used to join rows one after another # file = "Tata.xlsx" # SUS_NO = "9058786086" # imp_row = 4 # raw_sheet = 1 infile = readline(prompt="Input file: ") SUS_NO = readline(prompt="Suspect number: ") imp_row = as.numeric(readline(prompt="Row no. containing headers: ")) raw_sheet = as.numeric(readline(prompt="Raw CDR Sheet number: ")) # Read particular sheet from excel workbook; adjust startRow as per the number of useless rows in the beginnig, remember to remove empty rows df = read.xlsx(xlsxFile=infile, sheet=raw_sheet, startRow=imp_row, colNames=TRUE, detectDates=TRUE, skipEmptyRows=FALSE) df <- df[!is.na(df$DURATION),] # remove useless rows from bottom names(df)[names(df) == 'Calling.No'] <- 'Calling_No' # Do this in case you want to change the header name of a particular column #Do this in case you want to change the names of all columns (more preferable) colnames(df) <- c("Calling_No", "Called_No", "Date", "Time", "Duration", "Cell_1", "Cell_2", "Communication_Type", "IMEI", "IMSI", "Type", "SMSC", "Roam", "Switch", "LRN") drops <- c("Type","SMSC","Switch","LRN") # These are the columns you want that may be removed, change them as per your will df = df[ , !(names(df) %in% drops)] # drop the columns from the dataframe # Make hyphens empty in Cell_1 and Cell_2 columns df$Cell_1[df$Cell_1 == "-"] <- "" df$Cell_2[df$Cell_2 == "-"] <- "" df$Roam[df$Roam == "-"] <- "" df$Time <- times(as.numeric(df$Time)) # Change time from default decimal format to proper HH::MM::SS format # Microsoft Excel date gives some offset, remove it using this and change format to proper DD/MM/YY format df$Date <- format(as.Date(df$Date), "%d/%m/%y") ######################################################################################################################################################## # Create a new dataframe for pivoting according to B_party # This function has two parameters -> x: phone numbers; t: communication type, supplied when calling this function f <- function(x, t) { return (sum( df$Communication_Type[df$Calling_No == x | df$Called_No == x] == t )) } J = rbind(as.matrix(df$Calling_No), as.matrix(df$Called_No)) # all numbers that communicated with our suspect U = as.matrix(unique(J[J != SUS_NO])) # the same in matrix format, to be used in apply function rm(J) # delete temporary J # Gets count of each communication type; MARGIN=1, function is applied for each row of matrix # x1 means first column of X=U SMS_IN_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="SMT")) SMS_OUT_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="SMO")) CALL_IN_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="MTC")) CALL_OUT_List = apply(X=U, MARGIN=1, FUN=function(x1) f(x = x1, t="MOC")) # Total communication count between all B-parties TOTAL_List = SMS_IN_List+SMS_OUT_List+CALL_IN_List+CALL_OUT_List # Create pivot dataframe: B-Party and communication count details df_pivot <- data.frame(U,CALL_IN_List,CALL_OUT_List,SMS_IN_List,SMS_OUT_List,TOTAL_List) colnames(df_pivot) <- c("B_Party", "IN", "OUT", "SMS_IN", "SMS_OUT", "Total") # give column names df_pivot <- df_pivot[order(-df_pivot$Total),] # Note the (-) sign: sort in descending order of total communication # Output pivot details to a file outfile = readline(prompt="Output file: ") sheet = readline(prompt="Sheet name: ") hs <- createStyle(textDecoration = "BOLD", fontColour = "#FFFFFF", fontSize=12, fontName="Arial Narrow", fgFill = "#4F80BD") write.xlsx(x=df_pivot, file=outfile, sheetName = sheet, headerStyle=hs)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/strataMethods.R \docType{methods} \name{strata} \alias{strata} \alias{strata,genind-method} \alias{strata,genlight-method} \alias{strata<-} \alias{strata<-,genind-method} \alias{strata<-,genlight-method} \alias{nameStrata} \alias{nameStrata,genind-method} \alias{nameStrata,genlight-method} \alias{nameStrata<-} \alias{nameStrata<-,genind-method} \alias{nameStrata<-,genlight-method} \alias{splitStrata} \alias{splitStrata,genind-method} \alias{splitStrata,genlight-method} \alias{splitStrata<-} \alias{splitStrata<-,genind-method} \alias{splitStrata<-,genlight-method} \alias{addStrata} \alias{addStrata,genind-method} \alias{addStrata,genlight-method} \alias{addStrata<-} \alias{addStrata<-,genind-method} \alias{addStrata<-,genlight-method} \title{Access and manipulate the population strata for genind or genlight objects.} \usage{ strata(x, formula = NULL, combine = TRUE, value) strata(x) <- value nameStrata(x, value) nameStrata(x) <- value splitStrata(x, value, sep = "_") splitStrata(x, sep = "_") <- value addStrata(x, value, name = "NEW") addStrata(x, name = "NEW") <- value } \arguments{ \item{x}{a genind or genlight object} \item{formula}{a nested formula indicating the order of the population strata.} \item{combine}{if \code{TRUE} (default), the levels will be combined according to the formula argument. If it is \code{FALSE}, the levels will not be combined.} \item{value}{a data frame OR vector OR formula (see details).} \item{sep}{a \code{character} indicating the character used to separate hierarchical levels. This defaults to "_".} \item{name}{an optional name argument for use with addStrata if supplying a vector. Defaults to "NEW".} } \description{ The following methods allow the user to quickly change the strata of a genind or genlight object. } \details{ \subsection{Function Specifics}{ \itemize{ \item \strong{strata()} - Use this function to view or define population stratification of a \linkS4class{genind} or \linkS4class{genlight} object. \item \strong{nameStrata()} - View or rename the different levels of strata. \item \strong{splitStrata()} - Split strata that are combined with a common separator. This function should only be used once during a workflow. \itemize{ \item \emph{Rationale:} It is often difficult to import files with several levels of strata as most data formats do not allow unlimited population levels. This is circumvented by collapsing all population strata into a single population factor with a common separator for each observation. } \item \strong{addStrata()} - Add levels to your population strata. This is ideal for adding groups defined by \code{\link{find.clusters}}. You can input a data frame or a vector, but if you put in a vector, you have the option to name it. }} \subsection{Argument Specifics}{ These functions allow the user to seamlessly carry all possible population stratification with their \linkS4class{genind} or \linkS4class{genlight} object. Note that there are two ways of performing all methods: \itemize{ \item modifying: \code{strata(myData) <- myStrata} \item preserving: \code{myNewData <- strata(myData, value = myStrata)} } They essentially do the same thing except that the modifying assignment method (the one with the "\code{<-}") will modify the object in place whereas the non-assignment method will preserve the original object (unless you overwrite it). Due to convention, everything right of the assignment is termed \code{value}. To avoid confusion, here is a guide to the argument \strong{\code{value}} for each function: \itemize{ \item \strong{strata()} \code{value = }a \code{\link{data.frame}} that defines the strata for each individual in the rows. \item \strong{nameStrata()} \code{value = }a \code{\link{vector}} or a \code{\link{formula}} that will define the names. \item \strong{splitStrata()} \code{value = }a \code{\link{formula}} argument with the same number of levels as the strata you wish to split. \item \strong{addStrata()} \code{value = }a \code{\link{vector}} or \code{\link{data.frame}} with the same length as the number of individuals in your data. }} \subsection{Details on Formulas}{ The preferred use of these functions is with a \code{\link{formula}} object. Specifically, a hierarchical formula argument is used to assign the levels of the strata. An example of a hierarchical formula would be:\tabular{r}{ \code{~Country/City/Neighborhood}} This convention was chosen as it becomes easier to type and makes intuitive sense when defining a \code{\link{hierarchy}}. Note: it is important to use hiearchical formulas when specifying hierarchies as other types of formulas (eg. \code{~Country*City*Neighborhood}) will give incorrect results.} } \examples{ # let's look at the microbov data set: data(microbov) microbov # We see that we have three vectors of different names in the 'other' slot. # ?microbov # These are Country, Breed, and Species names(other(microbov)) # Let's set the strata strata(microbov) <- data.frame(other(microbov)) microbov # And change the names so we know what they are nameStrata(microbov) <- ~Country/Breed/Species \dontrun{ # let's see what the strata looks like by Species and Breed: head(strata(microbov, ~Breed/Species)) # If we didn't want the last column combined with the first, we can set # combine = FALSE head(strata(microbov, ~Breed/Species, combine = FALSE)) #### USING splitStrata #### # For the sake of example, we'll imagine that we have imported our data set # with all of the stratifications combined. setPop(microbov) <- ~Country/Breed/Species strata(microbov) <- NULL # This is what our data would look like after import. microbov # To set our strata here, we need to use the functions strata and splitStrata strata(microbov) <- data.frame(x = pop(microbov)) microbov # shows us that we have "one" level of stratification head(strata(microbov)) # all strata are separated by "_" splitStrata(microbov) <- ~Country/Breed/Species microbov # Now we have all of our strata named and split head(strata(microbov)) # all strata are appropriately named and split. } } \seealso{ \code{\link{setPop}} \code{\link{genind}} \code{\link{as.genind}} } \author{ Zhian N. Kamvar }
/man/strata-methods.Rd
no_license
thibautjombart/adegenet
R
false
true
6,376
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/strataMethods.R \docType{methods} \name{strata} \alias{strata} \alias{strata,genind-method} \alias{strata,genlight-method} \alias{strata<-} \alias{strata<-,genind-method} \alias{strata<-,genlight-method} \alias{nameStrata} \alias{nameStrata,genind-method} \alias{nameStrata,genlight-method} \alias{nameStrata<-} \alias{nameStrata<-,genind-method} \alias{nameStrata<-,genlight-method} \alias{splitStrata} \alias{splitStrata,genind-method} \alias{splitStrata,genlight-method} \alias{splitStrata<-} \alias{splitStrata<-,genind-method} \alias{splitStrata<-,genlight-method} \alias{addStrata} \alias{addStrata,genind-method} \alias{addStrata,genlight-method} \alias{addStrata<-} \alias{addStrata<-,genind-method} \alias{addStrata<-,genlight-method} \title{Access and manipulate the population strata for genind or genlight objects.} \usage{ strata(x, formula = NULL, combine = TRUE, value) strata(x) <- value nameStrata(x, value) nameStrata(x) <- value splitStrata(x, value, sep = "_") splitStrata(x, sep = "_") <- value addStrata(x, value, name = "NEW") addStrata(x, name = "NEW") <- value } \arguments{ \item{x}{a genind or genlight object} \item{formula}{a nested formula indicating the order of the population strata.} \item{combine}{if \code{TRUE} (default), the levels will be combined according to the formula argument. If it is \code{FALSE}, the levels will not be combined.} \item{value}{a data frame OR vector OR formula (see details).} \item{sep}{a \code{character} indicating the character used to separate hierarchical levels. This defaults to "_".} \item{name}{an optional name argument for use with addStrata if supplying a vector. Defaults to "NEW".} } \description{ The following methods allow the user to quickly change the strata of a genind or genlight object. } \details{ \subsection{Function Specifics}{ \itemize{ \item \strong{strata()} - Use this function to view or define population stratification of a \linkS4class{genind} or \linkS4class{genlight} object. \item \strong{nameStrata()} - View or rename the different levels of strata. \item \strong{splitStrata()} - Split strata that are combined with a common separator. This function should only be used once during a workflow. \itemize{ \item \emph{Rationale:} It is often difficult to import files with several levels of strata as most data formats do not allow unlimited population levels. This is circumvented by collapsing all population strata into a single population factor with a common separator for each observation. } \item \strong{addStrata()} - Add levels to your population strata. This is ideal for adding groups defined by \code{\link{find.clusters}}. You can input a data frame or a vector, but if you put in a vector, you have the option to name it. }} \subsection{Argument Specifics}{ These functions allow the user to seamlessly carry all possible population stratification with their \linkS4class{genind} or \linkS4class{genlight} object. Note that there are two ways of performing all methods: \itemize{ \item modifying: \code{strata(myData) <- myStrata} \item preserving: \code{myNewData <- strata(myData, value = myStrata)} } They essentially do the same thing except that the modifying assignment method (the one with the "\code{<-}") will modify the object in place whereas the non-assignment method will preserve the original object (unless you overwrite it). Due to convention, everything right of the assignment is termed \code{value}. To avoid confusion, here is a guide to the argument \strong{\code{value}} for each function: \itemize{ \item \strong{strata()} \code{value = }a \code{\link{data.frame}} that defines the strata for each individual in the rows. \item \strong{nameStrata()} \code{value = }a \code{\link{vector}} or a \code{\link{formula}} that will define the names. \item \strong{splitStrata()} \code{value = }a \code{\link{formula}} argument with the same number of levels as the strata you wish to split. \item \strong{addStrata()} \code{value = }a \code{\link{vector}} or \code{\link{data.frame}} with the same length as the number of individuals in your data. }} \subsection{Details on Formulas}{ The preferred use of these functions is with a \code{\link{formula}} object. Specifically, a hierarchical formula argument is used to assign the levels of the strata. An example of a hierarchical formula would be:\tabular{r}{ \code{~Country/City/Neighborhood}} This convention was chosen as it becomes easier to type and makes intuitive sense when defining a \code{\link{hierarchy}}. Note: it is important to use hiearchical formulas when specifying hierarchies as other types of formulas (eg. \code{~Country*City*Neighborhood}) will give incorrect results.} } \examples{ # let's look at the microbov data set: data(microbov) microbov # We see that we have three vectors of different names in the 'other' slot. # ?microbov # These are Country, Breed, and Species names(other(microbov)) # Let's set the strata strata(microbov) <- data.frame(other(microbov)) microbov # And change the names so we know what they are nameStrata(microbov) <- ~Country/Breed/Species \dontrun{ # let's see what the strata looks like by Species and Breed: head(strata(microbov, ~Breed/Species)) # If we didn't want the last column combined with the first, we can set # combine = FALSE head(strata(microbov, ~Breed/Species, combine = FALSE)) #### USING splitStrata #### # For the sake of example, we'll imagine that we have imported our data set # with all of the stratifications combined. setPop(microbov) <- ~Country/Breed/Species strata(microbov) <- NULL # This is what our data would look like after import. microbov # To set our strata here, we need to use the functions strata and splitStrata strata(microbov) <- data.frame(x = pop(microbov)) microbov # shows us that we have "one" level of stratification head(strata(microbov)) # all strata are separated by "_" splitStrata(microbov) <- ~Country/Breed/Species microbov # Now we have all of our strata named and split head(strata(microbov)) # all strata are appropriately named and split. } } \seealso{ \code{\link{setPop}} \code{\link{genind}} \code{\link{as.genind}} } \author{ Zhian N. Kamvar }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/jackse.R \name{jackse} \alias{jackse} \title{Jackknife standard errors} \usage{ jackse(x, theta, bycol = TRUE, ...) } \arguments{ \item{x}{A vector or matrix to be summarized.} \item{theta}{The summary statistic to be used. For example, \code{theta = mean} calculates the jackknife standard errors for the mean.} \item{bycol}{Logical indicating if the data are in rows or columns when x is a matrix. The default is TRUE.} \item{...}{Other parameters to be passed to the summary statistic function specified by \code{theta}.} } \value{ Jackknife standard errors. } \description{ Calculate jackknife standard errors. } \author{ Ander Wilson }
/man/jackse.Rd
no_license
my1120/smurf
R
false
true
725
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/jackse.R \name{jackse} \alias{jackse} \title{Jackknife standard errors} \usage{ jackse(x, theta, bycol = TRUE, ...) } \arguments{ \item{x}{A vector or matrix to be summarized.} \item{theta}{The summary statistic to be used. For example, \code{theta = mean} calculates the jackknife standard errors for the mean.} \item{bycol}{Logical indicating if the data are in rows or columns when x is a matrix. The default is TRUE.} \item{...}{Other parameters to be passed to the summary statistic function specified by \code{theta}.} } \value{ Jackknife standard errors. } \description{ Calculate jackknife standard errors. } \author{ Ander Wilson }
#install.packages('rsconnect') #library(rsconnect) #install.packages("shinyjs") options(scipen=999) # imports ----------------------------------------------------------------- library(shiny) library(shinyjs) library(leaflet) library(RColorBrewer) library(scales) library(lattice) library(dplyr) library(ggplot2) library(plotly) library(data.table) library(lubridate) library(leaflet.extras) library(magrittr) # chain operators, e.g. to "pipe" a value forward #library(plyr) library(tidyverse) library(DT) library(knitr) library(maps) library(rgdal) library(ggmap) library(tmap) library(sp) library(tmap) library(sf) library(stars) library(spData) library(classInt) library(lattice) library(grid) library(pals) # prajwal's data fetch ---------------------------------------------------------- # Download the data from https://data.cityofnewyork.us/api/views/3q43-55fe/rows.csv?accessType=DOWNLOAD # Alternate link: https://data.cityofnewyork.us/Social-Services/Rat-Sightings/3q43-55fe, click Export -> CSV rat_sightings <- read.csv("https://data.cityofnewyork.us/api/views/3q43-55fe/rows.csv?accessType=DOWNLOAD") #rat_sightings <- read.csv("data/Rat_Sightings.csv") rat_sightings <- rat_sightings %>% filter(!(Status=='Open')) rat_sightings <- rat_sightings %>% filter(!(Status=='Draft')) rat_sightings <- rat_sightings %>% filter(!(Borough=='Unspecified')) rat_sightings$latitude <- rat_sightings$Latitude rat_sightings$longitude <- rat_sightings$Longitude #set.seed(100) #c("BROOKLYN", "QUEENS","STATEN ISLAND") #rat_sightings_buroughs <- c("BROOKLYN", "QUEENS","STATEN ISLAND") # PRATISHTA'S DATA FETCH ------------------------------------------------------- # read in the main csv file rat_data<-read.csv("data/rat_data.csv") rat_data <- rat_data %>% mutate(Borough = str_to_title(rat_data$Borough)) tonnage_data<-read.csv("data/dsny_boro_tonnage.csv", stringsAsFactors = FALSE) ton_date <- tonnage_data %>% mutate(MONTH = paste(MONTH, " / 01")) %>% mutate(MONTH = as.Date(MONTH, format = '%Y / %m / %d')) %>% filter(MONTH > as.Date('2020-01-01', '%Y-%m-%d'), MONTH < as.Date('2021-03-01', '%Y-%m-%d')) %>% arrange(desc(MONTH)) rat_date <- rat_data %>% mutate(Created.Date = as.Date(Created.Date, "%m/%d/%Y")) %>% mutate(Created.Date = as.character(Created.Date)) %>% mutate(Created.Date = substr(Created.Date, 1, 8)) %>% mutate(Created.Date = paste(Created.Date, '01')) %>% mutate(Created.Date = as.Date(Created.Date, "%Y-%m-%d")) %>% group_by(Created.Date, Borough) %>% tally() %>% filter(Created.Date > as.Date('2020-01-01', '%Y-%m-%d'), Created.Date < as.Date('2021-03-01', '%Y-%m-%d')) %>% arrange(desc(Created.Date)) rat_ton_date <- merge(rat_date, ton_date, by.x = c("Created.Date", "Borough"), by.y = c("MONTH", "BOROUGH")) %>% mutate(rate = n / (REFUSETONSCOLLECTED / 100)) # END OF PRATISHTA'S DATA FETCH ------------------------------------------------ # PRATISHTA'S CODE ------------------------------------------------------------- # community district conversion functions convertBoroCDToDistrict <- function(borocd) { sapply(borocd, function(borocd) { boro_ch = as.character(borocd) boro_n = substr(boro_ch, 1, 1) cd_n = substr(boro_ch, 2, 3) boro = case_when (boro_n == '1' ~ 'MN', boro_n == '2' ~ 'BX', boro_n == '3' ~ 'BK', boro_n == '4' ~ 'QW', boro_n == '5' ~ 'SI' ) ans <- paste(boro, cd_n, sep="") return (ans) }) } convertToShpDistrict <- function(com_district) { sapply(com_district, function(com_district) { split = strsplit(com_district, " ") boro = case_when (str_to_lower(split[[1]][2]) == 'brooklyn' ~ 'BK', str_to_lower(split[[1]][2]) == 'manhattan' ~ 'MN', str_to_lower(split[[1]][2]) == 'queens' ~ 'QW', str_to_lower(split[[1]][2]) == 'staten' ~ 'SI', str_to_lower(split[[1]][2]) == 'bronx' ~ 'BX' ); ans <- paste(boro, split[[1]][1], sep="") return (ans) }) } # reading in data and modify string format of community district column full_tonnage <-read.csv("sanitation_data/dsny_full_tonnage.csv", stringsAsFactors = FALSE) full_tonnage <- full_tonnage %>% mutate(district = paste(full_tonnage$COMMUNITYDISTRICT, str_to_upper(full_tonnage$BOROUGH))) district = paste(full_tonnage$COMMUNITYDISTRICT, str_to_upper(full_tonnage$BOROUGH)) # creating data to be mapped ton_map <- full_tonnage %>% mutate(community_district = convertToShpDistrict(district)) %>% group_by(community_district) %>% summarise(total_ton = sum(REFUSETONSCOLLECTED)) ton_map community_district <- paste(rat_data$Community.Board, str_to_upper(rat_data$Community.Board)) rat_map <- rat_data %>% mutate(community_district = convertToShpDistrict(community_district)) %>% group_by(community_district) %>% tally() rat_map rat_borough <- rat_data %>% group_by(Borough) %>% tally() rat_borough ton_boro <- tonnage_data %>% group_by(BOROUGH) %>% summarise(total_ton = sum(REFUSETONSCOLLECTED)) ton_boro rat_ton <- left_join(rat_borough, ton_boro, by = c("Borough" = "BOROUGH")) rat <- ggplot(rat_ton, aes(y=n, x=Borough, fill = Borough)) + geom_bar(position="dodge", stat="identity") ton <- ggplot(rat_ton, aes(y=total_ton, x=Borough, fill = Borough)) + geom_bar(position="dodge", stat="identity") # map data nyc <- readOGR("sanitation_data/CommunityDistricts/.", "geo_export_d81daad1-2b49-44c3-81d4-72436a58def3") nyc_sp <- spTransform(nyc, CRS("+proj=longlat +datum=WGS84")) nyc_sp@data <- nyc_sp@data %>% mutate(community_district = convertBoroCDToDistrict(boro_cd)) nyc_sp@data nyc_sp@data <- left_join(nyc_sp@data, rat_map) nyc_sp@data nyc_sp@data <- left_join(nyc_sp@data, ton_map) nyc_sp@data # END OF PRATISHTA'S CODE------------------------------------------------------- # shiny code # brendan's imports and code ------------------------------------------------------- library(ggplot2) library(ggthemes) library(gridExtra) library(dplyr) library(readr) library(leaflet) library(leaflet.extras) library(magrittr) library(dplyr) library(tidyr) library(wordcloud) library(png) library(ggwordcloud) library(tidytext) library(readr) library(png) #setwd("~/Bayesian") open <- read.csv("data/Open_Restaurant_Applications.csv") inspection <- read.csv("data/DOHMH_New_York_City_Restaurant_Inspection_Results.csv") rat_311 <- read.csv("data/311_Service_Requests_from_2010_to_Present.csv") restaurant_borough <- count(open, Borough) names(restaurant_borough)[names(restaurant_borough) == "n"] <- "count" rat_borough <- count(rat_311, Borough) borough <- c("Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island", "none") rat_borough <- cbind(rat_borough, borough) %>% filter(borough!= "none") rat_borough <- select(rat_borough, borough, n) names(rat_borough)[names(rat_borough) == "n"] <- "count" names(rat_borough)[names(rat_borough) == "borough"] <- "Borough" inspection_bc <- inspection %>% filter(GRADE == "B" | GRADE == "C") inspection_count_2020 <- count(inspection_bc, BORO) names(inspection_count_2020)[names(inspection_count_2020) == "n"] <- "count" names(inspection_count_2020)[names(inspection_count_2020) == "BORO"] <- "Borough" street_seating <- filter(open, Approved.for.Roadway.Seating == "yes") count_street <- count(street_seating, Borough) names(count_street)[names(count_street) == "n"] <- "count" sidewalk_seating <- filter(open, Approved.for.Sidewalk.Seating == "yes") count_sidewalk <- count(sidewalk_seating, Borough) names(count_sidewalk)[names(count_sidewalk) == "n"] <- "count" manhattan_311 <- filter(rat_311, Borough == "MANHATTAN") #manhattan_311 <- read.csv("manhattan311.csv") manhattan_open <- read.csv("data/manhattan open restaurants.csv") manhattan_311 <- filter(manhattan_311, manhattan_311$Complaint.Type=="Rodent") manhattan_311 <- data.frame(manhattan_311$Latitude, manhattan_311$Longitude, manhattan_311$Incident.Address, manhattan_311$Created.Date, manhattan_311$Descriptor) icon <- makeIcon(iconUrl= "https://cdn3.iconfinder.com/data/icons/farm-animals/128/mouse-512.png", iconWidth=25, iconHeight = 20) #manhattan_311b <- read.csv("manhattan311.csv") #manhattan_311b <- read.csv("https://nycopendata.socrata.com/api/views/erm2-nwe9/rows.csv?accessType=DOWNLOAD") # code for making wordcloud (not used in live version for processing power reasons) ----------------------------------------------- # manhattan_311b <- filter(rat_311, Borough == "MANHATTAN") # nrow(manhattan_311b) # # manhattan_311b <- manhattan_311b %>% filter(Complaint.Type != "Noise = Street/Sidewalk" & Complaint.Type != "Noise - Residential" & Complaint.Type != "HEAT/HOT WATER" & Complaint.Type != "Illegal Parking" & Complaint.Type != "Non-Emergency Police Matter" & Complaint.Type != "Noise" & Complaint.Type != "Noise - Vehicle" & Complaint.Type != " Noise - Commercial") # descriptors <- manhattan_311b %>% select(Descriptor) # descriptors_fix <- as.character(descriptors$Descriptor) # text_df <- tibble(line = 1:length(descriptors_fix), text = descriptors_fix) # descriptors <- text_df %>% unnest_tokens(word, text) # # descriptors <- count(descriptors, word) # descriptors2 <- filter(descriptors, n > 2000) # col <- c(ifelse(descriptors2$word == "pests" | descriptors2$word == "rat" | descriptors2$word == "sighting" | descriptors2$word == "rodents", "red", "black")) # descriptors3 <- cbind(descriptors2, col) # descriptors3 <- filter(descriptors3, word != "n" & word != "a" & word != "not" & word != "business" & word != "no" & word!= "compliance" & word != "or" & word != "in" & word != "of" & word!= "to" & word!= "non" & word!= "on" & word != "has" & word!= "for") # #setwd("~/Bayesian") # img <- readPNG("data/rat.png") # #img <- icon # descriptors3 <- descriptors3 %>% filter(word != "loud" & word!= "music" & word != "party") # set.seed(14) # (wordcloud1 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area(mask=img, rm_outside = TRUE) + scale_size_area(max_size=5) + theme_classic()) # (wordcloud2 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area() + scale_size_area()) # user interface for setting layout of plots ---------------------------------------------------------- # sliders and interactive map --------------------------------------------- rat_sightings_buroughs <- as.character(unique(unlist(rat_sightings$Borough))) rat_sightings_case_status <- as.character(unique(unlist(rat_sightings$Status))) ui <- fluidPage( # header description ------------------------------------------------------ tags$head( # Note the wrapping of the string in HTML() tags$style(HTML(" .row { margin-left: 0; margin-right:0; }")) ), fluidRow(align = "center", h1("Rats and NYC: Exploratory Visualization"), strong("Data Visualization (QMSS - G5063) Final Project, Spring 2021"), br(), em("Group N: Brendan Mapes, Prajwal Seth, and Pratishta Yerakala"), h3(a("Link to code and process book", href="https://github.com/QMSS-G5063-2021/Group_N_NYCdata")), br(),br(),br(), p("In this project, we will explore in detail New York City's rat problem. New York has always dealt with a relatively high population of rats, as do many other large metropolitan areas. However, since the beginning of the COVID-19 pandemic rat sightings have been on the rise. Rats are being seen more often, during new times of day, and are acting more aggressive. Through the following visualizations we hope to find some explanation for this recent uptick in rat sightings. The way restaurants and residents handle their trash plays a large role in the survival and behavior of rats in the city. So through exploration of city sanitation data, restaurant registration data, and 311 calls in the city, we hope to find some potential explanations as to why New York's rat problem has gotten so bad."),), br(),br(),br(), # prajwal's description --------------------------------------------------- # fluidRow( # align = "center", # headerPanel("Hello 1!"), # p("p creates a paragraph of text."), # p("A new p() command starts a new paragraph. Supply a style attribute to change the format of the entire paragraph.", style = "font-family: 'times'; font-si16pt"), # strong("strong() makes bold text."), # em("em() creates italicized (i.e, emphasized) text."), # br(), # code("code displays your text similar to computer code"), # div("div creates segments of text with a similar style. This division of text is all blue because I passed the argument 'style = color:blue' to div", style = "color:blue"), # br(), # p("span does the same thing as div, but it works with", # span("groups of words", style = "color:blue"), # "that appear inside a paragraph."), # ), fluidRow( align = "center", style='margin-left:0px; margin-right: 0px;', h2("Interactive map of rodent complaints in NYC since 2010"), h3("Prajwal Seth"), br(), ), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings (automatically updated daily)", href="https://data.cityofnewyork.us/Social-Services/Rat-Sightings/3q43-55fe"), br(), h4("Background:"), p("In this section, I have visualized rodent complaints from 2010 till today submitted to the NYC311 portal. Feel free to play around with the provided filters for number of samples, years, boroughs, and case status (however, due to processing constraints on shinyapps.io, the website will crash if you set the number of samples too high). The map on the left will dynamically update as you change the filters (or will not update if there is no data to display after the filters are applied). The plot for the trend in complaint status also updates according to the rat complaints that are visible in the map. Upon zooming into the map, you will see that the color of the marker for each complaint is set according to the complaint status (refer to the legend of the map). Also provided is a tooltip displaying the complaint's created date, closed date, address, status, and location type. There is a layer of heat added to the map, with the intensity of the heat being calculated based on the number of rat sightings in the area."), ), ), # sliders and map etc ----------------------------------------------------- fluidRow( sidebarLayout(position = "right", sidebarPanel(width = 6, sliderInput("num_sample", label = h4("Select number of random samples"), min = 1, max = nrow(rat_sightings), value = 1000, step = 1000), sliderInput("year_input", label = h4("Select years"), min = 2010, max = 2021, value = c(2010, 2021), step = 1, format = "####"), #selected = rat_sightings_buroughs[1:length(multiInput)]) #selected = rat_sightings_buroughs, selectizeInput("burough_input", label=h4("Select boroughs"), choices =rat_sightings_buroughs, multiple = TRUE, selected = rat_sightings_buroughs), selectizeInput("case_status", label=h4("Select status"), choices =rat_sightings_case_status, multiple = TRUE, selected = rat_sightings_case_status), #plotlyOutput("cityViz", height = 300), plotlyOutput("yearViz", height = 250), #plotlyOutput("locationViz", height = 220), #plotlyOutput("locationViz", height = 300), ), mainPanel(width = 6, style='margin-top:40px;', leafletOutput("map", height = 825), ), ), # PRATISHTA'S WRITEUP -------------------------------------------------------- fluidRow( align = "center", style='margin-left:0px; margin-right: 0px;', h2("Rat Sightings and Sanitation Waste by Borough"), h3("Pratishta Yerakala"), br(), ), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("filtered for rodent sightings between Feb 2020 and Feb 2021.")), h5(a("DSNY Monthly Tonnage", href="https://data.cityofnewyork.us/City-Government/DSNY-Monthly-Tonnage-Data/ebb7-mvp5"), h6("filtered for months between Feb 2020 and Feb 2021.")), h5(a("NYC Community Districts Shapefile", href="https://data.cityofnewyork.us/City-Government/Community-Districts/yfnk-k7r4")), ), div(class='padding', h4("Background:"), p("The large rodent population in New York City is no secret. Rats have been associated with the city for a long time whether it's from the famous", a('pizza rat', href='https://knowyourmeme.com/memes/pizza-rat'), "or to the rising concern from residents who have noticed changes since the COVID-19 pandemic. Many businesses and normally occurring procedures have been slowed down or halted completely. One such example in particular with the Department of Sanitation of NY (DSNY) where limited resources and budget cuts since the pandemic have caused an", a("increased amount of litter and waste production", href="https://patch.com/new-york/new-york-city/city-state-leaders-decry-sanitation-setback-trash-piles"), "."), ) ), fluidRow( align = "center", div(class='padding', h4(align = "left", "Visualizations:"), ), # descriptive charts h3("Total Number of Rat Sightings (2020-2021)"), h6("Chart 1"), plotlyOutput("pratishta5", width = "50%"), br(), h3("Total Waste Produced (2020-2021)"), h6("Chart 2"), plotlyOutput("pratishta4", width = "50%"), br(), p(class = "padding", align = "left", "We can see in Chart 1 that Brooklyn produces the most tons of waste followed by Queens, and then by Bronx and Manhattan. Staten Island is last with the least amount of waste. Chart 2 shows the number of rat sightings per borough and naturally, we have Brooklyn at the top with around 6,000 sightings. But Instead of Queens, Manhattan follows with most rat s ightings. Then Queens and Bronx. From here it seems that Staten Island and Bronx are boroughs that have some what proportional sightings to waste produced. However, though Queens produces a lot of waste, it does not have nearly the same rate of rat sightings. Conversely, Manhattan doesn't quite produce the same amount of waste as Queens but seems to have far more rat sightings. Brooklyin is consistenly infested."), # time series charts h3("Waste per Month (2020-2021)"), h6("Chart 3"), plotlyOutput("pratishta1", width = "70%"), br(), h3("Rat Sightings per Month (2020-2021)"), h6("Chart 4"), plotlyOutput("pratishta2", width = "70%"), br(), h3("Rate of Rats per Waste Ton per Month"), h6("Chart 5"), plotlyOutput("pratishta3", width = "70%"), br(), p(class = "padding", align = "left", "Charts 3 to 5 show a time series line graphs. Chart 3 shows the tons of waste per month generated by each borough. It seems that around March and April of 2020 there was a change in the trend. Though the waste was rising, it flattened out - or even fell like with Manhattan for example - between March and April of 2020. But after april there was a more mellow rise and then gentle decline closer to Fall of 2020 and early 2021. This exploratory chart is good to possibly check out Manhattan and why the waste production went down. Perhaps for restaurants closing?"), p(class = "padding", align = "left", "Chart 4 shows that all boroughs saw an increase in rat sightings, especially Brooklyn. It did seem to peak around summer of 2020 and decline again to almost normal rates. These sightings might be due to the sanitation departments' limits as mentioned earlier."), p(class = "padding", align = "left", "Chart 5 looks at the 'rate' at which a rat sighting is possible for every kilo-ton of waste produced in each borough per month. It seems that these rates also follow a similar path of an increase around April 2020 and then a peak in summer of 2020 and then a mellow decline. However Manhattan's rate shot up for early 2021 with around 0.75 (sightings per ton of waste) to 1.5 (sightings per ton of waste). Perhaps this could be due to frequent testings, vaccinations, and re-opening of restaurants (producing more waste)?"), # maps h3("Number of Rat Sightings per Month"), h6("Chart 6"), ), fluidRow( tmapOutput("pratishta7", width = "100%"), br(), ), fluidRow(align = "center", h3("Waste Produced in Tons"), h6("Chart 7"), ), fluidRow( tmapOutput("pratishta8", width = "100%"), br(), ), fluidRow( align = "center", h3("Rat Sightings and Waste Produced By Community District"), h6("Chart 8"), plotOutput("pratishta9", width = "60%"), br(), p(class = "padding", align = "left", "Here we show choropleth maps of NYC by community district. Community district as the geographical feature here is because DSNY also records their information with that feature. It seems that there is one community districte that's seeing a severe rise in rat sightings (BK03). It may be worth it to take a closer look at that particular district if analysis or further studie are done."), p(class = "padding", align = "left", "As expected it looks like Queens produces a massive amount of waste and the particular districts are highlighted in deep red (100,000 - 120,000 tons category). And though Brooklyn also produces a lot of waste it seems to be spread out amongst the community districts."), p(class = "padding", align = "left", "Chart 8 depicts a bivariate choropleth map of the community districts. This make-shift rendering of a map using the tm_map package is from", a("this currently open issue from the tmap GitHub repsitory", href="https://github.com/mtennekes/tmap/issues/183#issuecomment-670554921"), ". As the districts become more blue in color, the more right sightings that have been reported in that district. The more purple a district, the more amount of waste produced there. As the color goes to indigo, there's a high rat sighting and a high waste production (a high high category if further spatial dependence analysis was conducted). Light grey represents few rat sightings and little waste production (a 'low low' again for further spatial research). This map demonstrates that hough there are high rat sightings in downtown Manhattan and parts of Brooklyn, it's not necessarily tied to waste production. In the same way, the outer boroughs have a huge waste production but not many rat sightings. But there are some districts (indigo) that do exhibit both features in high amounts. This exploratory data visulaization provides the insight to further look in those districts.") ), # Brendan's writeup ------------------------------------------------- fluidRow( align = "center", h2("Rat Sightings and Restaurants by Borough"), h3("Brendan Mapes"), br(), ), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("Filtered to 311 calls from Jan 1 2020 to Dec 31 2020, of complaint type β€œrodent”.")), h5(a("Open Restaurants", href="https://data.cityofnewyork.us/Transportation/Open-Restaurant-Applications/pitm-atqc/data"),), ), div(class='padding', h4("Background:"), p("It is well documented that the COVID-19 pandemic has led to a rise in rat sightings throughout New York City. It is also well known that the pandemic has been especially hard on the restaurant industry. Hit especially hard by stay-at-home orders and social distancing mandates, restaurants have been forced to innovate their operations. Now more than ever, restaurants are serving customers outside in the streets. We suspect this change in the way restaurants do their business may be contributing to the increase in rat sightings. We explore this possibility a bit further in the next few visualizations."), ), div(class='padding', h4("Visualizations:"), ), ), # descriptive charts # fluidRow(align = "center", # br(), # h3("NYC311 rodent complaints in 2020 and number of restaurants by type"), # h6("Chart 9"),br(), # plotOutput("brendan_chart1", width = "80%"), # plotOutput("brendan_chart2", width = "80%"), # br(), # br(), # p(class = "padding", align = "left", "In all four figures, we can see that Manhattan is far above the rest of the boroughs in restaurants # approved for outdoor dining, in sidewalk and street dining. However, it is Brooklyn that is far above the # rest of the boroughs in rodent reports in 2020. This suggests that perhaps another factor is contributing # to the rat problem in the Brooklyn borough. If restaurants were fully to blame for it’s rat problem, we # would expect to see it having high numbers of restaurants approved for outdoor street and sidewalk # dining, a number comparable to the borough of Manhattan. # # The first bar plot displays the number of rodent related 311 reports in the year 2020 by borough. # Brooklyn leads the way with well over 10,000 rodent related calls in the year, while the next closest # borough, Manhattan, only has about 8,000 rodent related calls in the year. In the bar plots related to # restaurants, we see Manhattan leads the way across the board. In the restaurants with outdoor dining, # sidewalk and street dining, Manhattan has twice as many restaurants than any other borough. Because # of this vast difference in the number of restaurants in Manhattan compared to the other boroughs, we # will narrow our focus to Manhattan in the next visualization."),), fluidRow(align = "center", br(), br(), br(), # code for generating these plots # title: "brendan2" # author: "Brendan Mapes" # date: "4/17/2021" # output: html_document # --- # # ```{r setup, include=TRUE} # knitr::opts_chunk$set(echo = TRUE) # library(ggplot2) # library(ggthemes) # library(gridExtra) # library(dplyr) # library(plotly) # open <- read.csv("Open_Restaurant_Applications.csv") # inspection <- read.csv("DOHMH_New_York_City_Restaurant_Inspection_Results.csv") # rat_311 <- read.csv("311_Service_Requests_from_2010_to_Present.csv") # restaurant_borough <- count(open, Borough) # names(restaurant_borough)[names(restaurant_borough) == "n"] <- "count" # rat_borough <- count(rat_311, Borough) # borough <- c("Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island", "none") # rat_borough <- cbind(rat_borough, borough) %>% filter(borough!= "none") # rat_borough <- select(rat_borough, borough, n) # names(rat_borough)[names(rat_borough) == "n"] <- "count" # names(rat_borough)[names(rat_borough) == "borough"] <- "Borough" # inspection_bc <- inspection %>% filter(GRADE == "B" | GRADE == "C") # inspection_count_2020 <- count(inspection_bc, BORO) # names(inspection_count_2020)[names(inspection_count_2020) == "n"] <- "count" # names(inspection_count_2020)[names(inspection_count_2020) == "BORO"] <- "Borough" # street_seating <- filter(open, Approved.for.Roadway.Seating == "yes") # count_street <- count(street_seating, Borough) # names(count_street)[names(count_street) == "n"] <- "count" # sidewalk_seating <- filter(open, Approved.for.Sidewalk.Seating == "yes") # count_sidewalk <- count(sidewalk_seating, Borough) # names(count_sidewalk)[names(count_sidewalk) == "n"] <- "count" # plot1 <- ggplot() + geom_bar(data=rat_borough, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("2020 rodent reports") + ylab("Number of 311 calls\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot2 <- ggplot() + geom_bar(data=restaurant_borough, aes(x =Borough, y= count, fill =Borough), stat="identity") + ggtitle("Outdoor restaurants") + ylab("Applications approved\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot3 <- ggplot() + geom_bar(data=inspection_count_2020, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("Restaurants w/ B or C inspection scores") + ylab("Restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot4 <- ggplot() + geom_bar(data=count_street, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("Street dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot5 <- ggplot() + geom_bar(data=count_sidewalk, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("Sidewalk dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot1a <- ggplotly(plot1, tooltip=c("x", "y")) # plot2a <- ggplotly(plot2, tooltip=c("x", "y")) # plot3a <- ggplotly(plot3, tooltip=c("x", "y")) # plot4a <- ggplotly(plot4, tooltip=c("x", "y")) # plot5a <- ggplotly(plot5, tooltip=c("x", "y")) # plot1a # plot2a # plot3a # plot4a # plot5a h6("Chart 9"), plotlyOutput("brendan_chart1" ,width="50%"), br(), h6("Chart 10"), plotlyOutput("brendan_chart2",width="50%"), br(), h6("Chart 11"), plotlyOutput("brendan_chart3",width='50%'), br(), h6("Chart 12"), plotlyOutput("brendan_chart4",width='50%'), br(), h6("Chart 13"), plotlyOutput("brendan_chart5",width='50%'), br(), p(class = "padding", align = "left", "In all five figures, we can see that Manhattan is far above the rest of the boroughs in restaurants approved for outdoor dining, in sidewalk and street dining, and B and C graded restaurants. However, it is Brooklyn that is far above the rest of the boroughs in rodent reports in 2020. This suggests that perhaps another factor is contributing to the rat problem in the Brooklyn borough. If restaurants were fully to blame for it’s rat problem, we would expect to see it having high numbers of restaurants approved for outdoor street and sidewalk dining, a number comparable to the borough of Manhattan. The first bar plot displays the number of rodent related 311 reports in the year 2020 by borough. Brooklyn leads the way with well over 10,000 rodent related calls in the year, while the next closest borough, Manhattan, only has about 8,000 rodent related calls in the year. In the bar plots related to restaurants, we see Manhattan leads the way across the board. In the restaurants with outdoor dining, sidewalk and street dining, Manhattan has twice as many restaurants than any other borough. Because of this vast difference in the number of restaurants in Manhattan compared to the other boroughs, we will narrow our focus to Manhattan in the next visualization."),br(),br(), ), ), br(), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("Filtered to 311 calls from Jan 1 2020 to Dec 31 2020, of complaint type β€œrodent” in Manhattan borough.")), h5(a("Open Restaurants", href="https://data.cityofnewyork.us/Transportation/Open-Restaurant-Applications/pitm-atqc/data"),h6("Filtered to Manhattan borough.")), ), div(class='padding', h4("Visualization:"), ), fluidRow(align = "center", h3("Rat sightings in 2020 overlaid on restaurant locations in Manhattan"), h6("Chart 14"),),br(), fluidRow( leafletOutput("brendan_map", height = 500, width = "100%"), br(), br(), p(class = "padding", align = "left", "Based off exploratory analysis of the restaurants and rat reports across all boroughs, it’s clear Manhattan’s restaurant industry may be most closely linked to the rat problem than in other boroughs. For that reason, we have provided an interactive map visualization of the Manhattan borough specifically. In the map, restaurants are plotted and viewers can see the location and name of the restaurant, along with whether or not the restaurant is available for open street or sidewalk dining. Also charted on the map are the location of rat sightings in the 2020 311 calls data set, the same data used for previous visualizations. With no zoom, clusters of the rats are displayed in the visualization. After zooming in further, those clusters break into the individual rat sighting locations of which they consist. Rat sighting locations are represented by small rat icons on the map."), p(class = "padding", align = "left", "This visualization allows viewers to identify densely rat populated locations on the map and relate that information to the data provided for restaurants in the same locations. In real time, such a map would be useful for avoidance of rat β€œhot spots” when choosing places to dine. It also allows users to explore which restaurants have practices that may be contributing to the rat problem the most, with lots of rat sightings nearby."),), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("Filtered to 311 calls from Jan 1 2020 to Dec 31 2020, of complaint type 'rodent' in Manhattan borough. Calls related to noise, parking violations, and other non-emergency police related matters are also excluded from this visualization.")), ), div(class='padding', h4("Visualization:"), ), ), fluidRow(align = "center", h3("Wordcloud of the descriptor variable of all NYC311 complaints in 2020"), br(), h6("Chart 15"), img(src='Capture.PNG',width="50%"), br(), h6("Chart 16"), img(src='Picture2.png',width="50%"), br(), h6("For reference:"), img(src='rat.png',), br(), br(), p(class = "padding", align = "left", "For required text analysis, we have again referred to the 2020 rodent related 311 reports, specifically on the descriptor variable, where various notes are left on the nature or details of the complaint. Two word clouds are presented. The first is a basic wordcloud created with the ggwordcloud package. Words related to rat sightings are differentiated from others by color. Viewers can see in this wordcloud that the descriptor variable does have lots of mentions of rodent related issues. The second wordcloud presented is also from the ggwordcloud package, but with an added mask, intended to create a wordcloud the shape of a rat. This visualization is slightly more visually appealing, but reveals the exact same information to the reader. Rat sightings are often mentioned in the descriptor variable of the data set."),br(),br() ), # fluidRow( # align = "center", # plotOutput("brendan_wc1"), # plotOutput("bendan_wc2"), # ), ), ) ) # code for generating the plots ----------------------------------------------------------------- server <- function(input, output, session) { # prajwal's code for generating interactive map backend ------------------- # points <- eventReactive(input$recalc, { # cbind(rat_sightings_sample$latitude, rat_sightings_sample$longitude) # }, ignoreNULL = FALSE) # observe({ min_year <- input$year_input[1] max_year <- input$year_input[2] burough <- input$burough_input case_status1 <- input$case_status rat_sightings_sample <- rat_sightings[sample.int(nrow(rat_sightings), input$num_sample),] #rat_sightings_sample <- rat_sightings latitude_colnum <- grep('latitude', colnames(rat_sightings_sample)) longitude_colnum <- grep('longitude', colnames(rat_sightings_sample)) rat_sightings_sample <- rat_sightings_sample[complete.cases(rat_sightings_sample[,latitude_colnum:longitude_colnum]),] rat_sightings_sample$year_created <- year(parse_date_time(rat_sightings_sample$Created.Date, '%m/%d/%y %I:%M:%S %p')) #print('buroughh') #print(burough) #filter_rat_sightings <- rat_sightings_sample %>% filter(year_created >= min_year, year_created <= max_year, Borough %in% burough) check_rows_of_filter <- nrow(rat_sightings_sample %>% filter(year_created >= min_year, year_created <= max_year, Borough %in% burough, Status %in% case_status1)) rat_sightings_buroughs2 <- as.character(unique(unlist(rat_sightings_sample$Borough))) rat_sightings_case_status2 <- as.character(unique(unlist(rat_sightings_sample$Status))) # print('buroughs 2') # print(rat_sightings_buroughs2) # print('case statuses 2') # print(rat_sightings_case_status2) if (check_rows_of_filter <= 0){ #updateSliderInput(session, "year_input", value = c(2010, 2021)) #updateSliderInput(session, "burough_input", value = rat_sightings_buroughs2) #updateSliderInput(session, "case_status", value = rat_sightings_case_status2) # filter_rat_sightings2 <- rat_sightings_sample # reset("year_input") # reset("burough_input") # reset("burough_input") # print('in the case of 0 rows, resetting to entire df') leaflet() %>% addProviderTiles(providers$Stamen.TonerLite, options = providerTileOptions(noWrap = TRUE) ) %>% setView(lng = -73.98928, lat = 40.75042, zoom = 10) } else{ filter_rat_sightings2 <- rat_sightings_sample %>% filter(year_created >= min_year, year_created <= max_year, Borough %in% burough, Status %in% case_status1) filter_rat_sightings <- filter_rat_sightings2 getColor <- function(filter_rat_sightings, i) { if(filter_rat_sightings$Status[i] == "Closed") { "green" } else if(filter_rat_sightings$Status[i] == "In Progress") { "lightblue" } else if(filter_rat_sightings$Status[i] == "Assigned") { "orange" } else if(filter_rat_sightings$Status[i] == "Open") { "purple" } else if(filter_rat_sightings$Status[i] == "Pending") { "darkred" } else if(filter_rat_sightings$Status[i] == "Draft") { "blue" }} markerColors <- rep(NA, nrow(filter_rat_sightings)) for (i in 1:nrow(filter_rat_sightings)){ markerColors[i] <- getColor(filter_rat_sightings, i) } icons <- awesomeIcons( icon = 'ios-close', iconColor = 'cadetblue', library = 'ion', markerColor = markerColors ) output$map <- renderLeaflet({ leaflet(data = filter_rat_sightings) %>% addProviderTiles(providers$Stamen.TonerLite, options = providerTileOptions(noWrap = TRUE) ) %>% setView(lng = -73.98928, lat = 40.75042, zoom = 10) %>% addAwesomeMarkers( ~longitude, ~latitude, clusterOptions = markerClusterOptions() ,icon = icons, popup = as.character(paste('Created date:', filter_rat_sightings$Created.Date,'<br>', 'Closed Date:', filter_rat_sightings$Closed.Date,'<br>', #'Complaint type:',filter_rat_sightings$Complaint.Type,'<br>', #'Descriptor:',filter_rat_sightings$Descriptor,'<br>', 'Address:',filter_rat_sightings$Incident.Address,'<br>', 'Status:', filter_rat_sightings$Status, '<br>', 'Location Type:', filter_rat_sightings$Location.Type))) %>% addHeatmap( ~longitude, ~latitude, group = "heat",max=1, blur = 45, minOpacity = 0.8) %>% addLegend("topleft", colors =c('green', "darkred", "lightblue", "orange"), #"purple", "#56a0d1" labels= c("Closed", "Pending", "In Progress","Assigned"), # "Open", "Draft" title= "Complaint status", opacity = 1) }) output$cityViz <- renderPlotly({ if (nrow(zipsInBounds()) == 0) return(NULL) tmp <- (zipsInBounds() %>% count(City)) tmp <- tmp[order(-tmp$n),] tmp <- tmp[1:5,] ggplotly( ggplot(tmp, aes(x=City, y=n, fill = City)) + geom_bar(stat="identity") + ylab("Top 5 visible buroughs") + theme(legend.position = "none") + scale_color_brewer(palette="Dark2")+ theme(axis.title.x=element_blank(), axis.ticks.x=element_blank()) ) }) output$locationViz <- renderPlotly({ if (nrow(zipsInBounds()) == 0) return(NULL) tmp <- (zipsInBounds() %>% count(Location.Type)) tmp <- tmp[order(-tmp$n),] tmp <- tmp[1:5,] ggplotly(tooltip = c("n"), ggplot(tmp, aes(x=Location.Type, y=n)) + geom_bar(stat="identity", aes(fill = Location.Type)) + ggtitle('Visible location types') + ylab("Visible location types") + theme_light()+ theme(axis.title.y=element_blank(), #axis.text.y=element_blank(), axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) + labs(fill = "Visible location types") + coord_flip() + theme(legend.position = "none") ) }) output$yearViz <- renderPlotly({ if (nrow(zipsInBounds()) == 0) return(NULL) # total cases created_date_sample <- data.table(zipsInBounds()$Created.Date) created_date_sample$dates <- parse_date_time(created_date_sample$V1, '%m/%d/%y %I:%M:%S %p') plot_created_year <- data.frame(table(year(date(created_date_sample$dates)))) for (i in 2010:2021){ if ((i %in% plot_created_year$Var1)==FALSE) { #print(i) tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- c('Var1','Freq') plot_created_year <- rbind(plot_created_year, tmp_df) } } plot_created_year$Var1 <- as.numeric(as.character(plot_created_year$Var1)) names(plot_created_year)[names(plot_created_year) == "Var1"] <- "Year" plot_created_year <- plot_created_year[order(plot_created_year$Year),] plot_created_year <- filter(plot_created_year, Year >= min_year, Year <= max_year) plot_created_year$case_status <- 'Total' # closed cases plot_closed<- filter(zipsInBounds(), Status == 'Closed') flag_closed <- 0 if (nrow(plot_closed) == 0) { flag_closed <- 1 } if (flag_closed == 0){ plot_closed <- data.table(plot_closed$Created.Date) plot_closed$dates <- parse_date_time(plot_closed$V1, '%m/%d/%y %I:%M:%S %p') plot_closed_year <- data.frame(table(year(date(plot_closed$dates)))) #print(plot_closed_year) for (i in 2010:2021){ if ((i %in% plot_closed_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_closed_year) plot_closed_year <- rbind(plot_closed_year, tmp_df) } } plot_closed_year$Var1 <- as.numeric(as.character(plot_closed_year$Var1)) names(plot_closed_year)[names(plot_closed_year) == "Var1"] <- "Year" plot_closed_year <- plot_closed_year[order(plot_closed_year$Year),] plot_closed_year <- filter(plot_closed_year, Year >= min_year, Year <= max_year) plot_closed_year$case_status <- 'Closed' } # assigned cases plot_assigned<- filter(zipsInBounds(), Status == 'Assigned') flag_assigned <- 0 if (nrow(plot_assigned) == 0) { flag_assigned <- 1 } if (flag_assigned == 0){ plot_assigned <- data.table(plot_assigned$Created.Date) plot_assigned$dates <- parse_date_time(plot_assigned$V1, '%m/%d/%y %I:%M:%S %p') plot_assigned_year <- data.frame(table(year(date(plot_assigned$dates)))) #print(plot_assigned_year) for (i in 2010:2021){ if ((i %in% plot_assigned_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_assigned_year) plot_assigned_year <- rbind(plot_assigned_year, tmp_df) } } plot_assigned_year$Var1 <- as.numeric(as.character(plot_assigned_year$Var1)) names(plot_assigned_year)[names(plot_assigned_year) == "Var1"] <- "Year" plot_assigned_year <- plot_assigned_year[order(plot_assigned_year$Year),] plot_assigned_year <- filter(plot_assigned_year, Year >= min_year, Year <= max_year) plot_assigned_year$case_status <- 'Assigned' #print('assigned or in progress') #print(plot_assigned_year) } # assigned or in progress cases plot_in_progress<- filter(zipsInBounds(), Status == 'In Progress') flag_in_progress <- 0 if (nrow(plot_in_progress) == 0) { flag_in_progress <- 1 } if (flag_in_progress == 0){ plot_in_progress <- data.table(plot_in_progress$Created.Date) plot_in_progress$dates <- parse_date_time(plot_in_progress$V1, '%m/%d/%y %I:%M:%S %p') plot_in_progress_year <- data.frame(table(year(date(plot_in_progress$dates)))) #print(plot_in_progress_year) for (i in 2010:2021){ if ((i %in% plot_in_progress_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_in_progress_year) plot_in_progress_year <- rbind(plot_in_progress_year, tmp_df) } } plot_in_progress_year$Var1 <- as.numeric(as.character(plot_in_progress_year$Var1)) names(plot_in_progress_year)[names(plot_in_progress_year) == "Var1"] <- "Year" plot_in_progress_year <- plot_in_progress_year[order(plot_in_progress_year$Year),] plot_in_progress_year <- filter(plot_in_progress_year, Year >= min_year, Year <= max_year) plot_in_progress_year$case_status <- 'In Progress' #print('assigned or in progress') #print(plot_in_progress_year) } # open cases plot_open<- filter(zipsInBounds(), Status == 'Open') flag_open <- 0 if (nrow(plot_open) == 0) { flag_open <- 1 } if (flag_open == 0){ plot_open <- data.table(plot_open$Created.Date) plot_open$dates <- parse_date_time(plot_open$V1, '%m/%d/%y %I:%M:%S %p') plot_open_year <- data.frame(table(year(date(plot_open$dates)))) #print(plot_open_year) for (i in 2010:2021){ if ((i %in% plot_open_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_open_year) plot_open_year <- rbind(plot_open_year, tmp_df) } } plot_open_year$Var1 <- as.numeric(as.character(plot_open_year$Var1)) names(plot_open_year)[names(plot_open_year) == "Var1"] <- "Year" plot_open_year <- plot_open_year[order(plot_open_year$Year),] plot_open_year <- filter(plot_open_year, Year >= min_year, Year <= max_year) plot_open_year$case_status <- 'Open' #print('open or pending') #print(plot_open_year) # print('created') # print(plot_created_year) # print('closed') # print(plot_closed_year) # print('combined') } # pending cases plot_pending<- filter(zipsInBounds(), Status == 'Pending') flag_pending <- 0 if (nrow(plot_pending) == 0) { flag_pending <- 1 } if (flag_pending == 0){ plot_pending <- data.table(plot_pending$Created.Date) plot_pending$dates <- parse_date_time(plot_pending$V1, '%m/%d/%y %I:%M:%S %p') plot_pending_year <- data.frame(table(year(date(plot_pending$dates)))) #print(plot_pending_year) for (i in 2010:2021){ if ((i %in% plot_pending_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_pending_year) plot_pending_year <- rbind(plot_pending_year, tmp_df) } } plot_pending_year$Var1 <- as.numeric(as.character(plot_pending_year$Var1)) names(plot_pending_year)[names(plot_pending_year) == "Var1"] <- "Year" plot_pending_year <- plot_pending_year[order(plot_pending_year$Year),] plot_pending_year <- filter(plot_pending_year, Year >= min_year, Year <= max_year) plot_pending_year$case_status <- 'Pending' #print('open or pending') #print(plot_pending_year) # print('created') # print(plot_created_year) # print('closed') # print(plot_closed_year) # print('combined') } #plot_this <- plot_created_year plot_this <- data.frame(matrix(ncol = 3, nrow = 0)) colnames(plot_this) <- c("Year",'Freq','case_status') rownames(plot_created_year) # print('flag open') # print(flag_open) # print('flag pending') # print(flag_pending) # print('flag assigned') # print(flag_assigned) # print('flag in progress') # print(flag_in_progress) # print('flag closed') # print(flag_closed) if (flag_open == 0){ plot_this <- rbind(plot_this, plot_open_year) } if (flag_pending == 0){ plot_this <- rbind(plot_this, plot_pending_year) } if (flag_assigned == 0) { plot_this <- rbind(plot_this, plot_assigned_year) } if (flag_in_progress == 0) { plot_this <- rbind(plot_this, plot_in_progress_year) } if (flag_closed == 0){ plot_this <- rbind(plot_this, plot_closed_year) } #print(plot_this) # p_years <- ggplotly( # ggplot(data=plot_created_year, aes(x=Year, y=Freq)) + geom_path(stat="identity") + ylab('Rat sightings') + geom_point()+ # theme(axis.title.x=element_blank()) + scale_x_continuous(breaks=seq(min_year, max_year, 1)) # ) colors_for_case_status <- rep(NA, nrow(plot_this)) for (i in 1:nrow(plot_this)){ if (plot_this$case_status[i] == "Closed"){ colors_for_case_status[i] <- "green" } else if (plot_this$case_status[i] == "Pending"){ colors_for_case_status[i] <- "darkred" } else if (plot_this$case_status[i] == "Assigned"){ colors_for_case_status[i] <- "orange" } else if (plot_this$case_status[i] == "In Progress"){ colors_for_case_status[i] <- "cadetblue" } else if (plot_this$case_status[i] == "Draft"){ colors_for_case_status[i] <- "blue" } else if (plot_this$case_status[i] == "Open"){ colors_for_case_status[i] <- "purple" } } p_years <- ggplotly( ggplot(data=plot_this, aes(x=Year, y=Freq)) + geom_line(aes(color=case_status)) + geom_point(aes(colour=case_status)) #+ scale_colour_manual(name = 'Case status',values =c('green'='green','cadetblue' = 'cadetblue', 'orange'='orange', 'darkred'='darkred'), labels = c("closed","in progress", "assigned",'pending')) + ggtitle('Complaint status trend') + scale_x_continuous(breaks=seq(min_year, max_year, 1)) + theme_light() + theme(axis.title.y=element_blank(), #axis.text.y=element_blank(), axis.title.x=element_blank(),) #axis.text.x=element_blank()) + theme(legend.title = element_blank()) #+ theme(legend.position="left") #+ labs(color='Status') + theme(axis.title.x=element_blank()) ) }) zipsInBounds <- reactive({ if (is.null(input$map_bounds)) return(zipdata[FALSE,]) bounds <- input$map_bounds #print(bounds) latRng <- range(bounds$north, bounds$south) lngRng <- range(bounds$east, bounds$west) #print(latRng) subset(filter_rat_sightings, latitude >= latRng[1] & latitude <= latRng[2] & longitude >= lngRng[1] & longitude <= lngRng[2]) }) } #filter_rat_sightings <- filter_rat_sightings[,burough] # if (nrow(event_data("plotly_selecting"))>0){ # filter_rat_sightings <- filter_rat_sightings %>% filter(year_created %in% event_data("plotly_selecting")$Var1) # } #print('reached here') #print(filter_rat_sightings) #print('end reached here') }) # PRATISHTA'S VISUALIZATIONS ------------------------------------------------- output$pratishta1 <- renderPlotly({ p <- ggplot(rat_ton_date, aes(x=Created.Date, y=REFUSETONSCOLLECTED)) + geom_line(aes(color = Borough)) + geom_point(aes(color = Borough)) + xlab("Date by Months") + ylab("Weight of Waste (Tons)") + theme_light() p }) output$pratishta2 <- renderPlotly({ p <- ggplot(rat_ton_date, aes(x=Created.Date, y=n)) + geom_line(aes(color = Borough)) + geom_point(aes(color = Borough)) + xlab("Date by Months") + ylab("Number of rat sightings") + theme_light() p }) output$pratishta3 <- renderPlotly({ p <- ggplot(rat_ton_date, aes(x=Created.Date, y=rate)) + geom_line(aes(color = Borough)) + geom_point(aes(color = Borough)) + xlab("Date by Months") + ylab("Rate of rats per kiloton of waste") + theme_light() p }) output$pratishta4 <- renderPlotly({ ton + xlab("Boroughs") + ylab("Weight of Waste (Tons)") + theme_light() }) output$pratishta5 <- renderPlotly({ rat + xlab("Boroughs") + ylab("Number of Rat Sightings") + theme_light() }) output$pratishta7 <- renderTmap({ ## ------------------------------------------------------------------------ tm_shape(nyc_sp) + tm_fill("n", title = "Rat Sightings in Community Districts")+tm_view(set.view = c(-73.98928, 40.70042,10)) }) output$pratishta8 <- renderTmap({ ## ------------------------------------------------------------------------ tm_shape(nyc_sp) + tm_fill("total_ton", title = "Tones of Waste and Rat Sightings by DSNY Districts")+tm_view(set.view = c(-73.98928, 40.70042,10)) }) output$pratishta9 <- renderPlot({ ## ------------------------------------------------------------------------ legend_creator = function(col.regions, xlab, ylab, nbins){ bilegend = levelplot(matrix(1:(nbins * nbins), nrow = nbins), axes = FALSE, col.regions = col.regions, xlab = xlab, ylab = ylab, cuts = 8, colorkey = FALSE, scales = list(draw = 0)) bilegend } add_new_var = function(x, var1, var2, nbins, style = "quantile"){ class1 = suppressWarnings(findCols(classIntervals(c(x[[var1]]), n = nbins, style = style))) class2 = suppressWarnings(findCols(classIntervals(c(x[[var2]]), n = nbins, style = style))) x$new_class = class1 + nbins * (class2 - 1) return(x) } ## ------------------------------------------------------------------------ nyc_cd <- nyc_sp ## ------------------------------------------------------------------------ nyc_cd = add_new_var(nyc_cd, var1 = "n", var2 = "total_ton", nbins = 3) ## ------------------------------------------------------------------------ bilegend = legend_creator(stevens.pinkblue(n = 9), xlab = "rats", ylab = "total tonnes", nbins = 3) vp = viewport(x = 0.25, y = 0.25, width = 0.25, height = 0.25) pushViewport(vp) #print(bilegend, newpage = FALSE) bimap = tm_shape(nyc_cd) + tm_fill("new_class", style = "cat", palette = stevens.pinkblue(n = 9), legend.show = FALSE) + tm_layout(legend.show = FALSE) grid.newpage() vp = viewport(x = 0.37, y = 0.75, width = 0.25, height = 0.25) print(bimap, vp = viewport()) pushViewport(vp) print(bilegend, newpage = FALSE, vp = vp) }) # END OF PRATISHTA'S VISUALIZATIONS ------------------------------------------ # brendan's viz ----------------------------------------------------------- output$brendan_chart1 <- renderPlotly({ plot1 <-ggplot() + geom_bar(data=rat_borough, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("2020 rodent reports") + ylab("Number of 311 calls\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot1 }) output$brendan_chart2 <- renderPlotly({ plot2 <- ggplot() + geom_bar(data=restaurant_borough, aes(x =Borough, y= count), stat="identity", fill=rainbow(n=5)) + ggtitle("Outdoor restaurants") + ylab("Applications approved\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot2 }) output$brendan_chart3 <- renderPlotly({ plot3 <- ggplot() + geom_bar(data=inspection_count_2020, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("Restaurants w/ B or C inspection scores") + ylab("Restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot3 }) output$brendan_chart4 <- renderPlotly({ plot4 <- ggplot() + geom_bar(data=count_street, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("Street dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot4 }) output$brendan_chart5 <- renderPlotly({ plot5 <- ggplot() + geom_bar(data=count_sidewalk, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("Sidewalk dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot5 }) output$brendan_map <- renderLeaflet({ interactive_map <- leaflet() %>% addProviderTiles(providers$Stamen.TonerLite, options = providerTileOptions(noWrap = TRUE)) %>% addCircleMarkers(data=manhattan_open, lng=~Longitude, lat=~Latitude, radius=1, color= "red", fillOpacity=1, popup=~paste('Restuarant:', manhattan_open$Restaurant.Name, '<br>', 'Street Dining?', manhattan_open$Approved.for.Roadway.Seating, '<br>', 'Sidewalk Dining?', manhattan_open$Approved.for.Sidewalk.Seating, '<br>')) %>% addMarkers(data=manhattan_311,lng=~manhattan_311.Longitude, lat=~manhattan_311.Latitude, icon=icon, popup=~paste('Address:',manhattan_311$manhattan_311.Incident.Address,'<br>', 'Call Date:', manhattan_311$manhattan_311.Created.Date,'<br>','Descriptor:', manhattan_311$manhattan_311.Descriptor,'<br>'), clusterOptions= markerClusterOptions(disableClusteringAtZoom=16)) %>% setView(lng = -73.98928, lat = 40.77042, zoom = 12) }) # output$brendan_wc1 <- renderPlot({ # (wordcloud1 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area(mask=img, rm_outside = TRUE) + scale_size_area(max_size=5) + theme_classic()) # # }) # # output$brendan_wc2 <- renderPlot({ # (wordcloud2 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area() + scale_size_area()) # # }) } shinyApp(ui = ui, server = server)
/group_n/app.R
no_license
pratishta/Group_N_NYCdata
R
false
false
66,717
r
#install.packages('rsconnect') #library(rsconnect) #install.packages("shinyjs") options(scipen=999) # imports ----------------------------------------------------------------- library(shiny) library(shinyjs) library(leaflet) library(RColorBrewer) library(scales) library(lattice) library(dplyr) library(ggplot2) library(plotly) library(data.table) library(lubridate) library(leaflet.extras) library(magrittr) # chain operators, e.g. to "pipe" a value forward #library(plyr) library(tidyverse) library(DT) library(knitr) library(maps) library(rgdal) library(ggmap) library(tmap) library(sp) library(tmap) library(sf) library(stars) library(spData) library(classInt) library(lattice) library(grid) library(pals) # prajwal's data fetch ---------------------------------------------------------- # Download the data from https://data.cityofnewyork.us/api/views/3q43-55fe/rows.csv?accessType=DOWNLOAD # Alternate link: https://data.cityofnewyork.us/Social-Services/Rat-Sightings/3q43-55fe, click Export -> CSV rat_sightings <- read.csv("https://data.cityofnewyork.us/api/views/3q43-55fe/rows.csv?accessType=DOWNLOAD") #rat_sightings <- read.csv("data/Rat_Sightings.csv") rat_sightings <- rat_sightings %>% filter(!(Status=='Open')) rat_sightings <- rat_sightings %>% filter(!(Status=='Draft')) rat_sightings <- rat_sightings %>% filter(!(Borough=='Unspecified')) rat_sightings$latitude <- rat_sightings$Latitude rat_sightings$longitude <- rat_sightings$Longitude #set.seed(100) #c("BROOKLYN", "QUEENS","STATEN ISLAND") #rat_sightings_buroughs <- c("BROOKLYN", "QUEENS","STATEN ISLAND") # PRATISHTA'S DATA FETCH ------------------------------------------------------- # read in the main csv file rat_data<-read.csv("data/rat_data.csv") rat_data <- rat_data %>% mutate(Borough = str_to_title(rat_data$Borough)) tonnage_data<-read.csv("data/dsny_boro_tonnage.csv", stringsAsFactors = FALSE) ton_date <- tonnage_data %>% mutate(MONTH = paste(MONTH, " / 01")) %>% mutate(MONTH = as.Date(MONTH, format = '%Y / %m / %d')) %>% filter(MONTH > as.Date('2020-01-01', '%Y-%m-%d'), MONTH < as.Date('2021-03-01', '%Y-%m-%d')) %>% arrange(desc(MONTH)) rat_date <- rat_data %>% mutate(Created.Date = as.Date(Created.Date, "%m/%d/%Y")) %>% mutate(Created.Date = as.character(Created.Date)) %>% mutate(Created.Date = substr(Created.Date, 1, 8)) %>% mutate(Created.Date = paste(Created.Date, '01')) %>% mutate(Created.Date = as.Date(Created.Date, "%Y-%m-%d")) %>% group_by(Created.Date, Borough) %>% tally() %>% filter(Created.Date > as.Date('2020-01-01', '%Y-%m-%d'), Created.Date < as.Date('2021-03-01', '%Y-%m-%d')) %>% arrange(desc(Created.Date)) rat_ton_date <- merge(rat_date, ton_date, by.x = c("Created.Date", "Borough"), by.y = c("MONTH", "BOROUGH")) %>% mutate(rate = n / (REFUSETONSCOLLECTED / 100)) # END OF PRATISHTA'S DATA FETCH ------------------------------------------------ # PRATISHTA'S CODE ------------------------------------------------------------- # community district conversion functions convertBoroCDToDistrict <- function(borocd) { sapply(borocd, function(borocd) { boro_ch = as.character(borocd) boro_n = substr(boro_ch, 1, 1) cd_n = substr(boro_ch, 2, 3) boro = case_when (boro_n == '1' ~ 'MN', boro_n == '2' ~ 'BX', boro_n == '3' ~ 'BK', boro_n == '4' ~ 'QW', boro_n == '5' ~ 'SI' ) ans <- paste(boro, cd_n, sep="") return (ans) }) } convertToShpDistrict <- function(com_district) { sapply(com_district, function(com_district) { split = strsplit(com_district, " ") boro = case_when (str_to_lower(split[[1]][2]) == 'brooklyn' ~ 'BK', str_to_lower(split[[1]][2]) == 'manhattan' ~ 'MN', str_to_lower(split[[1]][2]) == 'queens' ~ 'QW', str_to_lower(split[[1]][2]) == 'staten' ~ 'SI', str_to_lower(split[[1]][2]) == 'bronx' ~ 'BX' ); ans <- paste(boro, split[[1]][1], sep="") return (ans) }) } # reading in data and modify string format of community district column full_tonnage <-read.csv("sanitation_data/dsny_full_tonnage.csv", stringsAsFactors = FALSE) full_tonnage <- full_tonnage %>% mutate(district = paste(full_tonnage$COMMUNITYDISTRICT, str_to_upper(full_tonnage$BOROUGH))) district = paste(full_tonnage$COMMUNITYDISTRICT, str_to_upper(full_tonnage$BOROUGH)) # creating data to be mapped ton_map <- full_tonnage %>% mutate(community_district = convertToShpDistrict(district)) %>% group_by(community_district) %>% summarise(total_ton = sum(REFUSETONSCOLLECTED)) ton_map community_district <- paste(rat_data$Community.Board, str_to_upper(rat_data$Community.Board)) rat_map <- rat_data %>% mutate(community_district = convertToShpDistrict(community_district)) %>% group_by(community_district) %>% tally() rat_map rat_borough <- rat_data %>% group_by(Borough) %>% tally() rat_borough ton_boro <- tonnage_data %>% group_by(BOROUGH) %>% summarise(total_ton = sum(REFUSETONSCOLLECTED)) ton_boro rat_ton <- left_join(rat_borough, ton_boro, by = c("Borough" = "BOROUGH")) rat <- ggplot(rat_ton, aes(y=n, x=Borough, fill = Borough)) + geom_bar(position="dodge", stat="identity") ton <- ggplot(rat_ton, aes(y=total_ton, x=Borough, fill = Borough)) + geom_bar(position="dodge", stat="identity") # map data nyc <- readOGR("sanitation_data/CommunityDistricts/.", "geo_export_d81daad1-2b49-44c3-81d4-72436a58def3") nyc_sp <- spTransform(nyc, CRS("+proj=longlat +datum=WGS84")) nyc_sp@data <- nyc_sp@data %>% mutate(community_district = convertBoroCDToDistrict(boro_cd)) nyc_sp@data nyc_sp@data <- left_join(nyc_sp@data, rat_map) nyc_sp@data nyc_sp@data <- left_join(nyc_sp@data, ton_map) nyc_sp@data # END OF PRATISHTA'S CODE------------------------------------------------------- # shiny code # brendan's imports and code ------------------------------------------------------- library(ggplot2) library(ggthemes) library(gridExtra) library(dplyr) library(readr) library(leaflet) library(leaflet.extras) library(magrittr) library(dplyr) library(tidyr) library(wordcloud) library(png) library(ggwordcloud) library(tidytext) library(readr) library(png) #setwd("~/Bayesian") open <- read.csv("data/Open_Restaurant_Applications.csv") inspection <- read.csv("data/DOHMH_New_York_City_Restaurant_Inspection_Results.csv") rat_311 <- read.csv("data/311_Service_Requests_from_2010_to_Present.csv") restaurant_borough <- count(open, Borough) names(restaurant_borough)[names(restaurant_borough) == "n"] <- "count" rat_borough <- count(rat_311, Borough) borough <- c("Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island", "none") rat_borough <- cbind(rat_borough, borough) %>% filter(borough!= "none") rat_borough <- select(rat_borough, borough, n) names(rat_borough)[names(rat_borough) == "n"] <- "count" names(rat_borough)[names(rat_borough) == "borough"] <- "Borough" inspection_bc <- inspection %>% filter(GRADE == "B" | GRADE == "C") inspection_count_2020 <- count(inspection_bc, BORO) names(inspection_count_2020)[names(inspection_count_2020) == "n"] <- "count" names(inspection_count_2020)[names(inspection_count_2020) == "BORO"] <- "Borough" street_seating <- filter(open, Approved.for.Roadway.Seating == "yes") count_street <- count(street_seating, Borough) names(count_street)[names(count_street) == "n"] <- "count" sidewalk_seating <- filter(open, Approved.for.Sidewalk.Seating == "yes") count_sidewalk <- count(sidewalk_seating, Borough) names(count_sidewalk)[names(count_sidewalk) == "n"] <- "count" manhattan_311 <- filter(rat_311, Borough == "MANHATTAN") #manhattan_311 <- read.csv("manhattan311.csv") manhattan_open <- read.csv("data/manhattan open restaurants.csv") manhattan_311 <- filter(manhattan_311, manhattan_311$Complaint.Type=="Rodent") manhattan_311 <- data.frame(manhattan_311$Latitude, manhattan_311$Longitude, manhattan_311$Incident.Address, manhattan_311$Created.Date, manhattan_311$Descriptor) icon <- makeIcon(iconUrl= "https://cdn3.iconfinder.com/data/icons/farm-animals/128/mouse-512.png", iconWidth=25, iconHeight = 20) #manhattan_311b <- read.csv("manhattan311.csv") #manhattan_311b <- read.csv("https://nycopendata.socrata.com/api/views/erm2-nwe9/rows.csv?accessType=DOWNLOAD") # code for making wordcloud (not used in live version for processing power reasons) ----------------------------------------------- # manhattan_311b <- filter(rat_311, Borough == "MANHATTAN") # nrow(manhattan_311b) # # manhattan_311b <- manhattan_311b %>% filter(Complaint.Type != "Noise = Street/Sidewalk" & Complaint.Type != "Noise - Residential" & Complaint.Type != "HEAT/HOT WATER" & Complaint.Type != "Illegal Parking" & Complaint.Type != "Non-Emergency Police Matter" & Complaint.Type != "Noise" & Complaint.Type != "Noise - Vehicle" & Complaint.Type != " Noise - Commercial") # descriptors <- manhattan_311b %>% select(Descriptor) # descriptors_fix <- as.character(descriptors$Descriptor) # text_df <- tibble(line = 1:length(descriptors_fix), text = descriptors_fix) # descriptors <- text_df %>% unnest_tokens(word, text) # # descriptors <- count(descriptors, word) # descriptors2 <- filter(descriptors, n > 2000) # col <- c(ifelse(descriptors2$word == "pests" | descriptors2$word == "rat" | descriptors2$word == "sighting" | descriptors2$word == "rodents", "red", "black")) # descriptors3 <- cbind(descriptors2, col) # descriptors3 <- filter(descriptors3, word != "n" & word != "a" & word != "not" & word != "business" & word != "no" & word!= "compliance" & word != "or" & word != "in" & word != "of" & word!= "to" & word!= "non" & word!= "on" & word != "has" & word!= "for") # #setwd("~/Bayesian") # img <- readPNG("data/rat.png") # #img <- icon # descriptors3 <- descriptors3 %>% filter(word != "loud" & word!= "music" & word != "party") # set.seed(14) # (wordcloud1 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area(mask=img, rm_outside = TRUE) + scale_size_area(max_size=5) + theme_classic()) # (wordcloud2 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area() + scale_size_area()) # user interface for setting layout of plots ---------------------------------------------------------- # sliders and interactive map --------------------------------------------- rat_sightings_buroughs <- as.character(unique(unlist(rat_sightings$Borough))) rat_sightings_case_status <- as.character(unique(unlist(rat_sightings$Status))) ui <- fluidPage( # header description ------------------------------------------------------ tags$head( # Note the wrapping of the string in HTML() tags$style(HTML(" .row { margin-left: 0; margin-right:0; }")) ), fluidRow(align = "center", h1("Rats and NYC: Exploratory Visualization"), strong("Data Visualization (QMSS - G5063) Final Project, Spring 2021"), br(), em("Group N: Brendan Mapes, Prajwal Seth, and Pratishta Yerakala"), h3(a("Link to code and process book", href="https://github.com/QMSS-G5063-2021/Group_N_NYCdata")), br(),br(),br(), p("In this project, we will explore in detail New York City's rat problem. New York has always dealt with a relatively high population of rats, as do many other large metropolitan areas. However, since the beginning of the COVID-19 pandemic rat sightings have been on the rise. Rats are being seen more often, during new times of day, and are acting more aggressive. Through the following visualizations we hope to find some explanation for this recent uptick in rat sightings. The way restaurants and residents handle their trash plays a large role in the survival and behavior of rats in the city. So through exploration of city sanitation data, restaurant registration data, and 311 calls in the city, we hope to find some potential explanations as to why New York's rat problem has gotten so bad."),), br(),br(),br(), # prajwal's description --------------------------------------------------- # fluidRow( # align = "center", # headerPanel("Hello 1!"), # p("p creates a paragraph of text."), # p("A new p() command starts a new paragraph. Supply a style attribute to change the format of the entire paragraph.", style = "font-family: 'times'; font-si16pt"), # strong("strong() makes bold text."), # em("em() creates italicized (i.e, emphasized) text."), # br(), # code("code displays your text similar to computer code"), # div("div creates segments of text with a similar style. This division of text is all blue because I passed the argument 'style = color:blue' to div", style = "color:blue"), # br(), # p("span does the same thing as div, but it works with", # span("groups of words", style = "color:blue"), # "that appear inside a paragraph."), # ), fluidRow( align = "center", style='margin-left:0px; margin-right: 0px;', h2("Interactive map of rodent complaints in NYC since 2010"), h3("Prajwal Seth"), br(), ), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings (automatically updated daily)", href="https://data.cityofnewyork.us/Social-Services/Rat-Sightings/3q43-55fe"), br(), h4("Background:"), p("In this section, I have visualized rodent complaints from 2010 till today submitted to the NYC311 portal. Feel free to play around with the provided filters for number of samples, years, boroughs, and case status (however, due to processing constraints on shinyapps.io, the website will crash if you set the number of samples too high). The map on the left will dynamically update as you change the filters (or will not update if there is no data to display after the filters are applied). The plot for the trend in complaint status also updates according to the rat complaints that are visible in the map. Upon zooming into the map, you will see that the color of the marker for each complaint is set according to the complaint status (refer to the legend of the map). Also provided is a tooltip displaying the complaint's created date, closed date, address, status, and location type. There is a layer of heat added to the map, with the intensity of the heat being calculated based on the number of rat sightings in the area."), ), ), # sliders and map etc ----------------------------------------------------- fluidRow( sidebarLayout(position = "right", sidebarPanel(width = 6, sliderInput("num_sample", label = h4("Select number of random samples"), min = 1, max = nrow(rat_sightings), value = 1000, step = 1000), sliderInput("year_input", label = h4("Select years"), min = 2010, max = 2021, value = c(2010, 2021), step = 1, format = "####"), #selected = rat_sightings_buroughs[1:length(multiInput)]) #selected = rat_sightings_buroughs, selectizeInput("burough_input", label=h4("Select boroughs"), choices =rat_sightings_buroughs, multiple = TRUE, selected = rat_sightings_buroughs), selectizeInput("case_status", label=h4("Select status"), choices =rat_sightings_case_status, multiple = TRUE, selected = rat_sightings_case_status), #plotlyOutput("cityViz", height = 300), plotlyOutput("yearViz", height = 250), #plotlyOutput("locationViz", height = 220), #plotlyOutput("locationViz", height = 300), ), mainPanel(width = 6, style='margin-top:40px;', leafletOutput("map", height = 825), ), ), # PRATISHTA'S WRITEUP -------------------------------------------------------- fluidRow( align = "center", style='margin-left:0px; margin-right: 0px;', h2("Rat Sightings and Sanitation Waste by Borough"), h3("Pratishta Yerakala"), br(), ), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("filtered for rodent sightings between Feb 2020 and Feb 2021.")), h5(a("DSNY Monthly Tonnage", href="https://data.cityofnewyork.us/City-Government/DSNY-Monthly-Tonnage-Data/ebb7-mvp5"), h6("filtered for months between Feb 2020 and Feb 2021.")), h5(a("NYC Community Districts Shapefile", href="https://data.cityofnewyork.us/City-Government/Community-Districts/yfnk-k7r4")), ), div(class='padding', h4("Background:"), p("The large rodent population in New York City is no secret. Rats have been associated with the city for a long time whether it's from the famous", a('pizza rat', href='https://knowyourmeme.com/memes/pizza-rat'), "or to the rising concern from residents who have noticed changes since the COVID-19 pandemic. Many businesses and normally occurring procedures have been slowed down or halted completely. One such example in particular with the Department of Sanitation of NY (DSNY) where limited resources and budget cuts since the pandemic have caused an", a("increased amount of litter and waste production", href="https://patch.com/new-york/new-york-city/city-state-leaders-decry-sanitation-setback-trash-piles"), "."), ) ), fluidRow( align = "center", div(class='padding', h4(align = "left", "Visualizations:"), ), # descriptive charts h3("Total Number of Rat Sightings (2020-2021)"), h6("Chart 1"), plotlyOutput("pratishta5", width = "50%"), br(), h3("Total Waste Produced (2020-2021)"), h6("Chart 2"), plotlyOutput("pratishta4", width = "50%"), br(), p(class = "padding", align = "left", "We can see in Chart 1 that Brooklyn produces the most tons of waste followed by Queens, and then by Bronx and Manhattan. Staten Island is last with the least amount of waste. Chart 2 shows the number of rat sightings per borough and naturally, we have Brooklyn at the top with around 6,000 sightings. But Instead of Queens, Manhattan follows with most rat s ightings. Then Queens and Bronx. From here it seems that Staten Island and Bronx are boroughs that have some what proportional sightings to waste produced. However, though Queens produces a lot of waste, it does not have nearly the same rate of rat sightings. Conversely, Manhattan doesn't quite produce the same amount of waste as Queens but seems to have far more rat sightings. Brooklyin is consistenly infested."), # time series charts h3("Waste per Month (2020-2021)"), h6("Chart 3"), plotlyOutput("pratishta1", width = "70%"), br(), h3("Rat Sightings per Month (2020-2021)"), h6("Chart 4"), plotlyOutput("pratishta2", width = "70%"), br(), h3("Rate of Rats per Waste Ton per Month"), h6("Chart 5"), plotlyOutput("pratishta3", width = "70%"), br(), p(class = "padding", align = "left", "Charts 3 to 5 show a time series line graphs. Chart 3 shows the tons of waste per month generated by each borough. It seems that around March and April of 2020 there was a change in the trend. Though the waste was rising, it flattened out - or even fell like with Manhattan for example - between March and April of 2020. But after april there was a more mellow rise and then gentle decline closer to Fall of 2020 and early 2021. This exploratory chart is good to possibly check out Manhattan and why the waste production went down. Perhaps for restaurants closing?"), p(class = "padding", align = "left", "Chart 4 shows that all boroughs saw an increase in rat sightings, especially Brooklyn. It did seem to peak around summer of 2020 and decline again to almost normal rates. These sightings might be due to the sanitation departments' limits as mentioned earlier."), p(class = "padding", align = "left", "Chart 5 looks at the 'rate' at which a rat sighting is possible for every kilo-ton of waste produced in each borough per month. It seems that these rates also follow a similar path of an increase around April 2020 and then a peak in summer of 2020 and then a mellow decline. However Manhattan's rate shot up for early 2021 with around 0.75 (sightings per ton of waste) to 1.5 (sightings per ton of waste). Perhaps this could be due to frequent testings, vaccinations, and re-opening of restaurants (producing more waste)?"), # maps h3("Number of Rat Sightings per Month"), h6("Chart 6"), ), fluidRow( tmapOutput("pratishta7", width = "100%"), br(), ), fluidRow(align = "center", h3("Waste Produced in Tons"), h6("Chart 7"), ), fluidRow( tmapOutput("pratishta8", width = "100%"), br(), ), fluidRow( align = "center", h3("Rat Sightings and Waste Produced By Community District"), h6("Chart 8"), plotOutput("pratishta9", width = "60%"), br(), p(class = "padding", align = "left", "Here we show choropleth maps of NYC by community district. Community district as the geographical feature here is because DSNY also records their information with that feature. It seems that there is one community districte that's seeing a severe rise in rat sightings (BK03). It may be worth it to take a closer look at that particular district if analysis or further studie are done."), p(class = "padding", align = "left", "As expected it looks like Queens produces a massive amount of waste and the particular districts are highlighted in deep red (100,000 - 120,000 tons category). And though Brooklyn also produces a lot of waste it seems to be spread out amongst the community districts."), p(class = "padding", align = "left", "Chart 8 depicts a bivariate choropleth map of the community districts. This make-shift rendering of a map using the tm_map package is from", a("this currently open issue from the tmap GitHub repsitory", href="https://github.com/mtennekes/tmap/issues/183#issuecomment-670554921"), ". As the districts become more blue in color, the more right sightings that have been reported in that district. The more purple a district, the more amount of waste produced there. As the color goes to indigo, there's a high rat sighting and a high waste production (a high high category if further spatial dependence analysis was conducted). Light grey represents few rat sightings and little waste production (a 'low low' again for further spatial research). This map demonstrates that hough there are high rat sightings in downtown Manhattan and parts of Brooklyn, it's not necessarily tied to waste production. In the same way, the outer boroughs have a huge waste production but not many rat sightings. But there are some districts (indigo) that do exhibit both features in high amounts. This exploratory data visulaization provides the insight to further look in those districts.") ), # Brendan's writeup ------------------------------------------------- fluidRow( align = "center", h2("Rat Sightings and Restaurants by Borough"), h3("Brendan Mapes"), br(), ), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("Filtered to 311 calls from Jan 1 2020 to Dec 31 2020, of complaint type β€œrodent”.")), h5(a("Open Restaurants", href="https://data.cityofnewyork.us/Transportation/Open-Restaurant-Applications/pitm-atqc/data"),), ), div(class='padding', h4("Background:"), p("It is well documented that the COVID-19 pandemic has led to a rise in rat sightings throughout New York City. It is also well known that the pandemic has been especially hard on the restaurant industry. Hit especially hard by stay-at-home orders and social distancing mandates, restaurants have been forced to innovate their operations. Now more than ever, restaurants are serving customers outside in the streets. We suspect this change in the way restaurants do their business may be contributing to the increase in rat sightings. We explore this possibility a bit further in the next few visualizations."), ), div(class='padding', h4("Visualizations:"), ), ), # descriptive charts # fluidRow(align = "center", # br(), # h3("NYC311 rodent complaints in 2020 and number of restaurants by type"), # h6("Chart 9"),br(), # plotOutput("brendan_chart1", width = "80%"), # plotOutput("brendan_chart2", width = "80%"), # br(), # br(), # p(class = "padding", align = "left", "In all four figures, we can see that Manhattan is far above the rest of the boroughs in restaurants # approved for outdoor dining, in sidewalk and street dining. However, it is Brooklyn that is far above the # rest of the boroughs in rodent reports in 2020. This suggests that perhaps another factor is contributing # to the rat problem in the Brooklyn borough. If restaurants were fully to blame for it’s rat problem, we # would expect to see it having high numbers of restaurants approved for outdoor street and sidewalk # dining, a number comparable to the borough of Manhattan. # # The first bar plot displays the number of rodent related 311 reports in the year 2020 by borough. # Brooklyn leads the way with well over 10,000 rodent related calls in the year, while the next closest # borough, Manhattan, only has about 8,000 rodent related calls in the year. In the bar plots related to # restaurants, we see Manhattan leads the way across the board. In the restaurants with outdoor dining, # sidewalk and street dining, Manhattan has twice as many restaurants than any other borough. Because # of this vast difference in the number of restaurants in Manhattan compared to the other boroughs, we # will narrow our focus to Manhattan in the next visualization."),), fluidRow(align = "center", br(), br(), br(), # code for generating these plots # title: "brendan2" # author: "Brendan Mapes" # date: "4/17/2021" # output: html_document # --- # # ```{r setup, include=TRUE} # knitr::opts_chunk$set(echo = TRUE) # library(ggplot2) # library(ggthemes) # library(gridExtra) # library(dplyr) # library(plotly) # open <- read.csv("Open_Restaurant_Applications.csv") # inspection <- read.csv("DOHMH_New_York_City_Restaurant_Inspection_Results.csv") # rat_311 <- read.csv("311_Service_Requests_from_2010_to_Present.csv") # restaurant_borough <- count(open, Borough) # names(restaurant_borough)[names(restaurant_borough) == "n"] <- "count" # rat_borough <- count(rat_311, Borough) # borough <- c("Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island", "none") # rat_borough <- cbind(rat_borough, borough) %>% filter(borough!= "none") # rat_borough <- select(rat_borough, borough, n) # names(rat_borough)[names(rat_borough) == "n"] <- "count" # names(rat_borough)[names(rat_borough) == "borough"] <- "Borough" # inspection_bc <- inspection %>% filter(GRADE == "B" | GRADE == "C") # inspection_count_2020 <- count(inspection_bc, BORO) # names(inspection_count_2020)[names(inspection_count_2020) == "n"] <- "count" # names(inspection_count_2020)[names(inspection_count_2020) == "BORO"] <- "Borough" # street_seating <- filter(open, Approved.for.Roadway.Seating == "yes") # count_street <- count(street_seating, Borough) # names(count_street)[names(count_street) == "n"] <- "count" # sidewalk_seating <- filter(open, Approved.for.Sidewalk.Seating == "yes") # count_sidewalk <- count(sidewalk_seating, Borough) # names(count_sidewalk)[names(count_sidewalk) == "n"] <- "count" # plot1 <- ggplot() + geom_bar(data=rat_borough, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("2020 rodent reports") + ylab("Number of 311 calls\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot2 <- ggplot() + geom_bar(data=restaurant_borough, aes(x =Borough, y= count, fill =Borough), stat="identity") + ggtitle("Outdoor restaurants") + ylab("Applications approved\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot3 <- ggplot() + geom_bar(data=inspection_count_2020, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("Restaurants w/ B or C inspection scores") + ylab("Restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot4 <- ggplot() + geom_bar(data=count_street, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("Street dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot5 <- ggplot() + geom_bar(data=count_sidewalk, aes(x=Borough, y=count, fill=Borough), stat="identity") + ggtitle("Sidewalk dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) # plot1a <- ggplotly(plot1, tooltip=c("x", "y")) # plot2a <- ggplotly(plot2, tooltip=c("x", "y")) # plot3a <- ggplotly(plot3, tooltip=c("x", "y")) # plot4a <- ggplotly(plot4, tooltip=c("x", "y")) # plot5a <- ggplotly(plot5, tooltip=c("x", "y")) # plot1a # plot2a # plot3a # plot4a # plot5a h6("Chart 9"), plotlyOutput("brendan_chart1" ,width="50%"), br(), h6("Chart 10"), plotlyOutput("brendan_chart2",width="50%"), br(), h6("Chart 11"), plotlyOutput("brendan_chart3",width='50%'), br(), h6("Chart 12"), plotlyOutput("brendan_chart4",width='50%'), br(), h6("Chart 13"), plotlyOutput("brendan_chart5",width='50%'), br(), p(class = "padding", align = "left", "In all five figures, we can see that Manhattan is far above the rest of the boroughs in restaurants approved for outdoor dining, in sidewalk and street dining, and B and C graded restaurants. However, it is Brooklyn that is far above the rest of the boroughs in rodent reports in 2020. This suggests that perhaps another factor is contributing to the rat problem in the Brooklyn borough. If restaurants were fully to blame for it’s rat problem, we would expect to see it having high numbers of restaurants approved for outdoor street and sidewalk dining, a number comparable to the borough of Manhattan. The first bar plot displays the number of rodent related 311 reports in the year 2020 by borough. Brooklyn leads the way with well over 10,000 rodent related calls in the year, while the next closest borough, Manhattan, only has about 8,000 rodent related calls in the year. In the bar plots related to restaurants, we see Manhattan leads the way across the board. In the restaurants with outdoor dining, sidewalk and street dining, Manhattan has twice as many restaurants than any other borough. Because of this vast difference in the number of restaurants in Manhattan compared to the other boroughs, we will narrow our focus to Manhattan in the next visualization."),br(),br(), ), ), br(), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("Filtered to 311 calls from Jan 1 2020 to Dec 31 2020, of complaint type β€œrodent” in Manhattan borough.")), h5(a("Open Restaurants", href="https://data.cityofnewyork.us/Transportation/Open-Restaurant-Applications/pitm-atqc/data"),h6("Filtered to Manhattan borough.")), ), div(class='padding', h4("Visualization:"), ), fluidRow(align = "center", h3("Rat sightings in 2020 overlaid on restaurant locations in Manhattan"), h6("Chart 14"),),br(), fluidRow( leafletOutput("brendan_map", height = 500, width = "100%"), br(), br(), p(class = "padding", align = "left", "Based off exploratory analysis of the restaurants and rat reports across all boroughs, it’s clear Manhattan’s restaurant industry may be most closely linked to the rat problem than in other boroughs. For that reason, we have provided an interactive map visualization of the Manhattan borough specifically. In the map, restaurants are plotted and viewers can see the location and name of the restaurant, along with whether or not the restaurant is available for open street or sidewalk dining. Also charted on the map are the location of rat sightings in the 2020 311 calls data set, the same data used for previous visualizations. With no zoom, clusters of the rats are displayed in the visualization. After zooming in further, those clusters break into the individual rat sighting locations of which they consist. Rat sighting locations are represented by small rat icons on the map."), p(class = "padding", align = "left", "This visualization allows viewers to identify densely rat populated locations on the map and relate that information to the data provided for restaurants in the same locations. In real time, such a map would be useful for avoidance of rat β€œhot spots” when choosing places to dine. It also allows users to explore which restaurants have practices that may be contributing to the rat problem the most, with lots of rat sightings nearby."),), fluidRow( tags$style(".padding { margin-left:30px; margin-right:30px; }"), tags$style(".leftAlign{float:left;}"), align = "left", div(class='padding', h4("Data used:"), h5(a("Rat sightings", href="https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9"), h6("Filtered to 311 calls from Jan 1 2020 to Dec 31 2020, of complaint type 'rodent' in Manhattan borough. Calls related to noise, parking violations, and other non-emergency police related matters are also excluded from this visualization.")), ), div(class='padding', h4("Visualization:"), ), ), fluidRow(align = "center", h3("Wordcloud of the descriptor variable of all NYC311 complaints in 2020"), br(), h6("Chart 15"), img(src='Capture.PNG',width="50%"), br(), h6("Chart 16"), img(src='Picture2.png',width="50%"), br(), h6("For reference:"), img(src='rat.png',), br(), br(), p(class = "padding", align = "left", "For required text analysis, we have again referred to the 2020 rodent related 311 reports, specifically on the descriptor variable, where various notes are left on the nature or details of the complaint. Two word clouds are presented. The first is a basic wordcloud created with the ggwordcloud package. Words related to rat sightings are differentiated from others by color. Viewers can see in this wordcloud that the descriptor variable does have lots of mentions of rodent related issues. The second wordcloud presented is also from the ggwordcloud package, but with an added mask, intended to create a wordcloud the shape of a rat. This visualization is slightly more visually appealing, but reveals the exact same information to the reader. Rat sightings are often mentioned in the descriptor variable of the data set."),br(),br() ), # fluidRow( # align = "center", # plotOutput("brendan_wc1"), # plotOutput("bendan_wc2"), # ), ), ) ) # code for generating the plots ----------------------------------------------------------------- server <- function(input, output, session) { # prajwal's code for generating interactive map backend ------------------- # points <- eventReactive(input$recalc, { # cbind(rat_sightings_sample$latitude, rat_sightings_sample$longitude) # }, ignoreNULL = FALSE) # observe({ min_year <- input$year_input[1] max_year <- input$year_input[2] burough <- input$burough_input case_status1 <- input$case_status rat_sightings_sample <- rat_sightings[sample.int(nrow(rat_sightings), input$num_sample),] #rat_sightings_sample <- rat_sightings latitude_colnum <- grep('latitude', colnames(rat_sightings_sample)) longitude_colnum <- grep('longitude', colnames(rat_sightings_sample)) rat_sightings_sample <- rat_sightings_sample[complete.cases(rat_sightings_sample[,latitude_colnum:longitude_colnum]),] rat_sightings_sample$year_created <- year(parse_date_time(rat_sightings_sample$Created.Date, '%m/%d/%y %I:%M:%S %p')) #print('buroughh') #print(burough) #filter_rat_sightings <- rat_sightings_sample %>% filter(year_created >= min_year, year_created <= max_year, Borough %in% burough) check_rows_of_filter <- nrow(rat_sightings_sample %>% filter(year_created >= min_year, year_created <= max_year, Borough %in% burough, Status %in% case_status1)) rat_sightings_buroughs2 <- as.character(unique(unlist(rat_sightings_sample$Borough))) rat_sightings_case_status2 <- as.character(unique(unlist(rat_sightings_sample$Status))) # print('buroughs 2') # print(rat_sightings_buroughs2) # print('case statuses 2') # print(rat_sightings_case_status2) if (check_rows_of_filter <= 0){ #updateSliderInput(session, "year_input", value = c(2010, 2021)) #updateSliderInput(session, "burough_input", value = rat_sightings_buroughs2) #updateSliderInput(session, "case_status", value = rat_sightings_case_status2) # filter_rat_sightings2 <- rat_sightings_sample # reset("year_input") # reset("burough_input") # reset("burough_input") # print('in the case of 0 rows, resetting to entire df') leaflet() %>% addProviderTiles(providers$Stamen.TonerLite, options = providerTileOptions(noWrap = TRUE) ) %>% setView(lng = -73.98928, lat = 40.75042, zoom = 10) } else{ filter_rat_sightings2 <- rat_sightings_sample %>% filter(year_created >= min_year, year_created <= max_year, Borough %in% burough, Status %in% case_status1) filter_rat_sightings <- filter_rat_sightings2 getColor <- function(filter_rat_sightings, i) { if(filter_rat_sightings$Status[i] == "Closed") { "green" } else if(filter_rat_sightings$Status[i] == "In Progress") { "lightblue" } else if(filter_rat_sightings$Status[i] == "Assigned") { "orange" } else if(filter_rat_sightings$Status[i] == "Open") { "purple" } else if(filter_rat_sightings$Status[i] == "Pending") { "darkred" } else if(filter_rat_sightings$Status[i] == "Draft") { "blue" }} markerColors <- rep(NA, nrow(filter_rat_sightings)) for (i in 1:nrow(filter_rat_sightings)){ markerColors[i] <- getColor(filter_rat_sightings, i) } icons <- awesomeIcons( icon = 'ios-close', iconColor = 'cadetblue', library = 'ion', markerColor = markerColors ) output$map <- renderLeaflet({ leaflet(data = filter_rat_sightings) %>% addProviderTiles(providers$Stamen.TonerLite, options = providerTileOptions(noWrap = TRUE) ) %>% setView(lng = -73.98928, lat = 40.75042, zoom = 10) %>% addAwesomeMarkers( ~longitude, ~latitude, clusterOptions = markerClusterOptions() ,icon = icons, popup = as.character(paste('Created date:', filter_rat_sightings$Created.Date,'<br>', 'Closed Date:', filter_rat_sightings$Closed.Date,'<br>', #'Complaint type:',filter_rat_sightings$Complaint.Type,'<br>', #'Descriptor:',filter_rat_sightings$Descriptor,'<br>', 'Address:',filter_rat_sightings$Incident.Address,'<br>', 'Status:', filter_rat_sightings$Status, '<br>', 'Location Type:', filter_rat_sightings$Location.Type))) %>% addHeatmap( ~longitude, ~latitude, group = "heat",max=1, blur = 45, minOpacity = 0.8) %>% addLegend("topleft", colors =c('green', "darkred", "lightblue", "orange"), #"purple", "#56a0d1" labels= c("Closed", "Pending", "In Progress","Assigned"), # "Open", "Draft" title= "Complaint status", opacity = 1) }) output$cityViz <- renderPlotly({ if (nrow(zipsInBounds()) == 0) return(NULL) tmp <- (zipsInBounds() %>% count(City)) tmp <- tmp[order(-tmp$n),] tmp <- tmp[1:5,] ggplotly( ggplot(tmp, aes(x=City, y=n, fill = City)) + geom_bar(stat="identity") + ylab("Top 5 visible buroughs") + theme(legend.position = "none") + scale_color_brewer(palette="Dark2")+ theme(axis.title.x=element_blank(), axis.ticks.x=element_blank()) ) }) output$locationViz <- renderPlotly({ if (nrow(zipsInBounds()) == 0) return(NULL) tmp <- (zipsInBounds() %>% count(Location.Type)) tmp <- tmp[order(-tmp$n),] tmp <- tmp[1:5,] ggplotly(tooltip = c("n"), ggplot(tmp, aes(x=Location.Type, y=n)) + geom_bar(stat="identity", aes(fill = Location.Type)) + ggtitle('Visible location types') + ylab("Visible location types") + theme_light()+ theme(axis.title.y=element_blank(), #axis.text.y=element_blank(), axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) + labs(fill = "Visible location types") + coord_flip() + theme(legend.position = "none") ) }) output$yearViz <- renderPlotly({ if (nrow(zipsInBounds()) == 0) return(NULL) # total cases created_date_sample <- data.table(zipsInBounds()$Created.Date) created_date_sample$dates <- parse_date_time(created_date_sample$V1, '%m/%d/%y %I:%M:%S %p') plot_created_year <- data.frame(table(year(date(created_date_sample$dates)))) for (i in 2010:2021){ if ((i %in% plot_created_year$Var1)==FALSE) { #print(i) tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- c('Var1','Freq') plot_created_year <- rbind(plot_created_year, tmp_df) } } plot_created_year$Var1 <- as.numeric(as.character(plot_created_year$Var1)) names(plot_created_year)[names(plot_created_year) == "Var1"] <- "Year" plot_created_year <- plot_created_year[order(plot_created_year$Year),] plot_created_year <- filter(plot_created_year, Year >= min_year, Year <= max_year) plot_created_year$case_status <- 'Total' # closed cases plot_closed<- filter(zipsInBounds(), Status == 'Closed') flag_closed <- 0 if (nrow(plot_closed) == 0) { flag_closed <- 1 } if (flag_closed == 0){ plot_closed <- data.table(plot_closed$Created.Date) plot_closed$dates <- parse_date_time(plot_closed$V1, '%m/%d/%y %I:%M:%S %p') plot_closed_year <- data.frame(table(year(date(plot_closed$dates)))) #print(plot_closed_year) for (i in 2010:2021){ if ((i %in% plot_closed_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_closed_year) plot_closed_year <- rbind(plot_closed_year, tmp_df) } } plot_closed_year$Var1 <- as.numeric(as.character(plot_closed_year$Var1)) names(plot_closed_year)[names(plot_closed_year) == "Var1"] <- "Year" plot_closed_year <- plot_closed_year[order(plot_closed_year$Year),] plot_closed_year <- filter(plot_closed_year, Year >= min_year, Year <= max_year) plot_closed_year$case_status <- 'Closed' } # assigned cases plot_assigned<- filter(zipsInBounds(), Status == 'Assigned') flag_assigned <- 0 if (nrow(plot_assigned) == 0) { flag_assigned <- 1 } if (flag_assigned == 0){ plot_assigned <- data.table(plot_assigned$Created.Date) plot_assigned$dates <- parse_date_time(plot_assigned$V1, '%m/%d/%y %I:%M:%S %p') plot_assigned_year <- data.frame(table(year(date(plot_assigned$dates)))) #print(plot_assigned_year) for (i in 2010:2021){ if ((i %in% plot_assigned_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_assigned_year) plot_assigned_year <- rbind(plot_assigned_year, tmp_df) } } plot_assigned_year$Var1 <- as.numeric(as.character(plot_assigned_year$Var1)) names(plot_assigned_year)[names(plot_assigned_year) == "Var1"] <- "Year" plot_assigned_year <- plot_assigned_year[order(plot_assigned_year$Year),] plot_assigned_year <- filter(plot_assigned_year, Year >= min_year, Year <= max_year) plot_assigned_year$case_status <- 'Assigned' #print('assigned or in progress') #print(plot_assigned_year) } # assigned or in progress cases plot_in_progress<- filter(zipsInBounds(), Status == 'In Progress') flag_in_progress <- 0 if (nrow(plot_in_progress) == 0) { flag_in_progress <- 1 } if (flag_in_progress == 0){ plot_in_progress <- data.table(plot_in_progress$Created.Date) plot_in_progress$dates <- parse_date_time(plot_in_progress$V1, '%m/%d/%y %I:%M:%S %p') plot_in_progress_year <- data.frame(table(year(date(plot_in_progress$dates)))) #print(plot_in_progress_year) for (i in 2010:2021){ if ((i %in% plot_in_progress_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_in_progress_year) plot_in_progress_year <- rbind(plot_in_progress_year, tmp_df) } } plot_in_progress_year$Var1 <- as.numeric(as.character(plot_in_progress_year$Var1)) names(plot_in_progress_year)[names(plot_in_progress_year) == "Var1"] <- "Year" plot_in_progress_year <- plot_in_progress_year[order(plot_in_progress_year$Year),] plot_in_progress_year <- filter(plot_in_progress_year, Year >= min_year, Year <= max_year) plot_in_progress_year$case_status <- 'In Progress' #print('assigned or in progress') #print(plot_in_progress_year) } # open cases plot_open<- filter(zipsInBounds(), Status == 'Open') flag_open <- 0 if (nrow(plot_open) == 0) { flag_open <- 1 } if (flag_open == 0){ plot_open <- data.table(plot_open$Created.Date) plot_open$dates <- parse_date_time(plot_open$V1, '%m/%d/%y %I:%M:%S %p') plot_open_year <- data.frame(table(year(date(plot_open$dates)))) #print(plot_open_year) for (i in 2010:2021){ if ((i %in% plot_open_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_open_year) plot_open_year <- rbind(plot_open_year, tmp_df) } } plot_open_year$Var1 <- as.numeric(as.character(plot_open_year$Var1)) names(plot_open_year)[names(plot_open_year) == "Var1"] <- "Year" plot_open_year <- plot_open_year[order(plot_open_year$Year),] plot_open_year <- filter(plot_open_year, Year >= min_year, Year <= max_year) plot_open_year$case_status <- 'Open' #print('open or pending') #print(plot_open_year) # print('created') # print(plot_created_year) # print('closed') # print(plot_closed_year) # print('combined') } # pending cases plot_pending<- filter(zipsInBounds(), Status == 'Pending') flag_pending <- 0 if (nrow(plot_pending) == 0) { flag_pending <- 1 } if (flag_pending == 0){ plot_pending <- data.table(plot_pending$Created.Date) plot_pending$dates <- parse_date_time(plot_pending$V1, '%m/%d/%y %I:%M:%S %p') plot_pending_year <- data.frame(table(year(date(plot_pending$dates)))) #print(plot_pending_year) for (i in 2010:2021){ if ((i %in% plot_pending_year$Var1)==FALSE) { tmp_df <- data.frame(toString(i), 0) names(tmp_df) <- colnames(plot_pending_year) plot_pending_year <- rbind(plot_pending_year, tmp_df) } } plot_pending_year$Var1 <- as.numeric(as.character(plot_pending_year$Var1)) names(plot_pending_year)[names(plot_pending_year) == "Var1"] <- "Year" plot_pending_year <- plot_pending_year[order(plot_pending_year$Year),] plot_pending_year <- filter(plot_pending_year, Year >= min_year, Year <= max_year) plot_pending_year$case_status <- 'Pending' #print('open or pending') #print(plot_pending_year) # print('created') # print(plot_created_year) # print('closed') # print(plot_closed_year) # print('combined') } #plot_this <- plot_created_year plot_this <- data.frame(matrix(ncol = 3, nrow = 0)) colnames(plot_this) <- c("Year",'Freq','case_status') rownames(plot_created_year) # print('flag open') # print(flag_open) # print('flag pending') # print(flag_pending) # print('flag assigned') # print(flag_assigned) # print('flag in progress') # print(flag_in_progress) # print('flag closed') # print(flag_closed) if (flag_open == 0){ plot_this <- rbind(plot_this, plot_open_year) } if (flag_pending == 0){ plot_this <- rbind(plot_this, plot_pending_year) } if (flag_assigned == 0) { plot_this <- rbind(plot_this, plot_assigned_year) } if (flag_in_progress == 0) { plot_this <- rbind(plot_this, plot_in_progress_year) } if (flag_closed == 0){ plot_this <- rbind(plot_this, plot_closed_year) } #print(plot_this) # p_years <- ggplotly( # ggplot(data=plot_created_year, aes(x=Year, y=Freq)) + geom_path(stat="identity") + ylab('Rat sightings') + geom_point()+ # theme(axis.title.x=element_blank()) + scale_x_continuous(breaks=seq(min_year, max_year, 1)) # ) colors_for_case_status <- rep(NA, nrow(plot_this)) for (i in 1:nrow(plot_this)){ if (plot_this$case_status[i] == "Closed"){ colors_for_case_status[i] <- "green" } else if (plot_this$case_status[i] == "Pending"){ colors_for_case_status[i] <- "darkred" } else if (plot_this$case_status[i] == "Assigned"){ colors_for_case_status[i] <- "orange" } else if (plot_this$case_status[i] == "In Progress"){ colors_for_case_status[i] <- "cadetblue" } else if (plot_this$case_status[i] == "Draft"){ colors_for_case_status[i] <- "blue" } else if (plot_this$case_status[i] == "Open"){ colors_for_case_status[i] <- "purple" } } p_years <- ggplotly( ggplot(data=plot_this, aes(x=Year, y=Freq)) + geom_line(aes(color=case_status)) + geom_point(aes(colour=case_status)) #+ scale_colour_manual(name = 'Case status',values =c('green'='green','cadetblue' = 'cadetblue', 'orange'='orange', 'darkred'='darkred'), labels = c("closed","in progress", "assigned",'pending')) + ggtitle('Complaint status trend') + scale_x_continuous(breaks=seq(min_year, max_year, 1)) + theme_light() + theme(axis.title.y=element_blank(), #axis.text.y=element_blank(), axis.title.x=element_blank(),) #axis.text.x=element_blank()) + theme(legend.title = element_blank()) #+ theme(legend.position="left") #+ labs(color='Status') + theme(axis.title.x=element_blank()) ) }) zipsInBounds <- reactive({ if (is.null(input$map_bounds)) return(zipdata[FALSE,]) bounds <- input$map_bounds #print(bounds) latRng <- range(bounds$north, bounds$south) lngRng <- range(bounds$east, bounds$west) #print(latRng) subset(filter_rat_sightings, latitude >= latRng[1] & latitude <= latRng[2] & longitude >= lngRng[1] & longitude <= lngRng[2]) }) } #filter_rat_sightings <- filter_rat_sightings[,burough] # if (nrow(event_data("plotly_selecting"))>0){ # filter_rat_sightings <- filter_rat_sightings %>% filter(year_created %in% event_data("plotly_selecting")$Var1) # } #print('reached here') #print(filter_rat_sightings) #print('end reached here') }) # PRATISHTA'S VISUALIZATIONS ------------------------------------------------- output$pratishta1 <- renderPlotly({ p <- ggplot(rat_ton_date, aes(x=Created.Date, y=REFUSETONSCOLLECTED)) + geom_line(aes(color = Borough)) + geom_point(aes(color = Borough)) + xlab("Date by Months") + ylab("Weight of Waste (Tons)") + theme_light() p }) output$pratishta2 <- renderPlotly({ p <- ggplot(rat_ton_date, aes(x=Created.Date, y=n)) + geom_line(aes(color = Borough)) + geom_point(aes(color = Borough)) + xlab("Date by Months") + ylab("Number of rat sightings") + theme_light() p }) output$pratishta3 <- renderPlotly({ p <- ggplot(rat_ton_date, aes(x=Created.Date, y=rate)) + geom_line(aes(color = Borough)) + geom_point(aes(color = Borough)) + xlab("Date by Months") + ylab("Rate of rats per kiloton of waste") + theme_light() p }) output$pratishta4 <- renderPlotly({ ton + xlab("Boroughs") + ylab("Weight of Waste (Tons)") + theme_light() }) output$pratishta5 <- renderPlotly({ rat + xlab("Boroughs") + ylab("Number of Rat Sightings") + theme_light() }) output$pratishta7 <- renderTmap({ ## ------------------------------------------------------------------------ tm_shape(nyc_sp) + tm_fill("n", title = "Rat Sightings in Community Districts")+tm_view(set.view = c(-73.98928, 40.70042,10)) }) output$pratishta8 <- renderTmap({ ## ------------------------------------------------------------------------ tm_shape(nyc_sp) + tm_fill("total_ton", title = "Tones of Waste and Rat Sightings by DSNY Districts")+tm_view(set.view = c(-73.98928, 40.70042,10)) }) output$pratishta9 <- renderPlot({ ## ------------------------------------------------------------------------ legend_creator = function(col.regions, xlab, ylab, nbins){ bilegend = levelplot(matrix(1:(nbins * nbins), nrow = nbins), axes = FALSE, col.regions = col.regions, xlab = xlab, ylab = ylab, cuts = 8, colorkey = FALSE, scales = list(draw = 0)) bilegend } add_new_var = function(x, var1, var2, nbins, style = "quantile"){ class1 = suppressWarnings(findCols(classIntervals(c(x[[var1]]), n = nbins, style = style))) class2 = suppressWarnings(findCols(classIntervals(c(x[[var2]]), n = nbins, style = style))) x$new_class = class1 + nbins * (class2 - 1) return(x) } ## ------------------------------------------------------------------------ nyc_cd <- nyc_sp ## ------------------------------------------------------------------------ nyc_cd = add_new_var(nyc_cd, var1 = "n", var2 = "total_ton", nbins = 3) ## ------------------------------------------------------------------------ bilegend = legend_creator(stevens.pinkblue(n = 9), xlab = "rats", ylab = "total tonnes", nbins = 3) vp = viewport(x = 0.25, y = 0.25, width = 0.25, height = 0.25) pushViewport(vp) #print(bilegend, newpage = FALSE) bimap = tm_shape(nyc_cd) + tm_fill("new_class", style = "cat", palette = stevens.pinkblue(n = 9), legend.show = FALSE) + tm_layout(legend.show = FALSE) grid.newpage() vp = viewport(x = 0.37, y = 0.75, width = 0.25, height = 0.25) print(bimap, vp = viewport()) pushViewport(vp) print(bilegend, newpage = FALSE, vp = vp) }) # END OF PRATISHTA'S VISUALIZATIONS ------------------------------------------ # brendan's viz ----------------------------------------------------------- output$brendan_chart1 <- renderPlotly({ plot1 <-ggplot() + geom_bar(data=rat_borough, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("2020 rodent reports") + ylab("Number of 311 calls\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot1 }) output$brendan_chart2 <- renderPlotly({ plot2 <- ggplot() + geom_bar(data=restaurant_borough, aes(x =Borough, y= count), stat="identity", fill=rainbow(n=5)) + ggtitle("Outdoor restaurants") + ylab("Applications approved\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot2 }) output$brendan_chart3 <- renderPlotly({ plot3 <- ggplot() + geom_bar(data=inspection_count_2020, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("Restaurants w/ B or C inspection scores") + ylab("Restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), legend.position="none", axis.title.y=element_text(face="bold")) + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot3 }) output$brendan_chart4 <- renderPlotly({ plot4 <- ggplot() + geom_bar(data=count_street, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("Street dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot4 }) output$brendan_chart5 <- renderPlotly({ plot5 <- ggplot() + geom_bar(data=count_sidewalk, aes(x=Borough, y=count), stat="identity", fill=rainbow(n=5)) + ggtitle("Sidewalk dining") + ylab("Approved restaurants\n") + xlab("\nBorough") + theme_light() + theme(plot.title=element_text(face="bold"), axis.title.x=element_text(face="bold"), axis.title.y=element_text(face="bold"), legend.position="none") + theme(axis.text.x = element_text(angle = 40, vjust=.7)) plot5 }) output$brendan_map <- renderLeaflet({ interactive_map <- leaflet() %>% addProviderTiles(providers$Stamen.TonerLite, options = providerTileOptions(noWrap = TRUE)) %>% addCircleMarkers(data=manhattan_open, lng=~Longitude, lat=~Latitude, radius=1, color= "red", fillOpacity=1, popup=~paste('Restuarant:', manhattan_open$Restaurant.Name, '<br>', 'Street Dining?', manhattan_open$Approved.for.Roadway.Seating, '<br>', 'Sidewalk Dining?', manhattan_open$Approved.for.Sidewalk.Seating, '<br>')) %>% addMarkers(data=manhattan_311,lng=~manhattan_311.Longitude, lat=~manhattan_311.Latitude, icon=icon, popup=~paste('Address:',manhattan_311$manhattan_311.Incident.Address,'<br>', 'Call Date:', manhattan_311$manhattan_311.Created.Date,'<br>','Descriptor:', manhattan_311$manhattan_311.Descriptor,'<br>'), clusterOptions= markerClusterOptions(disableClusteringAtZoom=16)) %>% setView(lng = -73.98928, lat = 40.77042, zoom = 12) }) # output$brendan_wc1 <- renderPlot({ # (wordcloud1 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area(mask=img, rm_outside = TRUE) + scale_size_area(max_size=5) + theme_classic()) # # }) # # output$brendan_wc2 <- renderPlot({ # (wordcloud2 <- ggplot(descriptors3, aes(label=word, size=n, color=col)) + geom_text_wordcloud_area() + scale_size_area()) # # }) } shinyApp(ui = ui, server = server)
home <- tabPanel("Home", sidebarLayout(sidebarPanel( p( "Hi there, my name is Bayan Hammami and I'm a data scientist who loves data. This is my interactive data-driven resume. I hope you enjoy it!" ), p( "This site was built with R and the following packages; shiny, ggplot2, ggnet, network, wordcloud, fmsb, dplyr, tm and a few more." ), p( "The code for this app can be found here:", tags$b(tags$a(href ="https://github.com/BayanHammami/resume-shiny", "https://github.com/BayanHammami/resume-shiny")) ), p( "Please contact me on:", tags$b("bayan.hammami@gmail.com") ), hr(), sliderInput( "min_word_freq", "Minimum word frequency in my text resume", min = 1, max = 5, value = 2 ), actionButton("home_regenerate", "Regenerate Wordcloud"), hr(), span( style="margin:8px;", a(href="https://github.com/BayanHammami", target="_blank", icon("github", class = "fa-2x", lib = "font-awesome") ) ), span( style="margin:8px;", a(href="https://www.linkedin.com/in/bayan-hammami", target="_blank", icon("linkedin", class = "fa-2x", lib = "font-awesome") ) ), span( style="margin:8px;", a(href="https://twitter.com/bayan_aus", target="_blank", icon("twitter", class = "fa-2x", lib = "font-awesome") ) ) ), mainPanel( plotOutput("home_plot", height = "600px"), style="text-align: center;" )) )
/ui-components/nav-panels/ui-home.R
no_license
BayanHammami/resume-shiny
R
false
false
2,557
r
home <- tabPanel("Home", sidebarLayout(sidebarPanel( p( "Hi there, my name is Bayan Hammami and I'm a data scientist who loves data. This is my interactive data-driven resume. I hope you enjoy it!" ), p( "This site was built with R and the following packages; shiny, ggplot2, ggnet, network, wordcloud, fmsb, dplyr, tm and a few more." ), p( "The code for this app can be found here:", tags$b(tags$a(href ="https://github.com/BayanHammami/resume-shiny", "https://github.com/BayanHammami/resume-shiny")) ), p( "Please contact me on:", tags$b("bayan.hammami@gmail.com") ), hr(), sliderInput( "min_word_freq", "Minimum word frequency in my text resume", min = 1, max = 5, value = 2 ), actionButton("home_regenerate", "Regenerate Wordcloud"), hr(), span( style="margin:8px;", a(href="https://github.com/BayanHammami", target="_blank", icon("github", class = "fa-2x", lib = "font-awesome") ) ), span( style="margin:8px;", a(href="https://www.linkedin.com/in/bayan-hammami", target="_blank", icon("linkedin", class = "fa-2x", lib = "font-awesome") ) ), span( style="margin:8px;", a(href="https://twitter.com/bayan_aus", target="_blank", icon("twitter", class = "fa-2x", lib = "font-awesome") ) ) ), mainPanel( plotOutput("home_plot", height = "600px"), style="text-align: center;" )) )
###tidy_tuesday ###4/10/21 ###richard rachman ####################### ### library library(tidyverse) library(tidytuesdayR) library(here) library(viridis) library(hrbrthemes) ### data forest <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-04-06/forest.csv') view(forest) entity<- forest$entity NorthAmerica<- c("Canada","Cuba","Mexico","United States") forest1<- filter(forest, entity %in% NorthAmerica) %>% select(entity, year, net_forest_conversion) # North American countries # Belize # Canada # Costa Rica # Cuba # Dominican Republic # El Salvador # Guatemala # Honduras # Jamaica # Mexico # Nicaragua # Panama # USA ### script ggplot(forest1, aes(year, net_forest_conversion, label= entity, color= entity)) + geom_line((aes(colour = entity)))+ scale_color_viridis(discrete = TRUE) + ggtitle("Forest conversion by largest countries in NA") + theme_ipsum() + ylab("Scale of net forest conversion")+ xlab("Year")+ labs(caption = "Positive forest coversion suggestions forest expansion, though data is incomplete for USA")+ theme(legend.title = element_blank())+ ggsave(here("output","forests.jpeg")) # Plot
/script/tidytuesday_4-12-21.R
no_license
awanderingecologist/tidytuesday
R
false
false
1,211
r
###tidy_tuesday ###4/10/21 ###richard rachman ####################### ### library library(tidyverse) library(tidytuesdayR) library(here) library(viridis) library(hrbrthemes) ### data forest <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-04-06/forest.csv') view(forest) entity<- forest$entity NorthAmerica<- c("Canada","Cuba","Mexico","United States") forest1<- filter(forest, entity %in% NorthAmerica) %>% select(entity, year, net_forest_conversion) # North American countries # Belize # Canada # Costa Rica # Cuba # Dominican Republic # El Salvador # Guatemala # Honduras # Jamaica # Mexico # Nicaragua # Panama # USA ### script ggplot(forest1, aes(year, net_forest_conversion, label= entity, color= entity)) + geom_line((aes(colour = entity)))+ scale_color_viridis(discrete = TRUE) + ggtitle("Forest conversion by largest countries in NA") + theme_ipsum() + ylab("Scale of net forest conversion")+ xlab("Year")+ labs(caption = "Positive forest coversion suggestions forest expansion, though data is incomplete for USA")+ theme(legend.title = element_blank())+ ggsave(here("output","forests.jpeg")) # Plot
library(bigMap) ### Name: bdm.pakde ### Title: Perplexity-adaptive kernel density estimation ### Aliases: bdm.pakde ### ** Examples # --- load mapped dataset bdm.example() # --- run paKDE ## Not run: ##D exMap <- bdm.pakde(exMap, threads = 4, ppx = 200, g = 200, g.exp = 3) ## End(Not run) # --- plot paKDE output bdm.plot(exMap)
/data/genthat_extracted_code/bigMap/examples/bdm.pakde.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
339
r
library(bigMap) ### Name: bdm.pakde ### Title: Perplexity-adaptive kernel density estimation ### Aliases: bdm.pakde ### ** Examples # --- load mapped dataset bdm.example() # --- run paKDE ## Not run: ##D exMap <- bdm.pakde(exMap, threads = 4, ppx = 200, g = 200, g.exp = 3) ## End(Not run) # --- plot paKDE output bdm.plot(exMap)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/clear_selection.R \name{clear_selection} \alias{clear_selection} \title{Clear a selection of nodes or edges in a graph} \usage{ clear_selection(graph) } \arguments{ \item{graph}{a graph object of class \code{dgr_graph} that is created using \code{create_graph}.} } \value{ a graph object of class \code{dgr_graph}. } \description{ Clear the selection of nodes or edges within a graph object. } \examples{ # Create a simple graph nodes <- create_nodes( nodes = c("a", "b", "c", "d"), type = "letter", label = TRUE, value = c(3.5, 2.6, 9.4, 2.7)) edges <- create_edges( from = c("a", "b", "c"), to = c("d", "c", "a"), rel = "leading_to") graph <- create_graph( nodes_df = nodes, edges_df = edges) # Select nodes "a" and "c" graph <- select_nodes( graph = graph, nodes = c("a", "c")) # Verify that a node selection has been made get_selection(graph) #> [1] "a" "c" # Clear the selection with `clear_selection()` graph <- clear_selection(graph = graph) # Verify that the node selection has been cleared get_selection(graph) #> [1] NA }
/man/clear_selection.Rd
no_license
timelyportfolio/DiagrammeR
R
false
true
1,169
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/clear_selection.R \name{clear_selection} \alias{clear_selection} \title{Clear a selection of nodes or edges in a graph} \usage{ clear_selection(graph) } \arguments{ \item{graph}{a graph object of class \code{dgr_graph} that is created using \code{create_graph}.} } \value{ a graph object of class \code{dgr_graph}. } \description{ Clear the selection of nodes or edges within a graph object. } \examples{ # Create a simple graph nodes <- create_nodes( nodes = c("a", "b", "c", "d"), type = "letter", label = TRUE, value = c(3.5, 2.6, 9.4, 2.7)) edges <- create_edges( from = c("a", "b", "c"), to = c("d", "c", "a"), rel = "leading_to") graph <- create_graph( nodes_df = nodes, edges_df = edges) # Select nodes "a" and "c" graph <- select_nodes( graph = graph, nodes = c("a", "c")) # Verify that a node selection has been made get_selection(graph) #> [1] "a" "c" # Clear the selection with `clear_selection()` graph <- clear_selection(graph = graph) # Verify that the node selection has been cleared get_selection(graph) #> [1] NA }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/givenNamesDB_authorships.R \docType{data} \name{givenNamesDB_authorships} \alias{givenNamesDB_authorships} \title{Gender data for authorship sample} \format{A data.table object with 872 rows and 4 variables: \describe{ \item{name}{A term used as first name.} \item{gender}{The predicted gender for the term.} \item{probability}{The probability of the predicted gender.} \item{count}{How many social profiles with the term as a given name is recorded in the genderize.io database.} }} \source{ \url{http://genderize.io/} } \usage{ givenNamesDB_authorships } \description{ A dataset with first names and gender data from genderize.io for \pkg{authorships} dataset in the package. This is the output of \code{findGivenNames} function that was performed on December 26, 2014. } \keyword{datasets}
/man/givenNamesDB_authorships.Rd
permissive
cran/genderizeR
R
false
true
913
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/givenNamesDB_authorships.R \docType{data} \name{givenNamesDB_authorships} \alias{givenNamesDB_authorships} \title{Gender data for authorship sample} \format{A data.table object with 872 rows and 4 variables: \describe{ \item{name}{A term used as first name.} \item{gender}{The predicted gender for the term.} \item{probability}{The probability of the predicted gender.} \item{count}{How many social profiles with the term as a given name is recorded in the genderize.io database.} }} \source{ \url{http://genderize.io/} } \usage{ givenNamesDB_authorships } \description{ A dataset with first names and gender data from genderize.io for \pkg{authorships} dataset in the package. This is the output of \code{findGivenNames} function that was performed on December 26, 2014. } \keyword{datasets}
sidebar <- dashboardSidebar( sidebarMenu( menuItem("Webinar Participation", tabName = "social_location", icon = icon("user", lib = "glyphicon"), badgeLabel = "main", badgeColor = "green"), menuItem("User Journey", icon = icon("send", lib = "glyphicon"), tabName = "landing_page" #, #badgeLabel = "path", badgeColor = "orange" ) # , # menuItem("valueBox test", tabName = "valueboxtest", icon = icon("thumbs-up", lib = "glyphicon")) ) ) body <- dashboardBody( tabItems( tabItem(tabName = "social_location", fluidRow( column( width = 5, box(width = 12, title = "DA webinar registrations - July 2020", plotlyOutput("bulletgraph13", height = "120px") ) ), column(width = 2, br(), br(), valueBox(width = 12, goals$goal17Completions[5] + goals$goal13Completions[5], "Total signups (July)", icon = icon("list")) ), column(width = 5, box(width = 12, title = "PSD webinar registrations - July 2020", plotlyOutput("bulletgraph17", height = "120px") ) ) ), fluidRow( width = 12, plotOutput("goals") ), fluidRow( column(width = 6, br(), plotOutput("social") ), column(width = 6, br(), plotOutput("referrers") ) ), ), tabItem(tabName = "landing_page", fluidRow( box(width = 12, plotOutput("landing") ) ), fluidRow( box(width = 6, plotOutput("landing_goals13") ), box(width = 6, plotOutput("landing_goals17") ) ) ) # tabItem(tabName = "valueboxtest", # valueBox(50*2, "valueBox test", icon = icon("list"))) ) ) ui <- dashboardPage( dashboardHeader(title = "Website Engagement"), sidebar, body )
/ui.R
no_license
Debs20/data-proj-syn
R
false
false
2,527
r
sidebar <- dashboardSidebar( sidebarMenu( menuItem("Webinar Participation", tabName = "social_location", icon = icon("user", lib = "glyphicon"), badgeLabel = "main", badgeColor = "green"), menuItem("User Journey", icon = icon("send", lib = "glyphicon"), tabName = "landing_page" #, #badgeLabel = "path", badgeColor = "orange" ) # , # menuItem("valueBox test", tabName = "valueboxtest", icon = icon("thumbs-up", lib = "glyphicon")) ) ) body <- dashboardBody( tabItems( tabItem(tabName = "social_location", fluidRow( column( width = 5, box(width = 12, title = "DA webinar registrations - July 2020", plotlyOutput("bulletgraph13", height = "120px") ) ), column(width = 2, br(), br(), valueBox(width = 12, goals$goal17Completions[5] + goals$goal13Completions[5], "Total signups (July)", icon = icon("list")) ), column(width = 5, box(width = 12, title = "PSD webinar registrations - July 2020", plotlyOutput("bulletgraph17", height = "120px") ) ) ), fluidRow( width = 12, plotOutput("goals") ), fluidRow( column(width = 6, br(), plotOutput("social") ), column(width = 6, br(), plotOutput("referrers") ) ), ), tabItem(tabName = "landing_page", fluidRow( box(width = 12, plotOutput("landing") ) ), fluidRow( box(width = 6, plotOutput("landing_goals13") ), box(width = 6, plotOutput("landing_goals17") ) ) ) # tabItem(tabName = "valueboxtest", # valueBox(50*2, "valueBox test", icon = icon("list"))) ) ) ui <- dashboardPage( dashboardHeader(title = "Website Engagement"), sidebar, body )
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/spline-correlog.r \name{print.spline.correlog} \alias{print.spline.correlog} \title{Print function for spline.correlog objects} \usage{ \method{print}{spline.correlog}(x, ...) } \arguments{ \item{x}{an object of class "spline.correlog", usually, as a result of a call to \code{spline.correlog} or related).} \item{\dots}{other arguments} } \value{ The function-call is printed to screen. } \description{ `print' method for class "spline.correlog". } \seealso{ \code{\link{spline.correlog}} }
/man/print.spline.correlog.Rd
no_license
objornstad/ncf
R
false
true
571
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/spline-correlog.r \name{print.spline.correlog} \alias{print.spline.correlog} \title{Print function for spline.correlog objects} \usage{ \method{print}{spline.correlog}(x, ...) } \arguments{ \item{x}{an object of class "spline.correlog", usually, as a result of a call to \code{spline.correlog} or related).} \item{\dots}{other arguments} } \value{ The function-call is printed to screen. } \description{ `print' method for class "spline.correlog". } \seealso{ \code{\link{spline.correlog}} }
plot_case_studies <- function(cs1, cs2, performance_stats, perf_summaries, case_studies, cs_name = "realistic", lcomp_years = "max", plot_variable = "f", plot_period = "middle", modelo_name) { if (lcomp_years == "max"){ lyears <- max(performance_stats$prop_years_lcomp_data) } else if (lcomp_years == "min"){ lyears <- min(performance_stats$prop_years_lcomp_data) } cs_summary <- performance_stats %>% ungroup() %>% filter(case_study == case_study, prop_years_lcomp_data == lyears , variable == plot_variable, model == cs1 | model == cs2) # cs_summary$model <- fct_recode(as.factor(cs_summary$model), "Lengths Only" = cs1, # "Lengths + Economics" = cs2 ) cs_summ_plot <- cs_summary %>% gather(metric, value, recent_rmse, recent_median_bias) %>% ggplot(aes(value, fill = model)) + geom_vline(aes(xintercept = 0), linetype = 2) + geom_density_ridges(aes(x = value, y = metric, fill = model), alpha = 0.3, color = "darkgrey", show.legend = F) + scale_y_discrete(labels = c("bias", "rmse"), position = "right", name = element_blank())+ theme( plot.margin = unit(c(0, 0, 0, 1), units = "lines"), axis.title.y = element_blank(), axis.title.x = element_blank() ) + theme(legend.title = element_blank(), axis.text.x = element_text(size = 10)) + ggsci::scale_fill_aaas() + labs(caption = "Calculated over last 5 years", title = "B") lcomp_years <- case_studies %>% filter(case_study == cs_name, prop_years_lcomp_data == lyears, period == plot_period) lcomp_years <- lcomp_years$prepped_fishery[[1]]$scrooge_data$length_comps_years cs <- perf_summaries %>% ungroup() %>% filter(case_study == cs_name, prop_years_lcomp_data == lyears, model == cs1 | model == cs2) fill_vector <- rep("transparent", length (unique(cs$year[cs$variable == "f"]))) fill_vector[lcomp_years] <- "tomato" fill_vector <- c(fill_vector, fill_vector) cs_plot <- cs %>% filter(variable == plot_variable) %>% mutate(year = year - min(year) + 1) %>% mutate(lcomp_year = year %in% lcomp_years) %>% arrange(experiment) %>% ggplot() + geom_point(aes(year, observed), size = 3, alpha = 0.75, shape = 21, fill =fill_vector) + geom_ribbon(aes(year, ymin = lower_90, ymax = upper_90, fill = model), alpha = 0.2, show.legend = FALSE) + geom_line(aes(year,mean_predicted, color = model), show.legend = FALSE) + labs(title = "A",x = "Year", y = "Fishing Mortality", caption = "Points = Data, Shaded = Predictions") + ggsci::scale_color_aaas() + ggsci::scale_fill_aaas() + facet_wrap(~model, labeller = labeller(model = modelo_name)) + theme(plot.margin = unit(c(0,0,0,0), units = "lines"), panel.spacing = unit(0.1, units = "lines"), strip.text = element_text(size = 14)) go_away <- ls()[!ls() %in% c("cs_plot","cs_summ_plot")] rm(list = go_away) out <- cs_plot + cs_summ_plot + plot_layout(nrow = 1, ncol = 2, widths = c(3,1)) }
/functions/plot_case_studies.R
permissive
DanOvando/scrooge
R
false
false
3,140
r
plot_case_studies <- function(cs1, cs2, performance_stats, perf_summaries, case_studies, cs_name = "realistic", lcomp_years = "max", plot_variable = "f", plot_period = "middle", modelo_name) { if (lcomp_years == "max"){ lyears <- max(performance_stats$prop_years_lcomp_data) } else if (lcomp_years == "min"){ lyears <- min(performance_stats$prop_years_lcomp_data) } cs_summary <- performance_stats %>% ungroup() %>% filter(case_study == case_study, prop_years_lcomp_data == lyears , variable == plot_variable, model == cs1 | model == cs2) # cs_summary$model <- fct_recode(as.factor(cs_summary$model), "Lengths Only" = cs1, # "Lengths + Economics" = cs2 ) cs_summ_plot <- cs_summary %>% gather(metric, value, recent_rmse, recent_median_bias) %>% ggplot(aes(value, fill = model)) + geom_vline(aes(xintercept = 0), linetype = 2) + geom_density_ridges(aes(x = value, y = metric, fill = model), alpha = 0.3, color = "darkgrey", show.legend = F) + scale_y_discrete(labels = c("bias", "rmse"), position = "right", name = element_blank())+ theme( plot.margin = unit(c(0, 0, 0, 1), units = "lines"), axis.title.y = element_blank(), axis.title.x = element_blank() ) + theme(legend.title = element_blank(), axis.text.x = element_text(size = 10)) + ggsci::scale_fill_aaas() + labs(caption = "Calculated over last 5 years", title = "B") lcomp_years <- case_studies %>% filter(case_study == cs_name, prop_years_lcomp_data == lyears, period == plot_period) lcomp_years <- lcomp_years$prepped_fishery[[1]]$scrooge_data$length_comps_years cs <- perf_summaries %>% ungroup() %>% filter(case_study == cs_name, prop_years_lcomp_data == lyears, model == cs1 | model == cs2) fill_vector <- rep("transparent", length (unique(cs$year[cs$variable == "f"]))) fill_vector[lcomp_years] <- "tomato" fill_vector <- c(fill_vector, fill_vector) cs_plot <- cs %>% filter(variable == plot_variable) %>% mutate(year = year - min(year) + 1) %>% mutate(lcomp_year = year %in% lcomp_years) %>% arrange(experiment) %>% ggplot() + geom_point(aes(year, observed), size = 3, alpha = 0.75, shape = 21, fill =fill_vector) + geom_ribbon(aes(year, ymin = lower_90, ymax = upper_90, fill = model), alpha = 0.2, show.legend = FALSE) + geom_line(aes(year,mean_predicted, color = model), show.legend = FALSE) + labs(title = "A",x = "Year", y = "Fishing Mortality", caption = "Points = Data, Shaded = Predictions") + ggsci::scale_color_aaas() + ggsci::scale_fill_aaas() + facet_wrap(~model, labeller = labeller(model = modelo_name)) + theme(plot.margin = unit(c(0,0,0,0), units = "lines"), panel.spacing = unit(0.1, units = "lines"), strip.text = element_text(size = 14)) go_away <- ls()[!ls() %in% c("cs_plot","cs_summ_plot")] rm(list = go_away) out <- cs_plot + cs_summ_plot + plot_layout(nrow = 1, ncol = 2, widths = c(3,1)) }
# For compatibility with 2.2.21 .get_course_path <- function(){ tryCatch(swirl:::swirl_courses_dir(), error = function(c) {file.path(find.package("swirl"),"Courses")} ) } # Put initialization code in this file. path_to_course <- file.path(.get_course_path(), "R_102 - Getting_and_Cleaning_Data","ODBC")
/R_102 - Getting_and_Cleaning_Data/ODBC/initLesson.R
no_license
ImprovementPathSystems/IPS_swirl_beta
R
false
false
321
r
# For compatibility with 2.2.21 .get_course_path <- function(){ tryCatch(swirl:::swirl_courses_dir(), error = function(c) {file.path(find.package("swirl"),"Courses")} ) } # Put initialization code in this file. path_to_course <- file.path(.get_course_path(), "R_102 - Getting_and_Cleaning_Data","ODBC")
#' Change PCA Table names #' #' @param table created with the \code{sas_prcomp_PCA_table_function} function. #' @description First create a table from SAS output, then use this function to change the values of a couple of columns. #' #' @export sas_PCA_table_names <- function(table) { table %<>% mutate(`Summary Statistic` = Var) %>% mutate( `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="A1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="A2"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="B"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="C1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="C2"), "Max." ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="C3"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="D1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="D2"), "Max." ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="D3"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="E1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="E2"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="F"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="G"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="H1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="H2"), "Max." ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="H3"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="Eigenvalue"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="Cumulative Proportion of Variance Explained"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="Rotated"), "" ) ) %>% # mutate( # `All Data PC 2` = replace( # `All Data PC 2`, # which(is.na(`All Data PC 2`)), # "" # ) # ) %>% mutate( Var = replace( Var, which(Var=="A1"), "Daily Precipitation" ), Var = replace( Var, which(Var=="A2"), "" ), Var = replace( Var, which(Var=="B"), "Percentage of Days with Rain" ), Var = replace( Var, which(Var=="C1"), "Number of Consecutive Days with Rain" ), Var = replace( Var, which(Var=="C2"), "" ), Var = replace( Var, which(Var=="C3"), "" ), Var = replace( Var, which(Var=="D1"), "Number of Consecutive Days without Rain" ), Var = replace( Var, which(Var=="D2"), "" ), Var = replace( Var, which(Var=="D3"), "" ), Var = replace( Var, which(Var=="E1"), "Maximum Temperature" ), Var = replace( Var, which(Var=="E2"), "" ), Var = replace( Var, which(Var=="F"), "Mean Degree Day" ), Var = replace( Var, which(Var=="G"), "Percentage of Freezing Days"), Var = replace( Var, which(Var=="H1"), "Number of Cosecutive Days with Temperatures Below Freezing" ), Var = replace( Var, which(Var=="H2"), "" ), Var = replace( Var, which(Var=="H3"), "" ) ) %>% select(Var, `Summary Statistic`, everything()) names(table)[names(table)=="Var"] <- "Variable" return(table) }
/R/SAS_PCA_table_names.R
no_license
ksauby/modresproc
R
false
false
4,101
r
#' Change PCA Table names #' #' @param table created with the \code{sas_prcomp_PCA_table_function} function. #' @description First create a table from SAS output, then use this function to change the values of a couple of columns. #' #' @export sas_PCA_table_names <- function(table) { table %<>% mutate(`Summary Statistic` = Var) %>% mutate( `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="A1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="A2"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="B"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="C1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="C2"), "Max." ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="C3"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="D1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="D2"), "Max." ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="D3"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="E1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="E2"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="F"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="G"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="H1"), "Mean" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="H2"), "Max." ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="H3"), "SD" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="Eigenvalue"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="Cumulative Proportion of Variance Explained"), "" ), `Summary Statistic` = replace( `Summary Statistic`, which(`Summary Statistic`=="Rotated"), "" ) ) %>% # mutate( # `All Data PC 2` = replace( # `All Data PC 2`, # which(is.na(`All Data PC 2`)), # "" # ) # ) %>% mutate( Var = replace( Var, which(Var=="A1"), "Daily Precipitation" ), Var = replace( Var, which(Var=="A2"), "" ), Var = replace( Var, which(Var=="B"), "Percentage of Days with Rain" ), Var = replace( Var, which(Var=="C1"), "Number of Consecutive Days with Rain" ), Var = replace( Var, which(Var=="C2"), "" ), Var = replace( Var, which(Var=="C3"), "" ), Var = replace( Var, which(Var=="D1"), "Number of Consecutive Days without Rain" ), Var = replace( Var, which(Var=="D2"), "" ), Var = replace( Var, which(Var=="D3"), "" ), Var = replace( Var, which(Var=="E1"), "Maximum Temperature" ), Var = replace( Var, which(Var=="E2"), "" ), Var = replace( Var, which(Var=="F"), "Mean Degree Day" ), Var = replace( Var, which(Var=="G"), "Percentage of Freezing Days"), Var = replace( Var, which(Var=="H1"), "Number of Cosecutive Days with Temperatures Below Freezing" ), Var = replace( Var, which(Var=="H2"), "" ), Var = replace( Var, which(Var=="H3"), "" ) ) %>% select(Var, `Summary Statistic`, everything()) names(table)[names(table)=="Var"] <- "Variable" return(table) }
## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { ## Initialize the inverse property i <- NULL ## Method to set the matrix set <- function( matrix ) { m <<- matrix i <<- NULL } ## Method the get the matrix get <- function() { ## Return the matrix m } ## Method to set the inverse of the matrix setInverse <- function(inverse) { i <<- inverse } ## Method to get the inverse of the matrix getInverse <- function() { ## Return the inverse property i } ## Return a list of the methods list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## Write a short comment describing this function cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m <- x$getInverse() ## Just return the inverse if its already set if( !is.null(m) ) { message("getting cached data") return(m) } ## Get the matrix from our object data <- x$get() ## Calculate the inverse using matrix multiplication m <- solve(data) %*% data ## Set the inverse to the object x$setInverse(m) ## Return the matrix m }
/cachematrix.R
no_license
manavjain174/ProgrammingAssignment2
R
false
false
1,362
r
## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { ## Initialize the inverse property i <- NULL ## Method to set the matrix set <- function( matrix ) { m <<- matrix i <<- NULL } ## Method the get the matrix get <- function() { ## Return the matrix m } ## Method to set the inverse of the matrix setInverse <- function(inverse) { i <<- inverse } ## Method to get the inverse of the matrix getInverse <- function() { ## Return the inverse property i } ## Return a list of the methods list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## Write a short comment describing this function cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m <- x$getInverse() ## Just return the inverse if its already set if( !is.null(m) ) { message("getting cached data") return(m) } ## Get the matrix from our object data <- x$get() ## Calculate the inverse using matrix multiplication m <- solve(data) %*% data ## Set the inverse to the object x$setInverse(m) ## Return the matrix m }
testlist <- list(testX = c(191493125665849920, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), trainX = structure(c(1.78844646178735e+212, 1.93075223605916e+156, 121373.193669204, 1.26689771433298e+26, 2.46020195254853e+129, 8.54794497535107e-83, 2.61907806894971e-213, 1.5105425626729e+200, 6.51877713351675e+25, 4.40467528702727e-93, 7.6427933587945, 34208333744.1307, 1.6400690920442e-111, 3.9769673154778e-304, 4.76127371594362e-307, 8.63819952335095e+122, 1.18662128550178e-59, 1128.83285802937, 3.80368040657947e-72, 1.21321365773924e-195, 9.69744674150153e-268, 8.98899319496613e+272, 7.63669788330223e+285, 3.85830749537493e+266, 2.65348875902107e+136, 8.14965241967603e+92, 2.59677146539475e-173, 1.55228780425777e-91, 8.25550184376779e+105, 1.18572662524891e+134, 1.04113208597565e+183, 1.01971211553913e-259, 1.23680594512923e-165, 5.24757023065221e+62, 3.41816623041351e-96 ), .Dim = c(5L, 7L))) result <- do.call(dann:::calc_distance_C,testlist) str(result)
/dann/inst/testfiles/calc_distance_C/AFL_calc_distance_C/calc_distance_C_valgrind_files/1609867112-test.R
no_license
akhikolla/updated-only-Issues
R
false
false
1,199
r
testlist <- list(testX = c(191493125665849920, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), trainX = structure(c(1.78844646178735e+212, 1.93075223605916e+156, 121373.193669204, 1.26689771433298e+26, 2.46020195254853e+129, 8.54794497535107e-83, 2.61907806894971e-213, 1.5105425626729e+200, 6.51877713351675e+25, 4.40467528702727e-93, 7.6427933587945, 34208333744.1307, 1.6400690920442e-111, 3.9769673154778e-304, 4.76127371594362e-307, 8.63819952335095e+122, 1.18662128550178e-59, 1128.83285802937, 3.80368040657947e-72, 1.21321365773924e-195, 9.69744674150153e-268, 8.98899319496613e+272, 7.63669788330223e+285, 3.85830749537493e+266, 2.65348875902107e+136, 8.14965241967603e+92, 2.59677146539475e-173, 1.55228780425777e-91, 8.25550184376779e+105, 1.18572662524891e+134, 1.04113208597565e+183, 1.01971211553913e-259, 1.23680594512923e-165, 5.24757023065221e+62, 3.41816623041351e-96 ), .Dim = c(5L, 7L))) result <- do.call(dann:::calc_distance_C,testlist) str(result)
library(here) library(keras) library(tidytext) library(tidyverse) set.seed(55) tweets <- read_csv(here("tweets", "truthdata_allrounds.csv")) %>% mutate(accident = NA) %>% mutate(accident = replace(accident, accident_truth == "No", 0)) %>% mutate(accident = replace(accident, accident_truth == "Yes", 1)) %>% select("tweet", "accident") %>% na.omit table(tweets$accident) # pre-process text text_process <- function(text, stopwords = FALSE, lower = FALSE) { # remove time stamp and other numbers #text_data <- gsub("[[:digit:]]*|\\r", "", text) cat_text <- paste(text, collapse=" ") text_sequence <- unique(text_to_word_sequence(cat_text, split = " ", lower = lower)) if(stopwords) { text_index <- tibble(word = text_sequence, index = 1:length(text_sequence)) %>% anti_join(get_stopwords(), by = "word") } else { text_index <- tibble(word = text_sequence, index = 1:length(text_sequence)) } text_index } # create a word index to match text to integers word_index <- text_process(tweets$tweet) # make integer sequences of tweet text make_index_list <- function(x) { data_index <- c() for (i in 1:length(x)) { text <- x[[i]] x_seq <- text_to_word_sequence(text, split = " ", lower = FALSE) x_int <- c() for(n in x_seq) { int <- word_index$index[word_index$word %in% n] x_int <- c(x_int, int) x_int } data_index[[i]] <- x_int } data_index } # hot encode integer sequences vectorize_sequences <- function(sequences, dimension = nrow(word_index)) { results <- matrix(0, nrow = length(sequences), ncol = dimension) for (i in 1:length(sequences)) { results[i, sequences[[i]]] <- 1 } results } # separate tweet data into training and testing sets index2train <- sample(1:nrow(tweets), nrow(tweets)/2) # data train_data <- tweets$tweet[index2train] test_data <- tweets$tweet[-index2train] # labels y_train <- tweets$accident[index2train] y_test <- tweets$accident[-index2train] # convert words to integers based on their place in the dictionary test_index <- make_index_list(test_data) train_index <- make_index_list(train_data) x_train <- vectorize_sequences(train_index) x_test <- vectorize_sequences(test_index) #val_indices <- sample(1:nrow(x_train), 500) val_indices <- 1:500 x_val <- x_train[val_indices,] partial_x_train <- x_train[-val_indices,] y_val <- y_train[val_indices] partial_y_train <- y_train[-val_indices] model <- keras_model_sequential() %>% layer_dense(units = 16, activation = "relu", input_shape = nrow(word_index)) %>% layer_dense(units = 16, activation = "relu") %>% layer_dense(units = 1, activation = "sigmoid") model %>% compile( optimizer = "rmsprop", loss = "binary_crossentropy", metrics = c("accuracy") ) history <- model %>% fit( partial_x_train, partial_y_train, epochs = 50, batch_size = 300, validation_data = list(x_val, y_val) ) plot(history) # retrain model with peak epochs from validation model <- keras_model_sequential() %>% layer_dense(units = 16, activation = "relu", input_shape = nrow(word_index)) %>% layer_dense(units = 16, activation = "relu") %>% layer_dense(units = 1, activation = "sigmoid") model %>% compile( optimizer = "rmsprop", loss = "binary_crossentropy", metrics = c("accuracy") ) model %>% fit( x_train, y_train, epochs = 32, batch_size = 300 ) results <- model %>% evaluate(x_test, y_test) results predictions <- model %>% predict(x_test) predictions_check <- tibble(tweet = test_data, accident = y_test, prediction = predictions[,1]) %>% mutate(predict_accident = 0) %>% mutate(predict_accident = replace(predict_accident, prediction > .70, 1)) %>% mutate(correct = case_when(accident == predict_accident ~ 1)) %>% mutate(correct = replace(correct, is.na(correct), 0)) table(predictions_check$predict_accident) table(predictions_check$accident) mean(predictions_check$correct) ### Function for predicting new Tweets predict_accident <- function(tweet) { tweet_index <- make_index_list(tweet) tweet_vectorized <- vectorize_sequences(tweet_index) prediction <- model %>% predict(tweet_vectorized) if(prediction > .80) { list("This Tweet describes an accident.", tweet, prediction) } else { list("This Tweet does not describe an accident.", tweet, prediction) } } predict_accident("22:36 @KeNHAKenya the pothole is still there! (as you approach sigona from Limuru)Those are 4 cars with punctures! At this hour- and in the rain . For how long will Kenyans suffer?? @JamesMacharia_ via @bnyenjeri") predict_accident("heavy traffic between Roysambu zimmerman. alternative routes via") predict_accident("21:33 Ruaka route is really bad!. No cops to Assist control traffic. Sad!! via @FaithMunyasi") predict_accident("18:25 hit and run on Waiyaki Way causing snarl up. https://twitter.com/aqueerian/status/992787431157129217/photo/1pic.twitter.com/aaKMgmf8Zi via @aqueerian") predict_accident("18:24 Has anyone ever received these monies police claim? Witnesses come forward,,me i know ukiwaambia unamjua ndo utajua hujui via @Mkulima18") predict_accident("JAPAN: Bus drivers in Okayama have gone on strike, by continuing to drive their routes while refusing to take fares from passengers.") predict_accident("16:57 Avoid Outering Rd from Taj Mall towards Donholm.Traffic bumper to bumper, via @CaroleOO16") predict_accident("16:55 I passed their a few hours ago and was astonished by how drivers can be...parking vehicles on the road to go and peep at a crashed vehicle causing huge traffic snarl up ..... Every parked vehicle needed to be booked for obstruction via @MateMurithi") predict_accident("16:27 Stuck truck at Outering exit juu to Doni caltex frm pipeline creating jam kubwa via @simwa_") predict_accident("15:38 Very heavy traffic in Juja on your way to Thika. Still trying to recover the lorry that plunged into Ndarugo river. via @ThikaTowntoday") predict_accident("12:52 Alert: Accident involving motorbike and private car at the Bomas of Kenya near \"KWS\" College on Langata Road. Exercise caution. + No police on sight. https://twitter.com/GrayMarwa/status/992697224583897088 … via @GrayMarwa") predict_accident("12:28 Snarl up on Langata Road caused by accident involving a motorcycle & motor vehicle after Bomas before the National Park. via @Jaxon09") predict_accident("12:18 From South c to Uhuru High way towards CBD moving smoothlyπŸš™πŸš™πŸš™πŸš™πŸš™πŸš™πŸš™ Mombasa Road via @Eng_Onsoti") predict_accident("12:09 @NairobiAlerts @digitalmkenya Our laws are funny though,, the prosecutor had to prove the pastor intended to kill the said victim. Otherwise, it wil be treated as an accident and the best the family can do is to follow https://www.ma3route.com/update/703679 via @MatthewsMbuthia") predict_accident("12:02 @alfredootieno He promised a change in 100 days. What we have seen is painful. Water shortage is even beyond words can describe. Traffic has become the order of the day. What kind of patience are you talking about? via @AderaJacob") predict_accident("11:21 avoid route between muthaiga mini mkt and parklands. Bumper to bumper traffic as usual. via @Its_Sheshii") predict_accident("10:47 @Dj_Amar_B Riverside drive has become a construction site. I assume someone is blasting some site. via @Pagmainc") predict_accident("10:32 Speed trap as you approach Kinoo.. via @njauwamahugu") predict_accident("10:29 @KenyaPower_Care A pole has fallen/leaning on a vehicle along Gaberone rd off Luthuli avenue via @kimaniq") predict_accident("Fatal accident at Kiwanja on Nothern bypass cleared.huge crowd on the road side. Boda boda rider taken to hospital.the deceased was a pillion passenger @Kiss100kenya @PRSA_Roadsafety @NPSOfficial_KE @KURAroads @RadioJamboKenya @inooroke @CapitalFMKenya @2Fmke @K24Tv @ntsa_kenya ") predict_accident("10:11 @NPSOfficial_KE corruption thriving along Msa road just after machakos towards konza. cops in a highway xtrail patrol car via @cymohnganga") # remove hashtags and some stop words (in a) predict_accident("corruption thriving along Msa road just after machakos towards konza. cops highway xtrail patrol car via") predict_accident("09:39 Via @MwendeCharles Nothing beats a Subaru. The way these machines negotiate sharp bends at 150Km/hr! Damn! @NairobiAlerts via @digitalmkenya")
/scripts/classify_32_300_90.R
no_license
robtenorio/classify-accidents
R
false
false
8,390
r
library(here) library(keras) library(tidytext) library(tidyverse) set.seed(55) tweets <- read_csv(here("tweets", "truthdata_allrounds.csv")) %>% mutate(accident = NA) %>% mutate(accident = replace(accident, accident_truth == "No", 0)) %>% mutate(accident = replace(accident, accident_truth == "Yes", 1)) %>% select("tweet", "accident") %>% na.omit table(tweets$accident) # pre-process text text_process <- function(text, stopwords = FALSE, lower = FALSE) { # remove time stamp and other numbers #text_data <- gsub("[[:digit:]]*|\\r", "", text) cat_text <- paste(text, collapse=" ") text_sequence <- unique(text_to_word_sequence(cat_text, split = " ", lower = lower)) if(stopwords) { text_index <- tibble(word = text_sequence, index = 1:length(text_sequence)) %>% anti_join(get_stopwords(), by = "word") } else { text_index <- tibble(word = text_sequence, index = 1:length(text_sequence)) } text_index } # create a word index to match text to integers word_index <- text_process(tweets$tweet) # make integer sequences of tweet text make_index_list <- function(x) { data_index <- c() for (i in 1:length(x)) { text <- x[[i]] x_seq <- text_to_word_sequence(text, split = " ", lower = FALSE) x_int <- c() for(n in x_seq) { int <- word_index$index[word_index$word %in% n] x_int <- c(x_int, int) x_int } data_index[[i]] <- x_int } data_index } # hot encode integer sequences vectorize_sequences <- function(sequences, dimension = nrow(word_index)) { results <- matrix(0, nrow = length(sequences), ncol = dimension) for (i in 1:length(sequences)) { results[i, sequences[[i]]] <- 1 } results } # separate tweet data into training and testing sets index2train <- sample(1:nrow(tweets), nrow(tweets)/2) # data train_data <- tweets$tweet[index2train] test_data <- tweets$tweet[-index2train] # labels y_train <- tweets$accident[index2train] y_test <- tweets$accident[-index2train] # convert words to integers based on their place in the dictionary test_index <- make_index_list(test_data) train_index <- make_index_list(train_data) x_train <- vectorize_sequences(train_index) x_test <- vectorize_sequences(test_index) #val_indices <- sample(1:nrow(x_train), 500) val_indices <- 1:500 x_val <- x_train[val_indices,] partial_x_train <- x_train[-val_indices,] y_val <- y_train[val_indices] partial_y_train <- y_train[-val_indices] model <- keras_model_sequential() %>% layer_dense(units = 16, activation = "relu", input_shape = nrow(word_index)) %>% layer_dense(units = 16, activation = "relu") %>% layer_dense(units = 1, activation = "sigmoid") model %>% compile( optimizer = "rmsprop", loss = "binary_crossentropy", metrics = c("accuracy") ) history <- model %>% fit( partial_x_train, partial_y_train, epochs = 50, batch_size = 300, validation_data = list(x_val, y_val) ) plot(history) # retrain model with peak epochs from validation model <- keras_model_sequential() %>% layer_dense(units = 16, activation = "relu", input_shape = nrow(word_index)) %>% layer_dense(units = 16, activation = "relu") %>% layer_dense(units = 1, activation = "sigmoid") model %>% compile( optimizer = "rmsprop", loss = "binary_crossentropy", metrics = c("accuracy") ) model %>% fit( x_train, y_train, epochs = 32, batch_size = 300 ) results <- model %>% evaluate(x_test, y_test) results predictions <- model %>% predict(x_test) predictions_check <- tibble(tweet = test_data, accident = y_test, prediction = predictions[,1]) %>% mutate(predict_accident = 0) %>% mutate(predict_accident = replace(predict_accident, prediction > .70, 1)) %>% mutate(correct = case_when(accident == predict_accident ~ 1)) %>% mutate(correct = replace(correct, is.na(correct), 0)) table(predictions_check$predict_accident) table(predictions_check$accident) mean(predictions_check$correct) ### Function for predicting new Tweets predict_accident <- function(tweet) { tweet_index <- make_index_list(tweet) tweet_vectorized <- vectorize_sequences(tweet_index) prediction <- model %>% predict(tweet_vectorized) if(prediction > .80) { list("This Tweet describes an accident.", tweet, prediction) } else { list("This Tweet does not describe an accident.", tweet, prediction) } } predict_accident("22:36 @KeNHAKenya the pothole is still there! (as you approach sigona from Limuru)Those are 4 cars with punctures! At this hour- and in the rain . For how long will Kenyans suffer?? @JamesMacharia_ via @bnyenjeri") predict_accident("heavy traffic between Roysambu zimmerman. alternative routes via") predict_accident("21:33 Ruaka route is really bad!. No cops to Assist control traffic. Sad!! via @FaithMunyasi") predict_accident("18:25 hit and run on Waiyaki Way causing snarl up. https://twitter.com/aqueerian/status/992787431157129217/photo/1pic.twitter.com/aaKMgmf8Zi via @aqueerian") predict_accident("18:24 Has anyone ever received these monies police claim? Witnesses come forward,,me i know ukiwaambia unamjua ndo utajua hujui via @Mkulima18") predict_accident("JAPAN: Bus drivers in Okayama have gone on strike, by continuing to drive their routes while refusing to take fares from passengers.") predict_accident("16:57 Avoid Outering Rd from Taj Mall towards Donholm.Traffic bumper to bumper, via @CaroleOO16") predict_accident("16:55 I passed their a few hours ago and was astonished by how drivers can be...parking vehicles on the road to go and peep at a crashed vehicle causing huge traffic snarl up ..... Every parked vehicle needed to be booked for obstruction via @MateMurithi") predict_accident("16:27 Stuck truck at Outering exit juu to Doni caltex frm pipeline creating jam kubwa via @simwa_") predict_accident("15:38 Very heavy traffic in Juja on your way to Thika. Still trying to recover the lorry that plunged into Ndarugo river. via @ThikaTowntoday") predict_accident("12:52 Alert: Accident involving motorbike and private car at the Bomas of Kenya near \"KWS\" College on Langata Road. Exercise caution. + No police on sight. https://twitter.com/GrayMarwa/status/992697224583897088 … via @GrayMarwa") predict_accident("12:28 Snarl up on Langata Road caused by accident involving a motorcycle & motor vehicle after Bomas before the National Park. via @Jaxon09") predict_accident("12:18 From South c to Uhuru High way towards CBD moving smoothlyπŸš™πŸš™πŸš™πŸš™πŸš™πŸš™πŸš™ Mombasa Road via @Eng_Onsoti") predict_accident("12:09 @NairobiAlerts @digitalmkenya Our laws are funny though,, the prosecutor had to prove the pastor intended to kill the said victim. Otherwise, it wil be treated as an accident and the best the family can do is to follow https://www.ma3route.com/update/703679 via @MatthewsMbuthia") predict_accident("12:02 @alfredootieno He promised a change in 100 days. What we have seen is painful. Water shortage is even beyond words can describe. Traffic has become the order of the day. What kind of patience are you talking about? via @AderaJacob") predict_accident("11:21 avoid route between muthaiga mini mkt and parklands. Bumper to bumper traffic as usual. via @Its_Sheshii") predict_accident("10:47 @Dj_Amar_B Riverside drive has become a construction site. I assume someone is blasting some site. via @Pagmainc") predict_accident("10:32 Speed trap as you approach Kinoo.. via @njauwamahugu") predict_accident("10:29 @KenyaPower_Care A pole has fallen/leaning on a vehicle along Gaberone rd off Luthuli avenue via @kimaniq") predict_accident("Fatal accident at Kiwanja on Nothern bypass cleared.huge crowd on the road side. Boda boda rider taken to hospital.the deceased was a pillion passenger @Kiss100kenya @PRSA_Roadsafety @NPSOfficial_KE @KURAroads @RadioJamboKenya @inooroke @CapitalFMKenya @2Fmke @K24Tv @ntsa_kenya ") predict_accident("10:11 @NPSOfficial_KE corruption thriving along Msa road just after machakos towards konza. cops in a highway xtrail patrol car via @cymohnganga") # remove hashtags and some stop words (in a) predict_accident("corruption thriving along Msa road just after machakos towards konza. cops highway xtrail patrol car via") predict_accident("09:39 Via @MwendeCharles Nothing beats a Subaru. The way these machines negotiate sharp bends at 150Km/hr! Damn! @NairobiAlerts via @digitalmkenya")
context("list") skip_on_cran() skip_if_not_installed("modeltests") library(modeltests) test_that("not all lists can be tidied", { nl <- list(a = NULL) expect_error(tidy(nl), "No tidy method recognized for this list.") expect_error(glance(nl), "No glance method recognized for this list.") })
/tests/testthat/test-list.R
permissive
tidymodels/broom
R
false
false
302
r
context("list") skip_on_cran() skip_if_not_installed("modeltests") library(modeltests) test_that("not all lists can be tidied", { nl <- list(a = NULL) expect_error(tidy(nl), "No tidy method recognized for this list.") expect_error(glance(nl), "No glance method recognized for this list.") })
\name{edbGetActiveParticipants} \alias{edbGetActiveParticipants} \title{Returns dataframe with info about all active participants} \description{ Returns dataframe with info about all active participants } \usage{edbGetActiveParticipants(d)} \arguments{ \item{d}{cleaned enrollment database as dataframe} } \value{Returns a dataframe} \author{John J. Curtin \email{jjcurtin@wisc.edu}}
/man/edbGetActiveParticipants.Rd
no_license
jjcurtin/StudySupport
R
false
false
385
rd
\name{edbGetActiveParticipants} \alias{edbGetActiveParticipants} \title{Returns dataframe with info about all active participants} \description{ Returns dataframe with info about all active participants } \usage{edbGetActiveParticipants(d)} \arguments{ \item{d}{cleaned enrollment database as dataframe} } \value{Returns a dataframe} \author{John J. Curtin \email{jjcurtin@wisc.edu}}
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/export.r \name{CreateCsv} \alias{CreateCsv} \title{Create CSV} \usage{ CreateCsv(ediData, filePath) } \arguments{ \item{ediData}{The EDI data in format of data frame or ffdf containing the data to be inserted.} \item{filePath}{path and file name where CSV is written} } \description{ Create CSV } \details{ Generate CSV with snake-case columns }
/man/CreateCsv.Rd
permissive
parkyijoo/EdiToOmop
R
false
true
425
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/export.r \name{CreateCsv} \alias{CreateCsv} \title{Create CSV} \usage{ CreateCsv(ediData, filePath) } \arguments{ \item{ediData}{The EDI data in format of data frame or ffdf containing the data to be inserted.} \item{filePath}{path and file name where CSV is written} } \description{ Create CSV } \details{ Generate CSV with snake-case columns }
library(CaDENCE) ### Name: cadence.predict ### Title: Predict conditional distribution parameters from a fitted CDEN ### model ### Aliases: cadence.predict cadence.evaluate ### ** Examples data(FraserSediment) lnorm.distribution.fixed <- list(density.fcn = dlnorm, parameters = c("meanlog", "sdlog"), parameters.fixed = "sdlog", output.fcns = c(identity, exp)) fit <- cadence.fit(x = FraserSediment$x.1970.1976, y = FraserSediment$y.1970.1976, hidden.fcn = identity, maxit.Nelder = 100, trace.Nelder = 1, trace = 1, distribution = lnorm.distribution.fixed) pred <- cadence.predict(x = FraserSediment$x.1977.1979, fit = fit) matplot(pred, type = "l")
/data/genthat_extracted_code/CaDENCE/examples/cadence.predict.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
882
r
library(CaDENCE) ### Name: cadence.predict ### Title: Predict conditional distribution parameters from a fitted CDEN ### model ### Aliases: cadence.predict cadence.evaluate ### ** Examples data(FraserSediment) lnorm.distribution.fixed <- list(density.fcn = dlnorm, parameters = c("meanlog", "sdlog"), parameters.fixed = "sdlog", output.fcns = c(identity, exp)) fit <- cadence.fit(x = FraserSediment$x.1970.1976, y = FraserSediment$y.1970.1976, hidden.fcn = identity, maxit.Nelder = 100, trace.Nelder = 1, trace = 1, distribution = lnorm.distribution.fixed) pred <- cadence.predict(x = FraserSediment$x.1977.1979, fit = fit) matplot(pred, type = "l")
\name{b.com.est} \alias{b.com.est} \title{ Common slope estimation } \description{ Estimates a common slope from bivariate data for several independent groups. Called by \code{\link{slope.com}}. } \usage{ b.com.est(z, n, method, lambda = 1, res.df) } \arguments{ \item{z}{ Variances and covariances of each group. } \item{n}{ Sample sizes of each group. } \item{method}{ See \code{\link{slope.com}} for details. } \item{lambda}{ Error variance ration (implied by choice of method). } \item{res.df}{ Residual degrees of freedom, for each group. } } \author{ Warton, D. \email{David.Warton@unsw.edu.au} and J. Ormerod } \seealso{ \code{\link{slope.com}} } \keyword{ internal }
/man/b.com.est.Rd
no_license
cran/smatr
R
false
false
714
rd
\name{b.com.est} \alias{b.com.est} \title{ Common slope estimation } \description{ Estimates a common slope from bivariate data for several independent groups. Called by \code{\link{slope.com}}. } \usage{ b.com.est(z, n, method, lambda = 1, res.df) } \arguments{ \item{z}{ Variances and covariances of each group. } \item{n}{ Sample sizes of each group. } \item{method}{ See \code{\link{slope.com}} for details. } \item{lambda}{ Error variance ration (implied by choice of method). } \item{res.df}{ Residual degrees of freedom, for each group. } } \author{ Warton, D. \email{David.Warton@unsw.edu.au} and J. Ormerod } \seealso{ \code{\link{slope.com}} } \keyword{ internal }