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
# R script for Course Project W1 - Exploratory Data Analysis # Create Plot 3 # Last modified 2014-07-12 # Created by Ulf Rosén # Read source data source("readSource.R") # Plot 3 png(filename="plot3.png", width=480, height=480) with(reducedConsumption, plot(DateTime, Sub_metering_1, type="l", ylab = "Energy sub metering", xlab="")) with(reducedConsumption, lines(DateTime, Sub_metering_2, col="red")) with(reducedConsumption, lines(DateTime, Sub_metering_3, col="blue")) legend("topright", lty=1, col=c("black","blue", "red"), legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) dev.off()
/plot3.R
no_license
UffeG/ExData_Plotting1
R
false
false
606
r
# R script for Course Project W1 - Exploratory Data Analysis # Create Plot 3 # Last modified 2014-07-12 # Created by Ulf Rosén # Read source data source("readSource.R") # Plot 3 png(filename="plot3.png", width=480, height=480) with(reducedConsumption, plot(DateTime, Sub_metering_1, type="l", ylab = "Energy sub metering", xlab="")) with(reducedConsumption, lines(DateTime, Sub_metering_2, col="red")) with(reducedConsumption, lines(DateTime, Sub_metering_3, col="blue")) legend("topright", lty=1, col=c("black","blue", "red"), legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) dev.off()
interscal.delta <- function(sym.data) { res<-interval.dist(sym.data,distance='interscal') CMin<-res$min.matrix CMax<-res$max.matrix Fil<-sym.data$N D2M<-matrix(0,2*Fil,2*Fil) for(i in 1:Fil) { for(j in i:Fil) { if(i==j) { if(j!=Fil) { D2M[2*i-1,2*j-1]<-0 D2M[2*i,2*j]<-0 D2M[2*i-1,2*j]<-CMax[i,j] D2M[2*j,2*i-1]<-D2M[2*i-1,2*j] } else { D2M[2*i-1,2*j-1]<-0 D2M[2*i,2*j]<-0 D2M[2*i-1,2*j]<-CMax[i,i] D2M[2*j,2*i-1]<-D2M[2*i-1,2*j] } } else { D2M[2*i-1,2*j-1]<-CMin[i,j] D2M[2*i,2*j]<-CMax[i,j] D2M[2*i-1,2*j]<-(CMax[i,j]+CMin[i,j])/2 D2M[2*i,2*j-1]<-(CMax[i,j]+CMin[i,j])/2 D2M[2*j-1,2*i-1]<-D2M[2*i-1,2*j-1] D2M[2*j,2*i]<-D2M[2*i,2*j] D2M[2*j,2*i-1]<-D2M[2*i-1,2*j] D2M[2*j-1,2*i]<-D2M[2*i,2*j-1] } } } return(D2M) }
/RSDA/R/interscal.delta.R
no_license
ingted/R-Examples
R
false
false
988
r
interscal.delta <- function(sym.data) { res<-interval.dist(sym.data,distance='interscal') CMin<-res$min.matrix CMax<-res$max.matrix Fil<-sym.data$N D2M<-matrix(0,2*Fil,2*Fil) for(i in 1:Fil) { for(j in i:Fil) { if(i==j) { if(j!=Fil) { D2M[2*i-1,2*j-1]<-0 D2M[2*i,2*j]<-0 D2M[2*i-1,2*j]<-CMax[i,j] D2M[2*j,2*i-1]<-D2M[2*i-1,2*j] } else { D2M[2*i-1,2*j-1]<-0 D2M[2*i,2*j]<-0 D2M[2*i-1,2*j]<-CMax[i,i] D2M[2*j,2*i-1]<-D2M[2*i-1,2*j] } } else { D2M[2*i-1,2*j-1]<-CMin[i,j] D2M[2*i,2*j]<-CMax[i,j] D2M[2*i-1,2*j]<-(CMax[i,j]+CMin[i,j])/2 D2M[2*i,2*j-1]<-(CMax[i,j]+CMin[i,j])/2 D2M[2*j-1,2*i-1]<-D2M[2*i-1,2*j-1] D2M[2*j,2*i]<-D2M[2*i,2*j] D2M[2*j,2*i-1]<-D2M[2*i-1,2*j] D2M[2*j-1,2*i]<-D2M[2*i,2*j-1] } } } return(D2M) }
context("check.formulas") data <- nhanes where <- is.na(data) # blocks <- name.blocks(list("bmi", "age", "chl")) # ini <- mice(data, blocks = blocks, maxit = 0) # # # classic type specification # setup <- list(blocks = blocks, # predictorMatrix = ini$predictorMatrix, # formulas = NULL) # # v1 <- mice:::check.formulas(setup, data) # # # using a formula # #formulas <- v1$formulas # setup <- list(blocks = blocks, # predictorMatrix = ini$predictorMatrix, # formulas = formulas) # #v2 <- mice:::check.formulas(setup, data) # #v2$formulas # # test_that("updates `mode.formula` attribute", { # # expect_false(identical(v2$formulas, v2$formulas.arg)) # # expect_identical(v2$formulas[[1]], v2$formulas.arg[[1]]) # }) # # # try dot in formula # formulas <- list(bmi ~ ., age ~ ., chl ~ .) # formulas <- name.formulas(formulas) # setup <- list(blocks = blocks, # predictorMatrix = ini$predictorMatrix, # formulas = formulas) # #v3 <- mice:::check.formulas(setup, data) # #v3$formulas # # # classic specification using predictorMatrix # imp1 <- mice(nhanes, seed = 51212, print = FALSE, m = 1) # cmp1 <- complete(imp1) # # # formula specification # form <- list(age ~ ., bmi ~ ., hyp ~., chl ~ .) # imp2 <- mice(nhanes, formulas = form, seed = 51212, print = FALSE, m = 1) # cmp2 <- complete(imp2) # # test_that("predictorMatrix and formula yield same imputations", { # expect_identical(cmp1, cmp2) # expect_identical(imp1$imp, imp2$imp) # }) # formula specification form <- name.blocks(list(bmi ~ ., hyp ~., chl ~ .)) imp3 <- mice(nhanes, formulas = form, seed = 51212, print = FALSE, m = 1) cmp3 <- complete(imp3) # old.form <- c("", "bmi ~ chl + hyp", "hyp ~ bmi + chl", "chl ~ bmi + hyp") # imp <- mice(nhanes, formula = old.form, m = 1, maxit = 2, print = FALSE) # # form1 <- list(bmi = ~ 1, chl = ~ 1, hyp = ~ 1) # # impute given predictors # imp1 <- mice(nhanes, formula = form1, m = 1, maxit = 2, method = "norm.predict", # print = FALSE, seed = 1) # # impute the mean # imp2 <- mice(nhanes, formula = form1, m = 1, maxit = 2, method = "norm.predict", # print = FALSE, seed = 1) # # form2 <- list(bmi = "hyp ~ 1", chl = "hyp ~ 1", hyp = "hyp ~ 1") # imp3 <- mice(nhanes, formula = form2, m = 1, maxit = 2, method = "norm.predict", # print = FALSE, seed = 1) #
/tests/testthat/test-check.formula.R
no_license
worldbank/mice
R
false
false
2,480
r
context("check.formulas") data <- nhanes where <- is.na(data) # blocks <- name.blocks(list("bmi", "age", "chl")) # ini <- mice(data, blocks = blocks, maxit = 0) # # # classic type specification # setup <- list(blocks = blocks, # predictorMatrix = ini$predictorMatrix, # formulas = NULL) # # v1 <- mice:::check.formulas(setup, data) # # # using a formula # #formulas <- v1$formulas # setup <- list(blocks = blocks, # predictorMatrix = ini$predictorMatrix, # formulas = formulas) # #v2 <- mice:::check.formulas(setup, data) # #v2$formulas # # test_that("updates `mode.formula` attribute", { # # expect_false(identical(v2$formulas, v2$formulas.arg)) # # expect_identical(v2$formulas[[1]], v2$formulas.arg[[1]]) # }) # # # try dot in formula # formulas <- list(bmi ~ ., age ~ ., chl ~ .) # formulas <- name.formulas(formulas) # setup <- list(blocks = blocks, # predictorMatrix = ini$predictorMatrix, # formulas = formulas) # #v3 <- mice:::check.formulas(setup, data) # #v3$formulas # # # classic specification using predictorMatrix # imp1 <- mice(nhanes, seed = 51212, print = FALSE, m = 1) # cmp1 <- complete(imp1) # # # formula specification # form <- list(age ~ ., bmi ~ ., hyp ~., chl ~ .) # imp2 <- mice(nhanes, formulas = form, seed = 51212, print = FALSE, m = 1) # cmp2 <- complete(imp2) # # test_that("predictorMatrix and formula yield same imputations", { # expect_identical(cmp1, cmp2) # expect_identical(imp1$imp, imp2$imp) # }) # formula specification form <- name.blocks(list(bmi ~ ., hyp ~., chl ~ .)) imp3 <- mice(nhanes, formulas = form, seed = 51212, print = FALSE, m = 1) cmp3 <- complete(imp3) # old.form <- c("", "bmi ~ chl + hyp", "hyp ~ bmi + chl", "chl ~ bmi + hyp") # imp <- mice(nhanes, formula = old.form, m = 1, maxit = 2, print = FALSE) # # form1 <- list(bmi = ~ 1, chl = ~ 1, hyp = ~ 1) # # impute given predictors # imp1 <- mice(nhanes, formula = form1, m = 1, maxit = 2, method = "norm.predict", # print = FALSE, seed = 1) # # impute the mean # imp2 <- mice(nhanes, formula = form1, m = 1, maxit = 2, method = "norm.predict", # print = FALSE, seed = 1) # # form2 <- list(bmi = "hyp ~ 1", chl = "hyp ~ 1", hyp = "hyp ~ 1") # imp3 <- mice(nhanes, formula = form2, m = 1, maxit = 2, method = "norm.predict", # print = FALSE, seed = 1) #
library(ape) library(geiger) library(phytools) library(reshape) library(ggplot2) library(adespatial) library(rgdal) library(raster) library(plyr) # MAMMALS DATASET ------------------------------------------------------ # importing the datasets from small, mid and large size mammals # Small Mammals SM_species <- read.csv(here::here("data", "raw", "Dataset_Mammals", "Species", 'ATLANTIC_SM_Capture.csv'), header = T, sep = ";") SM_sites <- read.csv(here::here("data", "raw", "Dataset_Mammals", "Species", 'ATLANTIC_SM_Study_Site.csv'), header = T, sep = ";") # merging information for some small mammals dataset ---------------------- head(SM_species) head(SM_sites) SM_data <- merge(x = SM_species, y = SM_sites, by = "ID", all.x = T) head(SM_data) # Mid-Large Mammals MLM_data <- read.csv(here::here("data", "raw", "Dataset_Mammals", "Species", 'ATLANTIC_MAMMAL_MID_LARGE _assemblages_and_sites.csv'), header = T, sep = ";") WR <- map_data("world") ecor_ma <- readOGR(here::here("Spatial_data", "limit_af_ribeiroetal2009_biorregions_gcs_wgs84.shp")) base.plot <- ggplot() + geom_polygon(data = WR, aes(x = long, y = lat, group = group), color = "black", fill = NA, size = 0.3) + geom_polygon(data = ecor_ma, aes(x = long, y = lat, group = group), fill = "darkseagreen2", alpha = 0.5) + xlim(-85, -30) + ylim(-60, 15) + theme(plot.background = element_blank(), panel.background = element_blank(), panel.border = element_rect(color = "gray20", size = .5, fill = NA), panel.grid.major = element_line(size = .5, linetype = "dashed", color = "gray80")) + ylab("Latitude") + xlab("Longitude") # unifying the datasets mid-large and small mammals ----------------------- MM_data <- data.frame(ID_dataset = c(SM_data$ID, MLM_data$ID), Species_names = c(SM_data$Species_name_on_paper, MLM_data$Species_name_on_paper), Valid_names = c(SM_data$Actual_species_name, MLM_data$Actual_species_Name), Latitude = c(SM_data$Latitude, MLM_data$Latitude), Longitude = c(SM_data$Longitude, MLM_data$Longitude)) MM_data$Valid_names <- gsub(" ", "_", MM_data$Valid_names) MM_data$Species_names <- gsub(" ", "_", MM_data$Species_names) MM_data <- arrange(MM_data, desc(Latitude)) MM_data <- MM_data[-which(MM_data$ID_dataset == "AML13"),] # excludind site without coords information tail(MM_data) MM_data$sites_ID <- NA tmp <- unique(MM_data[, c("Latitude", "Longitude")]) for(i in 1:nrow(tmp)){ pos <- which(MM_data$Latitude == tmp$Latitude[i] & MM_data$Longitude == tmp$Longitude[i]) MM_data[pos, "sites_ID"] <- paste("MM", i, sep = "") } str(MM_data) base.plot + geom_point(data = MM_data, aes(Longitude, Latitude), alpha = .5) # read the phylogenetic tree ---------------------------------------------- # Phylogenetic tree for Mammals (Upham, Esselstyn and Jetz, 2019) --------- MM_tree <- read.tree(here::here("data", "raw", "Dataset_Mammals", "Phylogeny", "RAxML_bipartitions.result_FIN4_raw_rooted_wBoots_4098mam1out_OK.newick")) str(MM_tree) t1 <- c(unlist(strsplit(MM_tree$tip.label, "_")), NA, NA) MM_df <- as.data.frame(matrix(t1, ncol = 4, nrow = length(MM_tree$tip.label), byrow = TRUE)) tail(MM_df) colnames(MM_df) <- c("Genus", "Epithet", "Family", "Order") MM_df$Species <- paste(MM_df$Genus, MM_df$Epithet, sep = "_") head(MM_df) MM_tree$tip.label <- MM_df$Species MM_tree write.tree(MM_tree, here::here("data/processed/Mammals/Tree_Mammals_edit.new")) # pruning the phylogenetic trees according with species occurrence -------- source(here::here("R", "functions", "function_treedata_modif.R")) # correcting names MM_data[which(MM_data[,"Valid_names"] == "Dayprocta_azarae"), "Valid_names"] <- "Dasyprocta_azarae" MM_data[which(MM_data[,"Valid_names"] == "Equus_cabalus"), "Valid_names"] <- "Equus_caballus" MM_data[which(MM_data[,"Valid_names"] == "Euryzygomatomys_spinosus_"), "Valid_names"] <- "Euryzygomatomys_spinosus" MM_data[which(MM_data[,"Valid_names"] == "Marmosa_paraguayana"), "Valid_names"] <- "Marmosa_paraguayanus" MM_data[which(MM_data[,"Valid_names"] == "Ozotocerus_bezoarticus"), "Valid_names"] <- "Ozotoceros_bezoarticus" MM_data[which(MM_data[,"Valid_names"] == "Pteronura_brasilienses"), "Valid_names"] <- "Pteronura_brasiliensis" MM_data[which(MM_data[,"Valid_names"] == "Scaptemorys_meridionalis"), "Valid_names"] <- "Scapteromys_meridionalis" MM_data[which(MM_data[,"Valid_names"] == "Alouatta_guariba_clamitans"), "Valid_names"] <- "Alouatta_guariba" MM_data[which(MM_data[,"Valid_names"] == "Alouatta_clamitans"), "Valid_names"] <- "Alouatta_guariba" MM_data[which(MM_data[,"Valid_names"] == "Sapajus_nigritus_cuculatus"), "Valid_names"] <- "Sapajus_nigritus" MM_data[which(MM_data[,"Valid_names"] == "Euphractus_sexcinctus_"), "Valid_names"] <- "Euphractus_sexcinctus" MM_data[which(MM_data[,"Valid_names"] == "Puma_yagouaroundi"), "Valid_names"] <- "Herpailurus_yagouaroundi" MM_data[which(MM_data[,"Valid_names"] == "Oxymycterus_sp._"), "Valid_names"] <- "Oxymycterus_sp." MM_data[which(MM_data[,"Valid_names"] == "Lycalopex_gymnocercus"), "Valid_names"] <- "Pseudalopex_gymnocercus" MM_data[which(MM_data[,"Valid_names"] == "Lycalopex_vetulus"), "Valid_names"] <- "Pseudalopex_vetulus" MM_data[which(MM_data[,"Valid_names"] == "Callithrix_kuhlli"), "Valid_names"] <- "Callithrix_kuhlii" MM_data[which(MM_data[,"Valid_names"] == "Canis_familiaris"), "Valid_names"] <- "Canis_lupus" # change some tips for prune MM_data[which(MM_data[,"Valid_names"] == "Leontopithecus_chrysopygus"), "Valid_names"] <- "Leontopithecus_chrysomelas" MM_data[which(MM_data[,"Valid_names"] == "Guerlinguetus_brasiliensis"), "Valid_names"] <- "Sciurus_aestuans" MM_data[which(MM_data[,"Valid_names"] == "Guerlinguetus_sp."), "Valid_names"] <- "Sciurus_sp." # we will place Sphigugurus_villosus near to Coendou # and Abrawayaomys_ruschii and Wilfredomys_oenax in the Cricetidae family # creating a list of species MM_spp <- MM_data$Valid_names MM_spp1 <- gsub("cf._", "", MM_spp) MM_spp1 <- unique(MM_spp1) MM_spp1 <- setNames(MM_spp1, MM_spp1) data_MM <- treedata_modif(MM_tree, MM_spp1) phy.MM <- data_MM$phy # 2nd round of insertions spp.add <- data_MM$nc$data_not_tree is.ultrametric(phy.MM) phy.MM <- force.ultrametric(phy.MM) ## add the remaining species as polytomy for (i in 1:length(spp.add)) { phy.MM <- add.species.to.genus(phy.MM, spp.add[i]) } spp.add[is.na(match(spp.add, phy.MM$tip.label))] # Inserting the nodes names for Sphiggurus -------------------------------- df.nodes <- data.frame(Genus = matrix(unlist(strsplit(phy.MM$tip.label, "_")), ncol = 2, byrow = T)[,1], Species = phy.MM$tip.label) df.nodes$family <- MM_df[match(df.nodes$Species, MM_df$Species), "Family"] df.nodes phy.MM1 <- phy.MM phy.MM1 <- ape::makeNodeLabel(phy.MM1, "u", nodeList = list(Coendou = phy.MM1$tip.label[1:4])) phy.MM1$node.label extract.clade(phy.MM1, node = "Coendou") position_genus <- which(c(phy.MM1$tip.label, phy.MM1$node.label) == "Coendou") size_branch_genus <- phy.MM1$edge.length[sapply(position_genus, function(x, y) which(y == x), y = phy.MM1$edge[,2])] phy.MM1 <- phytools::bind.tip(phy.MM1, "Sphiggurus_villosus", where = position_genus, position = size_branch_genus/2) phy.MM1 # inserting the node names for Cricetidae --------------------------------- # spp1 - Abrawayaomys_ruschii df.nodes <- data.frame(Genus = matrix(unlist(strsplit(phy.MM1$tip.label, "_")), ncol = 2, byrow = T)[,1], Species = phy.MM1$tip.label) df.nodes$family <- MM_df[match(df.nodes$Species, MM_df$Species), "Family"] df.nodes phy.MM1$tip.label[44:108] # checking the names of all representants of Cricetidae phy.MM1 <- ape::makeNodeLabel(phy.MM1, "u", nodeList = list(Cricetidae = phy.MM1$tip.label[44:108])) phy.MM1$node.label extract.clade(phy.MM1, node = "Cricetidae") position_family <- which(c(phy.MM1$tip.label, phy.MM1$node.label) == "Cricetidae") phy.MM1 <- phytools::bind.tip(phy.MM1, "Abrawayaomys_ruschii", where = position_family, position = 0) phy.MM1$tip.label[44:109] # spp2- Wilfredomys_oenax df.nodes <- data.frame(Genus = matrix(unlist(strsplit(phy.MM1$tip.label, "_")), ncol = 2, byrow = T)[,1], Species = phy.MM1$tip.label) df.nodes$family <- MM_df[match(df.nodes$Species, MM_df$Species), "Family"] df.nodes phy.MM1 <- ape::makeNodeLabel(phy.MM1, "u", nodeList = list(Cricetidae = phy.MM1$tip.label[44:109])) phy.MM1$node.label extract.clade(phy.MM1, node = "Cricetidae") position_family <- which(c(phy.MM1$tip.label, phy.MM1$node.label) == "Cricetidae") phy.MM1 <- phytools::bind.tip(phy.MM1, "Wilfredomys_oenax", where = position_family, position = 0) phy.MM1$tip.label[44:110] write.tree(phy.MM1, here::here("data/processed/Mammals/pruned_SMLM_tree.new")) # Calculating the taxonomic and phylogenetic BD --------------------------- # create a community matrix MM_data$Occ <- rep(1, dim(MM_data)[1]) colnames(MM_data) junk.melt <- melt(MM_data, id.var = c("Valid_names", "sites_ID"), measure.var = "Occ") Y <- cast(junk.melt, sites_ID ~ Valid_names) tail(Y) colnames(Y) rownames(Y) <- Y$sites_ID # remove the first and last columns Y <- Y[,-1] # check if are only 0/1 values max(Y) sum(rowSums(Y) == 0) comm_MM <- ifelse(Y >= 1, 1, 0) max(comm_MM) setdiff(colnames(comm_MM), phy.MM1$tip.label) colnames(comm_MM)[which(colnames(comm_MM)== "Cavia_cf._magna")] <- "Cavia_magna" saveRDS(comm_MM, here::here("data/processed/Mammals/Comm_MM.rds")) source(here::here("R", "functions", "Beta.div_adapt.R")) BDtax.MM <- adespatial::beta.div(Y = comm_MM, method = "chord") saveRDS(BDtax.MM, here::here("data/processed/Mammals/BDtaxMM.rds")) BDphy.MM <- Beta.div_adapt(Y = comm_MM, dist_spp = cophenetic(phy.MM1)) saveRDS(BDphy.MM, here::here("data/processed/Mammals/BDphyMM.rds")) # taking the information by sites # Extracting information of bioclim --------------------------------------- bioclim <- getData("worldclim", var = "bio", res = 5) # get data of worldclim site tmp <- MM_data[, c("Longitude", "Latitude")] # separate the coordinates in long lat (important) tmp <- unique(tmp) points <- SpatialPoints(tmp, proj4string = bioclim@crs) # put the coordinates in the same projection of data values <- extract(bioclim, points) # Extracting the bioclim of interest and for the coords sites env.MM <- cbind.data.frame(coordinates(points), values) rownames(env.MM) <- unique(MM_data$sites_ID) env.MM$Richness <- apply(comm_MM, 1, sum) str(env.MM) env.MM$PLCBD <- BDphy.MM$LCBDextend.obs env.MM$LCBD <- BDtax.MM$LCBD saveRDS(env.MM, here::here("data/processed/Mammals/env_MM.rds")) base.plot <- ggplot() + geom_polygon(data = WR, aes(x = long, y = lat, group = group), color = "black", fill = NA, size = 0.3) + geom_polygon(data = ecor_ma, aes(x = long, y = lat, group = group), fill = "darkseagreen2", alpha = 0.5) + xlim(-85, -30) + ylim(-60, 15) + theme(plot.background = element_blank(), panel.background = element_blank(), panel.border = element_rect(color = "gray20", size = .5, fill = NA), panel.grid.major = element_line(size = .5, linetype = "dashed", color = "gray80")) + ylab("Latitude") + xlab("Longitude") p.phy <- base.plot + geom_point(data = env.MM, aes(x = Longitude, y = Latitude, colour = PLCBD)) + scale_color_viridis_c(alpha = .8, option = "A", direction = -1) p.tax <- base.plot + geom_point(data = env.MM, aes(x = Longitude, y = Latitude, colour = LCBD)) + scale_color_viridis_c(alpha = .8, option = "A", direction = -1) p.ric <- base.plot + geom_point(data = env.MM, aes(x = Longitude, y = Latitude, colour = Richness)) + scale_color_viridis_c(alpha = .8, option = "A", direction = -1) p.bd <- cowplot::plot_grid(p.ric, p.tax, p.phy) p.bd
/R/SML_Mammals.R
no_license
richterbine/BetaDiversityAtlanticForest
R
false
false
12,716
r
library(ape) library(geiger) library(phytools) library(reshape) library(ggplot2) library(adespatial) library(rgdal) library(raster) library(plyr) # MAMMALS DATASET ------------------------------------------------------ # importing the datasets from small, mid and large size mammals # Small Mammals SM_species <- read.csv(here::here("data", "raw", "Dataset_Mammals", "Species", 'ATLANTIC_SM_Capture.csv'), header = T, sep = ";") SM_sites <- read.csv(here::here("data", "raw", "Dataset_Mammals", "Species", 'ATLANTIC_SM_Study_Site.csv'), header = T, sep = ";") # merging information for some small mammals dataset ---------------------- head(SM_species) head(SM_sites) SM_data <- merge(x = SM_species, y = SM_sites, by = "ID", all.x = T) head(SM_data) # Mid-Large Mammals MLM_data <- read.csv(here::here("data", "raw", "Dataset_Mammals", "Species", 'ATLANTIC_MAMMAL_MID_LARGE _assemblages_and_sites.csv'), header = T, sep = ";") WR <- map_data("world") ecor_ma <- readOGR(here::here("Spatial_data", "limit_af_ribeiroetal2009_biorregions_gcs_wgs84.shp")) base.plot <- ggplot() + geom_polygon(data = WR, aes(x = long, y = lat, group = group), color = "black", fill = NA, size = 0.3) + geom_polygon(data = ecor_ma, aes(x = long, y = lat, group = group), fill = "darkseagreen2", alpha = 0.5) + xlim(-85, -30) + ylim(-60, 15) + theme(plot.background = element_blank(), panel.background = element_blank(), panel.border = element_rect(color = "gray20", size = .5, fill = NA), panel.grid.major = element_line(size = .5, linetype = "dashed", color = "gray80")) + ylab("Latitude") + xlab("Longitude") # unifying the datasets mid-large and small mammals ----------------------- MM_data <- data.frame(ID_dataset = c(SM_data$ID, MLM_data$ID), Species_names = c(SM_data$Species_name_on_paper, MLM_data$Species_name_on_paper), Valid_names = c(SM_data$Actual_species_name, MLM_data$Actual_species_Name), Latitude = c(SM_data$Latitude, MLM_data$Latitude), Longitude = c(SM_data$Longitude, MLM_data$Longitude)) MM_data$Valid_names <- gsub(" ", "_", MM_data$Valid_names) MM_data$Species_names <- gsub(" ", "_", MM_data$Species_names) MM_data <- arrange(MM_data, desc(Latitude)) MM_data <- MM_data[-which(MM_data$ID_dataset == "AML13"),] # excludind site without coords information tail(MM_data) MM_data$sites_ID <- NA tmp <- unique(MM_data[, c("Latitude", "Longitude")]) for(i in 1:nrow(tmp)){ pos <- which(MM_data$Latitude == tmp$Latitude[i] & MM_data$Longitude == tmp$Longitude[i]) MM_data[pos, "sites_ID"] <- paste("MM", i, sep = "") } str(MM_data) base.plot + geom_point(data = MM_data, aes(Longitude, Latitude), alpha = .5) # read the phylogenetic tree ---------------------------------------------- # Phylogenetic tree for Mammals (Upham, Esselstyn and Jetz, 2019) --------- MM_tree <- read.tree(here::here("data", "raw", "Dataset_Mammals", "Phylogeny", "RAxML_bipartitions.result_FIN4_raw_rooted_wBoots_4098mam1out_OK.newick")) str(MM_tree) t1 <- c(unlist(strsplit(MM_tree$tip.label, "_")), NA, NA) MM_df <- as.data.frame(matrix(t1, ncol = 4, nrow = length(MM_tree$tip.label), byrow = TRUE)) tail(MM_df) colnames(MM_df) <- c("Genus", "Epithet", "Family", "Order") MM_df$Species <- paste(MM_df$Genus, MM_df$Epithet, sep = "_") head(MM_df) MM_tree$tip.label <- MM_df$Species MM_tree write.tree(MM_tree, here::here("data/processed/Mammals/Tree_Mammals_edit.new")) # pruning the phylogenetic trees according with species occurrence -------- source(here::here("R", "functions", "function_treedata_modif.R")) # correcting names MM_data[which(MM_data[,"Valid_names"] == "Dayprocta_azarae"), "Valid_names"] <- "Dasyprocta_azarae" MM_data[which(MM_data[,"Valid_names"] == "Equus_cabalus"), "Valid_names"] <- "Equus_caballus" MM_data[which(MM_data[,"Valid_names"] == "Euryzygomatomys_spinosus_"), "Valid_names"] <- "Euryzygomatomys_spinosus" MM_data[which(MM_data[,"Valid_names"] == "Marmosa_paraguayana"), "Valid_names"] <- "Marmosa_paraguayanus" MM_data[which(MM_data[,"Valid_names"] == "Ozotocerus_bezoarticus"), "Valid_names"] <- "Ozotoceros_bezoarticus" MM_data[which(MM_data[,"Valid_names"] == "Pteronura_brasilienses"), "Valid_names"] <- "Pteronura_brasiliensis" MM_data[which(MM_data[,"Valid_names"] == "Scaptemorys_meridionalis"), "Valid_names"] <- "Scapteromys_meridionalis" MM_data[which(MM_data[,"Valid_names"] == "Alouatta_guariba_clamitans"), "Valid_names"] <- "Alouatta_guariba" MM_data[which(MM_data[,"Valid_names"] == "Alouatta_clamitans"), "Valid_names"] <- "Alouatta_guariba" MM_data[which(MM_data[,"Valid_names"] == "Sapajus_nigritus_cuculatus"), "Valid_names"] <- "Sapajus_nigritus" MM_data[which(MM_data[,"Valid_names"] == "Euphractus_sexcinctus_"), "Valid_names"] <- "Euphractus_sexcinctus" MM_data[which(MM_data[,"Valid_names"] == "Puma_yagouaroundi"), "Valid_names"] <- "Herpailurus_yagouaroundi" MM_data[which(MM_data[,"Valid_names"] == "Oxymycterus_sp._"), "Valid_names"] <- "Oxymycterus_sp." MM_data[which(MM_data[,"Valid_names"] == "Lycalopex_gymnocercus"), "Valid_names"] <- "Pseudalopex_gymnocercus" MM_data[which(MM_data[,"Valid_names"] == "Lycalopex_vetulus"), "Valid_names"] <- "Pseudalopex_vetulus" MM_data[which(MM_data[,"Valid_names"] == "Callithrix_kuhlli"), "Valid_names"] <- "Callithrix_kuhlii" MM_data[which(MM_data[,"Valid_names"] == "Canis_familiaris"), "Valid_names"] <- "Canis_lupus" # change some tips for prune MM_data[which(MM_data[,"Valid_names"] == "Leontopithecus_chrysopygus"), "Valid_names"] <- "Leontopithecus_chrysomelas" MM_data[which(MM_data[,"Valid_names"] == "Guerlinguetus_brasiliensis"), "Valid_names"] <- "Sciurus_aestuans" MM_data[which(MM_data[,"Valid_names"] == "Guerlinguetus_sp."), "Valid_names"] <- "Sciurus_sp." # we will place Sphigugurus_villosus near to Coendou # and Abrawayaomys_ruschii and Wilfredomys_oenax in the Cricetidae family # creating a list of species MM_spp <- MM_data$Valid_names MM_spp1 <- gsub("cf._", "", MM_spp) MM_spp1 <- unique(MM_spp1) MM_spp1 <- setNames(MM_spp1, MM_spp1) data_MM <- treedata_modif(MM_tree, MM_spp1) phy.MM <- data_MM$phy # 2nd round of insertions spp.add <- data_MM$nc$data_not_tree is.ultrametric(phy.MM) phy.MM <- force.ultrametric(phy.MM) ## add the remaining species as polytomy for (i in 1:length(spp.add)) { phy.MM <- add.species.to.genus(phy.MM, spp.add[i]) } spp.add[is.na(match(spp.add, phy.MM$tip.label))] # Inserting the nodes names for Sphiggurus -------------------------------- df.nodes <- data.frame(Genus = matrix(unlist(strsplit(phy.MM$tip.label, "_")), ncol = 2, byrow = T)[,1], Species = phy.MM$tip.label) df.nodes$family <- MM_df[match(df.nodes$Species, MM_df$Species), "Family"] df.nodes phy.MM1 <- phy.MM phy.MM1 <- ape::makeNodeLabel(phy.MM1, "u", nodeList = list(Coendou = phy.MM1$tip.label[1:4])) phy.MM1$node.label extract.clade(phy.MM1, node = "Coendou") position_genus <- which(c(phy.MM1$tip.label, phy.MM1$node.label) == "Coendou") size_branch_genus <- phy.MM1$edge.length[sapply(position_genus, function(x, y) which(y == x), y = phy.MM1$edge[,2])] phy.MM1 <- phytools::bind.tip(phy.MM1, "Sphiggurus_villosus", where = position_genus, position = size_branch_genus/2) phy.MM1 # inserting the node names for Cricetidae --------------------------------- # spp1 - Abrawayaomys_ruschii df.nodes <- data.frame(Genus = matrix(unlist(strsplit(phy.MM1$tip.label, "_")), ncol = 2, byrow = T)[,1], Species = phy.MM1$tip.label) df.nodes$family <- MM_df[match(df.nodes$Species, MM_df$Species), "Family"] df.nodes phy.MM1$tip.label[44:108] # checking the names of all representants of Cricetidae phy.MM1 <- ape::makeNodeLabel(phy.MM1, "u", nodeList = list(Cricetidae = phy.MM1$tip.label[44:108])) phy.MM1$node.label extract.clade(phy.MM1, node = "Cricetidae") position_family <- which(c(phy.MM1$tip.label, phy.MM1$node.label) == "Cricetidae") phy.MM1 <- phytools::bind.tip(phy.MM1, "Abrawayaomys_ruschii", where = position_family, position = 0) phy.MM1$tip.label[44:109] # spp2- Wilfredomys_oenax df.nodes <- data.frame(Genus = matrix(unlist(strsplit(phy.MM1$tip.label, "_")), ncol = 2, byrow = T)[,1], Species = phy.MM1$tip.label) df.nodes$family <- MM_df[match(df.nodes$Species, MM_df$Species), "Family"] df.nodes phy.MM1 <- ape::makeNodeLabel(phy.MM1, "u", nodeList = list(Cricetidae = phy.MM1$tip.label[44:109])) phy.MM1$node.label extract.clade(phy.MM1, node = "Cricetidae") position_family <- which(c(phy.MM1$tip.label, phy.MM1$node.label) == "Cricetidae") phy.MM1 <- phytools::bind.tip(phy.MM1, "Wilfredomys_oenax", where = position_family, position = 0) phy.MM1$tip.label[44:110] write.tree(phy.MM1, here::here("data/processed/Mammals/pruned_SMLM_tree.new")) # Calculating the taxonomic and phylogenetic BD --------------------------- # create a community matrix MM_data$Occ <- rep(1, dim(MM_data)[1]) colnames(MM_data) junk.melt <- melt(MM_data, id.var = c("Valid_names", "sites_ID"), measure.var = "Occ") Y <- cast(junk.melt, sites_ID ~ Valid_names) tail(Y) colnames(Y) rownames(Y) <- Y$sites_ID # remove the first and last columns Y <- Y[,-1] # check if are only 0/1 values max(Y) sum(rowSums(Y) == 0) comm_MM <- ifelse(Y >= 1, 1, 0) max(comm_MM) setdiff(colnames(comm_MM), phy.MM1$tip.label) colnames(comm_MM)[which(colnames(comm_MM)== "Cavia_cf._magna")] <- "Cavia_magna" saveRDS(comm_MM, here::here("data/processed/Mammals/Comm_MM.rds")) source(here::here("R", "functions", "Beta.div_adapt.R")) BDtax.MM <- adespatial::beta.div(Y = comm_MM, method = "chord") saveRDS(BDtax.MM, here::here("data/processed/Mammals/BDtaxMM.rds")) BDphy.MM <- Beta.div_adapt(Y = comm_MM, dist_spp = cophenetic(phy.MM1)) saveRDS(BDphy.MM, here::here("data/processed/Mammals/BDphyMM.rds")) # taking the information by sites # Extracting information of bioclim --------------------------------------- bioclim <- getData("worldclim", var = "bio", res = 5) # get data of worldclim site tmp <- MM_data[, c("Longitude", "Latitude")] # separate the coordinates in long lat (important) tmp <- unique(tmp) points <- SpatialPoints(tmp, proj4string = bioclim@crs) # put the coordinates in the same projection of data values <- extract(bioclim, points) # Extracting the bioclim of interest and for the coords sites env.MM <- cbind.data.frame(coordinates(points), values) rownames(env.MM) <- unique(MM_data$sites_ID) env.MM$Richness <- apply(comm_MM, 1, sum) str(env.MM) env.MM$PLCBD <- BDphy.MM$LCBDextend.obs env.MM$LCBD <- BDtax.MM$LCBD saveRDS(env.MM, here::here("data/processed/Mammals/env_MM.rds")) base.plot <- ggplot() + geom_polygon(data = WR, aes(x = long, y = lat, group = group), color = "black", fill = NA, size = 0.3) + geom_polygon(data = ecor_ma, aes(x = long, y = lat, group = group), fill = "darkseagreen2", alpha = 0.5) + xlim(-85, -30) + ylim(-60, 15) + theme(plot.background = element_blank(), panel.background = element_blank(), panel.border = element_rect(color = "gray20", size = .5, fill = NA), panel.grid.major = element_line(size = .5, linetype = "dashed", color = "gray80")) + ylab("Latitude") + xlab("Longitude") p.phy <- base.plot + geom_point(data = env.MM, aes(x = Longitude, y = Latitude, colour = PLCBD)) + scale_color_viridis_c(alpha = .8, option = "A", direction = -1) p.tax <- base.plot + geom_point(data = env.MM, aes(x = Longitude, y = Latitude, colour = LCBD)) + scale_color_viridis_c(alpha = .8, option = "A", direction = -1) p.ric <- base.plot + geom_point(data = env.MM, aes(x = Longitude, y = Latitude, colour = Richness)) + scale_color_viridis_c(alpha = .8, option = "A", direction = -1) p.bd <- cowplot::plot_grid(p.ric, p.tax, p.phy) p.bd
% Generated by roxygen2 (4.0.2): do not edit by hand \name{dropFeatures} \alias{dropFeatures} \title{Drop some features of task.} \usage{ dropFeatures(task, features) } \arguments{ \item{task}{[\code{\link{Task}}]\cr The task.} \item{features}{[\code{character}]\cr Features to drop.} } \value{ [\code{\link{Task}}]. } \description{ Drop some features of task. } \seealso{ Other eda_and_preprocess: \code{\link{capLargeValues}}; \code{\link{createDummyFeatures}}; \code{\link{mergeSmallFactorLevels}}; \code{\link{normalizeFeatures}}; \code{\link{removeConstantFeatures}}; \code{\link{summarizeColumns}} }
/man/dropFeatures.Rd
no_license
narayana1208/mlr
R
false
false
618
rd
% Generated by roxygen2 (4.0.2): do not edit by hand \name{dropFeatures} \alias{dropFeatures} \title{Drop some features of task.} \usage{ dropFeatures(task, features) } \arguments{ \item{task}{[\code{\link{Task}}]\cr The task.} \item{features}{[\code{character}]\cr Features to drop.} } \value{ [\code{\link{Task}}]. } \description{ Drop some features of task. } \seealso{ Other eda_and_preprocess: \code{\link{capLargeValues}}; \code{\link{createDummyFeatures}}; \code{\link{mergeSmallFactorLevels}}; \code{\link{normalizeFeatures}}; \code{\link{removeConstantFeatures}}; \code{\link{summarizeColumns}} }
learn.bnlearn<-function(solverConfig, filename_template, currentDir = "./../tmp/", indPath = NULL, bckg_file = NULL, verbose=1) { #Function for running the learning tasks for score-based learning. #This implements an exact search over the bnlearn package. #The function is rather a quick fix. #D data set from createDataSet. #p_threshold - sparsity penalty for the BIC local score # #Results options (where to store the results and tmp files): #indFilename - the serialized version of independences, default: "pipeline.ind" solving_time <- tic() df <- data.frame(D[[1]]$data) p_threshold <- solverConfig$p n <- solverConfig$n D <- solverConfig$MD$D #exhaustive search, not optimally fast here since looping over orders #there does not seem to be a proper implementation of score-based learning #in the exact sense for R #empty graph #overall the best graph bestbestG<-array(0,c(n,n)) bestbestscore<-(-Inf) ind<-0 for ( corder in permn(n) ) { #loop through all causal orders ind<-ind+1 #These are the best options for the order bestG<-array(0,c(n,n)) bestscore<-bnlearn::score(as.bn( G2st(bestG) ),df,k=p_threshold*log(nrow(df))/2) for ( i in n:2 ) { #consider nodes from the end of the order to beginning G<-bestG #always start with the best here node<-corder[i] #cat('\tnode:',node,'\n') #find the possible parents for the node possible_parents<-corder[index(1,(i-1))] #print(possible_parents) #cat('\t\tpossible_parents:',possible_parents,'\n') bestscore<-(-Inf) for ( ipa in index(0,2^length(possible_parents)-1)) {#do not have consider 0 G[node,possible_parents]<-dec.to.bin(ipa,length(possible_parents)) score<-bnlearn::score(as.bn( G2st(G) ),df,k=p_threshold*log(nrow(df))/2) #cat(G[node,],'score=',score) if ( score > bestscore ) { bestG<-G bestscore<-score #cat('!') } #cat('\n') }#parent configuration }#for i/node #now bestG is the best given this order, updating if it is the best given all orders if ( bestscore > bestbestscore) { bestbestG<-bestG bestbestscore<-bestscore } cat(ind,'bestscore:',bestscore,'bestbestscore:',bestbestscore,'\n') }#for order # make the L object from the best graph L <- list() L$G <- bestbestG L$Ge <- array(0, c(n,n)) L$objective <- NA L$solving_time <- toc(solving_time) L$C <- dag2causes(L$G) L$G[which(L$G==0)] <- -1 L$C[which(L$C==0)] <- -1 # Note that these tested_independences are the ones from the oracle with schedule n-2. L }
/R/learn_model/learn.bnlearn.R
permissive
caus-am/aci
R
false
false
2,830
r
learn.bnlearn<-function(solverConfig, filename_template, currentDir = "./../tmp/", indPath = NULL, bckg_file = NULL, verbose=1) { #Function for running the learning tasks for score-based learning. #This implements an exact search over the bnlearn package. #The function is rather a quick fix. #D data set from createDataSet. #p_threshold - sparsity penalty for the BIC local score # #Results options (where to store the results and tmp files): #indFilename - the serialized version of independences, default: "pipeline.ind" solving_time <- tic() df <- data.frame(D[[1]]$data) p_threshold <- solverConfig$p n <- solverConfig$n D <- solverConfig$MD$D #exhaustive search, not optimally fast here since looping over orders #there does not seem to be a proper implementation of score-based learning #in the exact sense for R #empty graph #overall the best graph bestbestG<-array(0,c(n,n)) bestbestscore<-(-Inf) ind<-0 for ( corder in permn(n) ) { #loop through all causal orders ind<-ind+1 #These are the best options for the order bestG<-array(0,c(n,n)) bestscore<-bnlearn::score(as.bn( G2st(bestG) ),df,k=p_threshold*log(nrow(df))/2) for ( i in n:2 ) { #consider nodes from the end of the order to beginning G<-bestG #always start with the best here node<-corder[i] #cat('\tnode:',node,'\n') #find the possible parents for the node possible_parents<-corder[index(1,(i-1))] #print(possible_parents) #cat('\t\tpossible_parents:',possible_parents,'\n') bestscore<-(-Inf) for ( ipa in index(0,2^length(possible_parents)-1)) {#do not have consider 0 G[node,possible_parents]<-dec.to.bin(ipa,length(possible_parents)) score<-bnlearn::score(as.bn( G2st(G) ),df,k=p_threshold*log(nrow(df))/2) #cat(G[node,],'score=',score) if ( score > bestscore ) { bestG<-G bestscore<-score #cat('!') } #cat('\n') }#parent configuration }#for i/node #now bestG is the best given this order, updating if it is the best given all orders if ( bestscore > bestbestscore) { bestbestG<-bestG bestbestscore<-bestscore } cat(ind,'bestscore:',bestscore,'bestbestscore:',bestbestscore,'\n') }#for order # make the L object from the best graph L <- list() L$G <- bestbestG L$Ge <- array(0, c(n,n)) L$objective <- NA L$solving_time <- toc(solving_time) L$C <- dag2causes(L$G) L$G[which(L$G==0)] <- -1 L$C[which(L$C==0)] <- -1 # Note that these tested_independences are the ones from the oracle with schedule n-2. L }
v <- c(10,20,15) plot(v,type = "o")
/Day 3/line.R
no_license
iamdaaniyaal/Data-Analytics-Using-R
R
false
false
35
r
v <- c(10,20,15) plot(v,type = "o")
shade <- function(x, steps, crop) { shade <- rev(grDevices::colorRampPalette(c(x, "black"))(steps + 1)) if (crop == 0) { return(rev(shade)) } rev(shade[-(seq_len(crop))]) } tint <- function(x, steps, crop) { tint <- rev(grDevices::colorRampPalette(c(x, "white"))(steps + 1)) if (crop == 0) { return(tint) } tint[-(seq_len(crop))] }
/R/utils.R
permissive
sebdalgarno/tinter
R
false
false
357
r
shade <- function(x, steps, crop) { shade <- rev(grDevices::colorRampPalette(c(x, "black"))(steps + 1)) if (crop == 0) { return(rev(shade)) } rev(shade[-(seq_len(crop))]) } tint <- function(x, steps, crop) { tint <- rev(grDevices::colorRampPalette(c(x, "white"))(steps + 1)) if (crop == 0) { return(tint) } tint[-(seq_len(crop))] }
# GlobalVariables and/or columns in survdat data utils::globalVariables( c( "a", "abundance", "abund_actual", "abund_tow_epu", "abund_tow_s", "b", "biom_per_lclass", "biom_tow_epu", "biom_tow_s", "biomass", "biomass_kg", "catchsex", "common_name", "comname", "convers", "cruise6", "CRUISE6", "decdeg_beglat", "decdeg_beglon", "depth", "epu", "epu_area_km2", "epu_ntows", "epu_ratio", "est_day", "est_month", "est_towdate", "est_year", "strat_total_abund_epu", "strat_total_abund_s", "fishery", "hare_group", "id", "ind_log_wt", "ind_weight_kg", "lat", "LAT", "length_cm", "llen", "ln_a", "lon", "LON", "lwbio_tow_s", "lwbio_tow_epu", "n_len_class", "n_len_classes", "newstrata", "numlen", "numlen_adj", "oisst_path", "poststrat", "s_area_km2", "scientific_name", "season", "spec_class", "st_ratio", "start_date", "station", "STATION", "strat_ntows", "strat_num", "stratum", "STRATUM", "sum_weight_kg", "survdat.big", "survey", "svspp", "svvessel", "tot_epu_area", "tot_s_area", "strat_mean_abund_epu", "strat_mean_abund_s", "strat_mean_biom_epu", "strat_mean_biom_s", "year" ))
/R/globals.R
permissive
gulfofmaine/gmRi
R
false
false
1,384
r
# GlobalVariables and/or columns in survdat data utils::globalVariables( c( "a", "abundance", "abund_actual", "abund_tow_epu", "abund_tow_s", "b", "biom_per_lclass", "biom_tow_epu", "biom_tow_s", "biomass", "biomass_kg", "catchsex", "common_name", "comname", "convers", "cruise6", "CRUISE6", "decdeg_beglat", "decdeg_beglon", "depth", "epu", "epu_area_km2", "epu_ntows", "epu_ratio", "est_day", "est_month", "est_towdate", "est_year", "strat_total_abund_epu", "strat_total_abund_s", "fishery", "hare_group", "id", "ind_log_wt", "ind_weight_kg", "lat", "LAT", "length_cm", "llen", "ln_a", "lon", "LON", "lwbio_tow_s", "lwbio_tow_epu", "n_len_class", "n_len_classes", "newstrata", "numlen", "numlen_adj", "oisst_path", "poststrat", "s_area_km2", "scientific_name", "season", "spec_class", "st_ratio", "start_date", "station", "STATION", "strat_ntows", "strat_num", "stratum", "STRATUM", "sum_weight_kg", "survdat.big", "survey", "svspp", "svvessel", "tot_epu_area", "tot_s_area", "strat_mean_abund_epu", "strat_mean_abund_s", "strat_mean_biom_epu", "strat_mean_biom_s", "year" ))
# Copyright 2019 Battelle Memorial Institute; see the LICENSE file. #' module_water_L201.water_resources_constrained #' #' Constrained surface and groudwater. #' #' @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{L201.RenewRsrcCurves_calib}, #' \code{201.GrdRenewRsrcMax_runoff}, \code{L201.DepRsrcCurves_ground}. The corresponding file in the #' original data system was \code{L102.water_supply_unlimited.R} (water level1). #' @details Genereates water resource input files for region + basin which includes runoff and groundwater. #' @importFrom assertthat assert_that #' @importFrom dplyr anti_join case_when distinct filter if_else inner_join mutate pull right_join select #' @importFrom tidyr complete nesting #' @importFrom stats spline #' @author ST Oct 2018 module_water_L201.water_resources_constrained <- function(command, ...) { if(command == driver.DECLARE_INPUTS) { return(c(FILE = "water/basin_ID", FILE = "water/basin_to_country_mapping", FILE = "common/GCAM_region_names", FILE = "common/iso_GCAM_regID", FILE = "water/basin_water_demand_1990_2015", "L100.runoff_accessible", "L100.runoff_max_bm3", "L101.groundwater_depletion_bm3", "L101.groundwater_grades_constrained_bm3", "L101.groundwater_grades_uniform_bm3", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share")) } else if(command == driver.DECLARE_OUTPUTS) { return(c("L201.DeleteUnlimitRsrc", "L201.Rsrc", "L201.RsrcPrice", "L201.RenewRsrcCurves_uncalibrated", "L201.GrdRenewRsrcMax_runoff", "L201.DepRsrcCurves_ground_uniform", "L201.RenewRsrcCurves_calib", "L201.DepRsrcCurves_ground", "L201.RenewRsrcTechShrwt", "L201.RsrcTechShrwt")) } else if(command == driver.MAKE) { region <- ISO <- iso <- GCAM_basin_ID <- Basin_name <- GCAM_region_ID <- basin_id <- GLU <- water_type <- basin_name <- resource <- runoff_max <- renewresource <- year <- access_fraction <- sub.renewable.resource <- grade <- available <- extractioncost <- price <- avail <- basin.id <- demand <- depletion <- runoff <- accessible <- x <- . <- accessible_runoff <- deficit <- years <- deficit_total <- subresource <- NULL # silence package check. all_data <- list(...)[[1]] # Load required inputs GCAM_region_names <- get_data(all_data, "common/GCAM_region_names") iso_GCAM_regID <- get_data(all_data, "common/iso_GCAM_regID") basin_to_country_mapping <- get_data(all_data, "water/basin_to_country_mapping", strip_attributes = TRUE) basin_ids <- get_data(all_data, "water/basin_ID") water_mapping_R_GLU_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_GLU_B_W_Ws_share", strip_attributes = TRUE) water_mapping_R_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_B_W_Ws_share", strip_attributes = TRUE) L100.runoff_max_bm3 <- get_data(all_data, "L100.runoff_max_bm3") L100.runoff_accessible <- get_data(all_data, "L100.runoff_accessible") L101.groundwater_depletion_bm3 <- get_data(all_data, "L101.groundwater_depletion_bm3") L101.DepRsrcCurves_ground_uniform_bm3 <- get_data(all_data, "L101.groundwater_grades_uniform_bm3") L101.groundwater_grades_constrained_bm3 <- get_data(all_data, "L101.groundwater_grades_constrained_bm3") basin_water_demand_1990_2015 <- get_data(all_data, "water/basin_water_demand_1990_2015") L103.water_mapping_R_GLU_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_GLU_B_W_Ws_share", strip_attributes = TRUE) L103.water_mapping_R_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_B_W_Ws_share", strip_attributes = TRUE) L101.groundwater_grades_constrained_bm3 <- get_data(all_data, "L101.groundwater_grades_constrained_bm3") # Basin_to_country_mapping table include only one set of distinct basins # that are mapped to a single country with largest basin share. # Assign GCAM region name to each basin. # Basin with overlapping GCAM regions assign to region with largest basin area. basin_to_country_mapping %>% rename(iso = ISO) %>% mutate(iso = tolower(iso)) %>% left_join(iso_GCAM_regID, by = "iso") %>% # ^^ non-restrictive join required (NA values generated for unmapped iso) # basins without gcam region mapping excluded (right join) # Antarctica not assigned right_join(GCAM_region_names, by = "GCAM_region_ID") %>% rename(basin_id = GCAM_basin_ID, basin_name = Basin_name) %>% select(GCAM_region_ID, region, basin_id) %>% arrange(region) -> RegionBasinHome # identify basins without gcam region mapping (anti_join) basin_to_country_mapping %>% rename(iso = ISO) %>% mutate(iso = tolower(iso)) %>% left_join(iso_GCAM_regID, by = "iso") %>% #not all iso included in basin mapping # ^^ non-restrictive join required (NA values generated for unmapped iso) anti_join(GCAM_region_names, by = "GCAM_region_ID") -> BasinNoRegion # create full set of region/basin combinations # some basins overlap multiple regions # Use left join to ensure only those basins in use by GCAM regions are included bind_rows(water_mapping_R_GLU_B_W_Ws_share %>% rename(basin_id = GLU), water_mapping_R_B_W_Ws_share) %>% select(GCAM_region_ID, basin_id, water_type) %>% filter(water_type == "water withdrawals") %>% distinct() %>% left_join(basin_ids, by = "basin_id") %>% # ^^ non-restrictive join required (NA values generated for unused basins) left_join_error_no_match(GCAM_region_names, by = "GCAM_region_ID") %>% mutate(water_type = "water withdrawals", resource = paste(basin_name, water_type, sep="_")) %>% arrange(region, basin_name) -> L201.region_basin # create unique set of region/basin combination with # basin contained by home region (region with largest basin area) L201.region_basin %>% inner_join(RegionBasinHome, by = c("basin_id","GCAM_region_ID","region")) %>% arrange(region, basin_name) -> L201.region_basin_home # create the delete for the unlimited resource markets for withdrawals L201.region_basin %>% arrange(region, basin_name) %>% rename(unlimited.resource = resource) %>% select(LEVEL2_DATA_NAMES[["DeleteUnlimitRsrc"]]) -> L201.DeleteUnlimitRsrc # create resource markets for water withdrawals with # unique or shared region/basin market L201.region_basin %>% arrange(region) %>% mutate(output.unit = water.WATER_UNITS_QUANTITY, price.unit = water.WATER_UNITS_PRICE, market = basin_name) %>% arrange(region, resource) %>% select(LEVEL2_DATA_NAMES[["Rsrc"]]) -> L201.Rsrc # read in base year price L201.Rsrc %>% mutate(year = MODEL_YEARS[1], price = water.DEFAULT_BASEYEAR_WATER_PRICE ) %>% arrange(region, resource) %>% select(LEVEL2_DATA_NAMES[["RsrcPrice"]]) -> L201.RsrcPrice # Read in annual water runoff supply for each basin # Use L201.region_basin_home to assign actual resource to # home region. # Runoff table includes basins not in use by GCAM regions. L201.region_basin_home %>% left_join(L100.runoff_max_bm3, by = "basin_id") %>% #only basins with withdrawals are used # ^^ non-restrictive join required (NA values generated for unused basins) mutate(sub.renewable.resource = "runoff", renewresource = resource, maxSubResource = round(runoff_max, water.DIGITS_GROUND_WATER_RSC)) %>% arrange(region, renewresource, year) %>% select(LEVEL2_DATA_NAMES[["GrdRenewRsrcMaxNoFillOut"]]) -> L201.GrdRenewRsrcMax_runoff # ==========================================================# # CREATE INPUTS FOR THE UNCALIBRATED WATER SUPPLY XML # basin accessible fraction of total runoff L201.region_basin_home %>% #only basins with withdrawals are used left_join(L100.runoff_accessible, by = "basin_id") -> # ^^ non-restrictive join required (NA values generated for unused basins) access_fraction_uncalibrated access_fraction_uncalibrated %>% mutate(grade = "grade2", sub.renewable.resource = "runoff") %>% rename(available = access_fraction) %>% complete(grade = c("grade1", "grade2", "grade3"), nesting(region, resource, sub.renewable.resource)) %>% mutate(available = case_when( #accessible fraction grade == "grade1" ~ 0, #none available grade == "grade2" ~ round(available, water.DIGITS_RENEW_WATER), grade == "grade3" ~ 1 #100% available ) ) %>% mutate(extractioncost = case_when( grade == "grade1" ~ water.RENEW.COST.GRADE1, grade == "grade2" ~ water.RENEW.COST.GRADE2, grade == "grade3" ~ water.RENEW.COST.GRADE3 ) ) %>% select(region, resource, sub.renewable.resource, grade, available, extractioncost) %>% arrange(region, resource, grade) -> L201.RenewRsrcCurves_uncalibrated # depleteable ground water supply curve for uniform resources L201.region_basin_home %>% # not all basin groundwater curves are in used left_join(L101.DepRsrcCurves_ground_uniform_bm3, by = c("basin_id" = "basin.id")) %>% # ^^ non-restrictive join required (NA values generated for unused basins) mutate(subresource = "groundwater") %>% arrange(region, resource, price) %>% mutate(extractioncost = round(price, water.DIGITS_GROUND_WATER), available = round(avail, water.DIGITS_GROUND_WATER)) %>% select(LEVEL2_DATA_NAMES[["RsrcCurves"]]) -> L201.DepRsrcCurves_ground_uniform # ==========================================================# # CREATE INPUTS FOR THE CALIBRATED WATER SUPPLY XML # Calibration procedure (this will be deprecated when the water supply is switched to logits) # Step 1: For basins with groundwater depletion... get historical (2000 - 2015) runoff, demand, and groundwater depletion ## We use the means across years for runoff; groundwater depletion is an annual value assumed invariant over time; ## We use the max of the estimated demands over all model base years (assumes that all of these historical withdrawals were "conventional") # Step 2: Assume no unconventional water withdrawals; back-calculate withdrawn runoff fraction using demand and groundwater depletion # Step 3: Combine with uncalibrated accessible water (used for basins where there is no groundwater depletion historically) # Step 4: Expand out for smooth resource curve (helps with GCAM solve) # Step 5: Determine historical grade groundwater based to be allowed and combine with depletion curves # Step 1 basin_water_demand_1990_2015 %>% filter(year %in% water.GW_DEPLETION_HISTORICAL) %>% arrange(basin.id, year) %>% group_by(basin.id) %>% summarise(demand = max(demand)) %>% ungroup() -> basin_water_demand_2005_2015 L100.runoff_max_bm3 %>% filter(year %in% water.GW_DEPLETION_HISTORICAL) %>% group_by(basin_id) %>% summarise(runoff = mean(runoff_max)) %>% ungroup() -> basin_max_runoff_2000_2010 # not all basin runoff water are in used # ^^ non-restrictive join required (NA values generated for unused basins) left_join(basin_water_demand_2005_2015, basin_max_runoff_2000_2010, by = c("basin.id" = "basin_id")) -> demand_runoff_cal # Step 2 L101.groundwater_depletion_bm3 %>% right_join(demand_runoff_cal, by = "basin.id") %>% mutate(accessible = (demand - depletion) / runoff, accessible = if_else(accessible < 0, NA_real_, accessible)) %>% select(basin_id = basin.id, accessible) -> accessible_water # Step 3 L201.region_basin_home %>% # not all basin runoff water are in used left_join(accessible_water, by= "basin_id") %>% # ^^ non-restrictive join required (NA values generated for unused basins) select(resource, accessible) %>% right_join(L201.RenewRsrcCurves_uncalibrated, by = "resource") %>% mutate(available = case_when( grade == "grade2" & is.na(accessible) == TRUE ~ available, grade == "grade2" & is.na(accessible) == FALSE ~ accessible, grade == "grade1" | grade == "grade3" ~ available )) %>% select(-accessible) %>% group_by(resource) %>% mutate(x = cumsum(available), available = if_else(x >= 2, x, available)) %>% select(-x) %>% ungroup() -> accessible_water_unsmoothed # Step 4 # make function to expand out the 3-point resource curve to an interpolated 20-point curve get_smooth_renewresource <- function(resource, data){ x <- data[data$resource == resource, ] av <- x$available ex <- x$extractioncost x_region <- x$region[1] #starting with only 3 points rnw_spline <- spline(av, ex, method = "hyman", xout = c( seq(av[1], av[2], length.out = 10), seq(av[2], av[3], length.out = 11))[-10]) tibble(region = x_region, resource = resource, sub.renewable.resource = "runoff", grade = paste0("grade", 1:20), available = round(rnw_spline$x, water.DIGITS_GROUND_WATER), extractioncost = round(rnw_spline$y, water.DIGITS_GROUND_WATER)) } # apply smoothing across all basins # filter out Arctic Ocean basin since no water demand accessible_water_unsmoothed %>% filter(!grepl("Arctic Ocean", resource)) %>% lapply(unique(pull(., resource)), get_smooth_renewresource, .) %>% bind_rows(filter(accessible_water_unsmoothed, grepl("Arctic Ocean", resource))) -> L201.RenewRsrcCurves_calib # Step 5 L100.runoff_max_bm3 %>% filter(year %in% water.RUNOFF_HISTORICAL) %>% group_by(basin_id) %>% summarise(runoff = mean(runoff_max)) %>% ungroup() %>% #keep only basins in use filter(basin_id %in% L201.region_basin_home$basin_id) -> runoff_mean_hist access_fraction_uncalibrated %>% select(basin_id, access_fraction) %>% left_join(accessible_water, by = "basin_id") %>% # ^^ non-restrictive join required (NA values generated for unused basins) left_join_error_no_match(runoff_mean_hist, by = "basin_id") %>% mutate(accessible = if_else(is.na(accessible), access_fraction, accessible), accessible_runoff = runoff * accessible) %>% # ^^ get runoff volumes available select(basin.id = basin_id, accessible_runoff) %>% right_join(basin_water_demand_1990_2015, by = "basin.id") %>% # ^^ join the historical demand mutate(deficit = demand - accessible_runoff, deficit = if_else(deficit <=0, 0, deficit)) %>% filter(year %in% MODEL_BASE_YEARS) %>% # ^^ determine how much water needs to be met by groundwater depletion left_join_error_no_match(tibble(year = MODEL_BASE_YEARS[MODEL_BASE_YEARS >= water.GW_DEPLETION_BASE_YEAR], years = diff(MODEL_BASE_YEARS)), by = "year") %>% mutate(deficit_total = deficit * years) %>% group_by(basin.id) %>% summarise(available = sum(deficit_total) * water.GW_HIST_MULTIPLIER) %>% ungroup() %>% filter(available > 0) %>% mutate(grade = "grade hist", price = water.DEFAULT_BASEYEAR_WATER_PRICE) -> groundwater_hist bind_rows( L201.region_basin_home %>% left_join(L101.groundwater_grades_constrained_bm3, by = c("basin_id" = "basin.id")), # ^^ non-restrictive join required (NA values generated for unused basins) L201.region_basin_home %>% left_join(groundwater_hist, by = c("basin_id" = "basin.id")) %>% # ^^ non-restrictive join required (NA values generated for unused basins) filter(!is.na(grade))) %>% rename(extractioncost = price) %>% mutate(subresource = "groundwater", available = round(available, water.DIGITS_GROUND_WATER_RSC), extractioncost = round(extractioncost, water.DIGITS_GROUND_WATER_RSC)) %>% select(LEVEL2_DATA_NAMES[["RsrcCurves"]]) %>% arrange(region, resource, extractioncost) -> L201.DepRsrcCurves_ground # problem with original groundwater constrained input file # contains extra 0 available grade and thus creastes discontinuous supply curve L201.DepRsrcCurves_ground %>% filter(grade == "grade24" & available == 0) -> L201.DepRsrcCurves_ground_last # drop grades with 0 availability in order to avoid having "flat" portions of the supply curve, where changes in # price do not change the quantity supplied. keep the grade1 points even where availability is zero in order to # ensure that the "grade hist" prices remain at desired levels. bind_rows( L201.DepRsrcCurves_ground %>% filter(grade == "grade1" | available > 0), L201.DepRsrcCurves_ground_last ) %>% arrange(region, resource, extractioncost) -> L201.DepRsrcCurves_ground # Remove any discontinuities in the supply curve (0 available between 2 grades) at the first grade by assigning # a small amount of water min_grade1_available <- min(L201.DepRsrcCurves_ground$available[L201.DepRsrcCurves_ground$grade == "grade1" & L201.DepRsrcCurves_ground$available > 0]) L201.DepRsrcCurves_ground %>% group_by(region, resource, subresource) %>% mutate(available = if_else(grade == "grade1" & available == 0, min_grade1_available, available)) %>% ungroup() -> L201.DepRsrcCurves_ground # Create an empty technology for all water resources and subresources. # Include a share weight of 1 to facilatate creating a technology. # Create technology for renewable freshwater and depletable groundwater subresource L201.RenewRsrcCurves_calib %>% distinct(region, resource, sub.renewable.resource) %>% repeat_add_columns(tibble(year = MODEL_YEARS)) %>% mutate(technology = sub.renewable.resource, share.weight = 1.0) %>% rename(subresource = sub.renewable.resource) %>% select(LEVEL2_DATA_NAMES[["ResTechShrwt"]]) -> L201.RenewRsrcTechShrwt L201.DepRsrcCurves_ground %>% distinct(region, resource, subresource) %>% repeat_add_columns(tibble(year = MODEL_YEARS)) %>% mutate(technology = subresource, share.weight = 1.0) %>% select(LEVEL2_DATA_NAMES[["ResTechShrwt"]]) -> L201.RsrcTechShrwt # =================================================== # Produce outputs L201.DeleteUnlimitRsrc %>% add_title("Delete Unlimited Resources") %>% add_units("NA") %>% add_comments("") %>% add_legacy_name("L201.DeleteUnlimitRsrc") %>% add_precursors("water/basin_ID", "common/GCAM_region_names", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share") -> L201.DeleteUnlimitRsrc L201.Rsrc %>% add_title("Resource markets for water withdrawals") %>% add_units("NA") %>% add_comments("") %>% add_legacy_name("L201.Rsrc") %>% add_precursors("water/basin_ID", "water/basin_to_country_mapping", "common/GCAM_region_names", "common/iso_GCAM_regID", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share") -> L201.Rsrc L201.RsrcPrice %>% add_title("Base year price") %>% add_units("1975$") %>% add_comments("") %>% add_legacy_name("L201.RsrcPrice") %>% add_precursors("water/basin_ID", "water/basin_to_country_mapping", "common/GCAM_region_names", "common/iso_GCAM_regID", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share") -> L201.RsrcPrice L201.RenewRsrcCurves_uncalibrated %>% add_title("Uncalibrated renewable resource curves") %>% add_units("bm^3, 1975$") %>% add_comments("") %>% add_legacy_name("L201.RenewRsrcCurves_uncalibrated") %>% add_precursors("L100.runoff_accessible") -> L201.RenewRsrcCurves_uncalibrated L201.GrdRenewRsrcMax_runoff %>% add_title("Maximum runoff") %>% add_units("bm^3, 1975$") %>% add_comments("Upper limit of water supply; RenewRsrc is applied to this to get renewable water") %>% add_legacy_name("L201.GrdRenewRsrcMax_runoff") %>% add_precursors("L100.runoff_max_bm3") -> L201.GrdRenewRsrcMax_runoff L201.DepRsrcCurves_ground_uniform %>% add_title("Uniform depletable groundwater curves") %>% add_units("bm^3, 1975$") %>% add_comments("") %>% add_legacy_name("L201.DepRsrcCurves_ground_uniform") %>% add_precursors("L101.groundwater_grades_uniform_bm3") -> L201.DepRsrcCurves_ground_uniform L201.RenewRsrcCurves_calib %>% add_title("Calibrated renewable water curves") %>% add_units("bm^3, 1975$") %>% add_comments("Calibrated to ensure observed groundwater is taken in calibration years") %>% add_legacy_name("L201.RenewRsrcCurves_calib") %>% add_precursors("water/basin_water_demand_1990_2015", "L101.groundwater_depletion_bm3", "L100.runoff_accessible", "L100.runoff_max_bm3") -> L201.RenewRsrcCurves_calib L201.DepRsrcCurves_ground %>% add_title("Depletable groundwater curves") %>% add_units("bm^3, 1975$") %>% add_comments("Includes historical grades") %>% add_legacy_name("L201.DepRsrcCurves_ground") %>% add_precursors("water/basin_water_demand_1990_2015", "L101.groundwater_grades_constrained_bm3") -> L201.DepRsrcCurves_ground L201.RenewRsrcTechShrwt %>% add_title("Water renewable resource technologies") %>% add_units("NA") %>% add_comments("share weight is 1") %>% add_precursors("L201.RenewRsrcCurves_calib") -> L201.RenewRsrcTechShrwt L201.RsrcTechShrwt %>% add_title("Water depletable resource technologies") %>% add_units("NA") %>% add_comments("share weight is 1") %>% add_precursors("L201.DepRsrcCurves_ground") -> L201.RsrcTechShrwt return_data(L201.DeleteUnlimitRsrc, L201.Rsrc, L201.RsrcPrice, L201.RenewRsrcCurves_uncalibrated, L201.GrdRenewRsrcMax_runoff, L201.DepRsrcCurves_ground_uniform, L201.RenewRsrcCurves_calib, L201.DepRsrcCurves_ground, L201.RenewRsrcTechShrwt, L201.RsrcTechShrwt) } else { stop("Unknown command") } }
/R/zchunk_L201.water_resources_constrained.R
permissive
Liyang-Guo/gcamdata
R
false
false
24,150
r
# Copyright 2019 Battelle Memorial Institute; see the LICENSE file. #' module_water_L201.water_resources_constrained #' #' Constrained surface and groudwater. #' #' @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{L201.RenewRsrcCurves_calib}, #' \code{201.GrdRenewRsrcMax_runoff}, \code{L201.DepRsrcCurves_ground}. The corresponding file in the #' original data system was \code{L102.water_supply_unlimited.R} (water level1). #' @details Genereates water resource input files for region + basin which includes runoff and groundwater. #' @importFrom assertthat assert_that #' @importFrom dplyr anti_join case_when distinct filter if_else inner_join mutate pull right_join select #' @importFrom tidyr complete nesting #' @importFrom stats spline #' @author ST Oct 2018 module_water_L201.water_resources_constrained <- function(command, ...) { if(command == driver.DECLARE_INPUTS) { return(c(FILE = "water/basin_ID", FILE = "water/basin_to_country_mapping", FILE = "common/GCAM_region_names", FILE = "common/iso_GCAM_regID", FILE = "water/basin_water_demand_1990_2015", "L100.runoff_accessible", "L100.runoff_max_bm3", "L101.groundwater_depletion_bm3", "L101.groundwater_grades_constrained_bm3", "L101.groundwater_grades_uniform_bm3", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share")) } else if(command == driver.DECLARE_OUTPUTS) { return(c("L201.DeleteUnlimitRsrc", "L201.Rsrc", "L201.RsrcPrice", "L201.RenewRsrcCurves_uncalibrated", "L201.GrdRenewRsrcMax_runoff", "L201.DepRsrcCurves_ground_uniform", "L201.RenewRsrcCurves_calib", "L201.DepRsrcCurves_ground", "L201.RenewRsrcTechShrwt", "L201.RsrcTechShrwt")) } else if(command == driver.MAKE) { region <- ISO <- iso <- GCAM_basin_ID <- Basin_name <- GCAM_region_ID <- basin_id <- GLU <- water_type <- basin_name <- resource <- runoff_max <- renewresource <- year <- access_fraction <- sub.renewable.resource <- grade <- available <- extractioncost <- price <- avail <- basin.id <- demand <- depletion <- runoff <- accessible <- x <- . <- accessible_runoff <- deficit <- years <- deficit_total <- subresource <- NULL # silence package check. all_data <- list(...)[[1]] # Load required inputs GCAM_region_names <- get_data(all_data, "common/GCAM_region_names") iso_GCAM_regID <- get_data(all_data, "common/iso_GCAM_regID") basin_to_country_mapping <- get_data(all_data, "water/basin_to_country_mapping", strip_attributes = TRUE) basin_ids <- get_data(all_data, "water/basin_ID") water_mapping_R_GLU_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_GLU_B_W_Ws_share", strip_attributes = TRUE) water_mapping_R_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_B_W_Ws_share", strip_attributes = TRUE) L100.runoff_max_bm3 <- get_data(all_data, "L100.runoff_max_bm3") L100.runoff_accessible <- get_data(all_data, "L100.runoff_accessible") L101.groundwater_depletion_bm3 <- get_data(all_data, "L101.groundwater_depletion_bm3") L101.DepRsrcCurves_ground_uniform_bm3 <- get_data(all_data, "L101.groundwater_grades_uniform_bm3") L101.groundwater_grades_constrained_bm3 <- get_data(all_data, "L101.groundwater_grades_constrained_bm3") basin_water_demand_1990_2015 <- get_data(all_data, "water/basin_water_demand_1990_2015") L103.water_mapping_R_GLU_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_GLU_B_W_Ws_share", strip_attributes = TRUE) L103.water_mapping_R_B_W_Ws_share <- get_data(all_data, "L103.water_mapping_R_B_W_Ws_share", strip_attributes = TRUE) L101.groundwater_grades_constrained_bm3 <- get_data(all_data, "L101.groundwater_grades_constrained_bm3") # Basin_to_country_mapping table include only one set of distinct basins # that are mapped to a single country with largest basin share. # Assign GCAM region name to each basin. # Basin with overlapping GCAM regions assign to region with largest basin area. basin_to_country_mapping %>% rename(iso = ISO) %>% mutate(iso = tolower(iso)) %>% left_join(iso_GCAM_regID, by = "iso") %>% # ^^ non-restrictive join required (NA values generated for unmapped iso) # basins without gcam region mapping excluded (right join) # Antarctica not assigned right_join(GCAM_region_names, by = "GCAM_region_ID") %>% rename(basin_id = GCAM_basin_ID, basin_name = Basin_name) %>% select(GCAM_region_ID, region, basin_id) %>% arrange(region) -> RegionBasinHome # identify basins without gcam region mapping (anti_join) basin_to_country_mapping %>% rename(iso = ISO) %>% mutate(iso = tolower(iso)) %>% left_join(iso_GCAM_regID, by = "iso") %>% #not all iso included in basin mapping # ^^ non-restrictive join required (NA values generated for unmapped iso) anti_join(GCAM_region_names, by = "GCAM_region_ID") -> BasinNoRegion # create full set of region/basin combinations # some basins overlap multiple regions # Use left join to ensure only those basins in use by GCAM regions are included bind_rows(water_mapping_R_GLU_B_W_Ws_share %>% rename(basin_id = GLU), water_mapping_R_B_W_Ws_share) %>% select(GCAM_region_ID, basin_id, water_type) %>% filter(water_type == "water withdrawals") %>% distinct() %>% left_join(basin_ids, by = "basin_id") %>% # ^^ non-restrictive join required (NA values generated for unused basins) left_join_error_no_match(GCAM_region_names, by = "GCAM_region_ID") %>% mutate(water_type = "water withdrawals", resource = paste(basin_name, water_type, sep="_")) %>% arrange(region, basin_name) -> L201.region_basin # create unique set of region/basin combination with # basin contained by home region (region with largest basin area) L201.region_basin %>% inner_join(RegionBasinHome, by = c("basin_id","GCAM_region_ID","region")) %>% arrange(region, basin_name) -> L201.region_basin_home # create the delete for the unlimited resource markets for withdrawals L201.region_basin %>% arrange(region, basin_name) %>% rename(unlimited.resource = resource) %>% select(LEVEL2_DATA_NAMES[["DeleteUnlimitRsrc"]]) -> L201.DeleteUnlimitRsrc # create resource markets for water withdrawals with # unique or shared region/basin market L201.region_basin %>% arrange(region) %>% mutate(output.unit = water.WATER_UNITS_QUANTITY, price.unit = water.WATER_UNITS_PRICE, market = basin_name) %>% arrange(region, resource) %>% select(LEVEL2_DATA_NAMES[["Rsrc"]]) -> L201.Rsrc # read in base year price L201.Rsrc %>% mutate(year = MODEL_YEARS[1], price = water.DEFAULT_BASEYEAR_WATER_PRICE ) %>% arrange(region, resource) %>% select(LEVEL2_DATA_NAMES[["RsrcPrice"]]) -> L201.RsrcPrice # Read in annual water runoff supply for each basin # Use L201.region_basin_home to assign actual resource to # home region. # Runoff table includes basins not in use by GCAM regions. L201.region_basin_home %>% left_join(L100.runoff_max_bm3, by = "basin_id") %>% #only basins with withdrawals are used # ^^ non-restrictive join required (NA values generated for unused basins) mutate(sub.renewable.resource = "runoff", renewresource = resource, maxSubResource = round(runoff_max, water.DIGITS_GROUND_WATER_RSC)) %>% arrange(region, renewresource, year) %>% select(LEVEL2_DATA_NAMES[["GrdRenewRsrcMaxNoFillOut"]]) -> L201.GrdRenewRsrcMax_runoff # ==========================================================# # CREATE INPUTS FOR THE UNCALIBRATED WATER SUPPLY XML # basin accessible fraction of total runoff L201.region_basin_home %>% #only basins with withdrawals are used left_join(L100.runoff_accessible, by = "basin_id") -> # ^^ non-restrictive join required (NA values generated for unused basins) access_fraction_uncalibrated access_fraction_uncalibrated %>% mutate(grade = "grade2", sub.renewable.resource = "runoff") %>% rename(available = access_fraction) %>% complete(grade = c("grade1", "grade2", "grade3"), nesting(region, resource, sub.renewable.resource)) %>% mutate(available = case_when( #accessible fraction grade == "grade1" ~ 0, #none available grade == "grade2" ~ round(available, water.DIGITS_RENEW_WATER), grade == "grade3" ~ 1 #100% available ) ) %>% mutate(extractioncost = case_when( grade == "grade1" ~ water.RENEW.COST.GRADE1, grade == "grade2" ~ water.RENEW.COST.GRADE2, grade == "grade3" ~ water.RENEW.COST.GRADE3 ) ) %>% select(region, resource, sub.renewable.resource, grade, available, extractioncost) %>% arrange(region, resource, grade) -> L201.RenewRsrcCurves_uncalibrated # depleteable ground water supply curve for uniform resources L201.region_basin_home %>% # not all basin groundwater curves are in used left_join(L101.DepRsrcCurves_ground_uniform_bm3, by = c("basin_id" = "basin.id")) %>% # ^^ non-restrictive join required (NA values generated for unused basins) mutate(subresource = "groundwater") %>% arrange(region, resource, price) %>% mutate(extractioncost = round(price, water.DIGITS_GROUND_WATER), available = round(avail, water.DIGITS_GROUND_WATER)) %>% select(LEVEL2_DATA_NAMES[["RsrcCurves"]]) -> L201.DepRsrcCurves_ground_uniform # ==========================================================# # CREATE INPUTS FOR THE CALIBRATED WATER SUPPLY XML # Calibration procedure (this will be deprecated when the water supply is switched to logits) # Step 1: For basins with groundwater depletion... get historical (2000 - 2015) runoff, demand, and groundwater depletion ## We use the means across years for runoff; groundwater depletion is an annual value assumed invariant over time; ## We use the max of the estimated demands over all model base years (assumes that all of these historical withdrawals were "conventional") # Step 2: Assume no unconventional water withdrawals; back-calculate withdrawn runoff fraction using demand and groundwater depletion # Step 3: Combine with uncalibrated accessible water (used for basins where there is no groundwater depletion historically) # Step 4: Expand out for smooth resource curve (helps with GCAM solve) # Step 5: Determine historical grade groundwater based to be allowed and combine with depletion curves # Step 1 basin_water_demand_1990_2015 %>% filter(year %in% water.GW_DEPLETION_HISTORICAL) %>% arrange(basin.id, year) %>% group_by(basin.id) %>% summarise(demand = max(demand)) %>% ungroup() -> basin_water_demand_2005_2015 L100.runoff_max_bm3 %>% filter(year %in% water.GW_DEPLETION_HISTORICAL) %>% group_by(basin_id) %>% summarise(runoff = mean(runoff_max)) %>% ungroup() -> basin_max_runoff_2000_2010 # not all basin runoff water are in used # ^^ non-restrictive join required (NA values generated for unused basins) left_join(basin_water_demand_2005_2015, basin_max_runoff_2000_2010, by = c("basin.id" = "basin_id")) -> demand_runoff_cal # Step 2 L101.groundwater_depletion_bm3 %>% right_join(demand_runoff_cal, by = "basin.id") %>% mutate(accessible = (demand - depletion) / runoff, accessible = if_else(accessible < 0, NA_real_, accessible)) %>% select(basin_id = basin.id, accessible) -> accessible_water # Step 3 L201.region_basin_home %>% # not all basin runoff water are in used left_join(accessible_water, by= "basin_id") %>% # ^^ non-restrictive join required (NA values generated for unused basins) select(resource, accessible) %>% right_join(L201.RenewRsrcCurves_uncalibrated, by = "resource") %>% mutate(available = case_when( grade == "grade2" & is.na(accessible) == TRUE ~ available, grade == "grade2" & is.na(accessible) == FALSE ~ accessible, grade == "grade1" | grade == "grade3" ~ available )) %>% select(-accessible) %>% group_by(resource) %>% mutate(x = cumsum(available), available = if_else(x >= 2, x, available)) %>% select(-x) %>% ungroup() -> accessible_water_unsmoothed # Step 4 # make function to expand out the 3-point resource curve to an interpolated 20-point curve get_smooth_renewresource <- function(resource, data){ x <- data[data$resource == resource, ] av <- x$available ex <- x$extractioncost x_region <- x$region[1] #starting with only 3 points rnw_spline <- spline(av, ex, method = "hyman", xout = c( seq(av[1], av[2], length.out = 10), seq(av[2], av[3], length.out = 11))[-10]) tibble(region = x_region, resource = resource, sub.renewable.resource = "runoff", grade = paste0("grade", 1:20), available = round(rnw_spline$x, water.DIGITS_GROUND_WATER), extractioncost = round(rnw_spline$y, water.DIGITS_GROUND_WATER)) } # apply smoothing across all basins # filter out Arctic Ocean basin since no water demand accessible_water_unsmoothed %>% filter(!grepl("Arctic Ocean", resource)) %>% lapply(unique(pull(., resource)), get_smooth_renewresource, .) %>% bind_rows(filter(accessible_water_unsmoothed, grepl("Arctic Ocean", resource))) -> L201.RenewRsrcCurves_calib # Step 5 L100.runoff_max_bm3 %>% filter(year %in% water.RUNOFF_HISTORICAL) %>% group_by(basin_id) %>% summarise(runoff = mean(runoff_max)) %>% ungroup() %>% #keep only basins in use filter(basin_id %in% L201.region_basin_home$basin_id) -> runoff_mean_hist access_fraction_uncalibrated %>% select(basin_id, access_fraction) %>% left_join(accessible_water, by = "basin_id") %>% # ^^ non-restrictive join required (NA values generated for unused basins) left_join_error_no_match(runoff_mean_hist, by = "basin_id") %>% mutate(accessible = if_else(is.na(accessible), access_fraction, accessible), accessible_runoff = runoff * accessible) %>% # ^^ get runoff volumes available select(basin.id = basin_id, accessible_runoff) %>% right_join(basin_water_demand_1990_2015, by = "basin.id") %>% # ^^ join the historical demand mutate(deficit = demand - accessible_runoff, deficit = if_else(deficit <=0, 0, deficit)) %>% filter(year %in% MODEL_BASE_YEARS) %>% # ^^ determine how much water needs to be met by groundwater depletion left_join_error_no_match(tibble(year = MODEL_BASE_YEARS[MODEL_BASE_YEARS >= water.GW_DEPLETION_BASE_YEAR], years = diff(MODEL_BASE_YEARS)), by = "year") %>% mutate(deficit_total = deficit * years) %>% group_by(basin.id) %>% summarise(available = sum(deficit_total) * water.GW_HIST_MULTIPLIER) %>% ungroup() %>% filter(available > 0) %>% mutate(grade = "grade hist", price = water.DEFAULT_BASEYEAR_WATER_PRICE) -> groundwater_hist bind_rows( L201.region_basin_home %>% left_join(L101.groundwater_grades_constrained_bm3, by = c("basin_id" = "basin.id")), # ^^ non-restrictive join required (NA values generated for unused basins) L201.region_basin_home %>% left_join(groundwater_hist, by = c("basin_id" = "basin.id")) %>% # ^^ non-restrictive join required (NA values generated for unused basins) filter(!is.na(grade))) %>% rename(extractioncost = price) %>% mutate(subresource = "groundwater", available = round(available, water.DIGITS_GROUND_WATER_RSC), extractioncost = round(extractioncost, water.DIGITS_GROUND_WATER_RSC)) %>% select(LEVEL2_DATA_NAMES[["RsrcCurves"]]) %>% arrange(region, resource, extractioncost) -> L201.DepRsrcCurves_ground # problem with original groundwater constrained input file # contains extra 0 available grade and thus creastes discontinuous supply curve L201.DepRsrcCurves_ground %>% filter(grade == "grade24" & available == 0) -> L201.DepRsrcCurves_ground_last # drop grades with 0 availability in order to avoid having "flat" portions of the supply curve, where changes in # price do not change the quantity supplied. keep the grade1 points even where availability is zero in order to # ensure that the "grade hist" prices remain at desired levels. bind_rows( L201.DepRsrcCurves_ground %>% filter(grade == "grade1" | available > 0), L201.DepRsrcCurves_ground_last ) %>% arrange(region, resource, extractioncost) -> L201.DepRsrcCurves_ground # Remove any discontinuities in the supply curve (0 available between 2 grades) at the first grade by assigning # a small amount of water min_grade1_available <- min(L201.DepRsrcCurves_ground$available[L201.DepRsrcCurves_ground$grade == "grade1" & L201.DepRsrcCurves_ground$available > 0]) L201.DepRsrcCurves_ground %>% group_by(region, resource, subresource) %>% mutate(available = if_else(grade == "grade1" & available == 0, min_grade1_available, available)) %>% ungroup() -> L201.DepRsrcCurves_ground # Create an empty technology for all water resources and subresources. # Include a share weight of 1 to facilatate creating a technology. # Create technology for renewable freshwater and depletable groundwater subresource L201.RenewRsrcCurves_calib %>% distinct(region, resource, sub.renewable.resource) %>% repeat_add_columns(tibble(year = MODEL_YEARS)) %>% mutate(technology = sub.renewable.resource, share.weight = 1.0) %>% rename(subresource = sub.renewable.resource) %>% select(LEVEL2_DATA_NAMES[["ResTechShrwt"]]) -> L201.RenewRsrcTechShrwt L201.DepRsrcCurves_ground %>% distinct(region, resource, subresource) %>% repeat_add_columns(tibble(year = MODEL_YEARS)) %>% mutate(technology = subresource, share.weight = 1.0) %>% select(LEVEL2_DATA_NAMES[["ResTechShrwt"]]) -> L201.RsrcTechShrwt # =================================================== # Produce outputs L201.DeleteUnlimitRsrc %>% add_title("Delete Unlimited Resources") %>% add_units("NA") %>% add_comments("") %>% add_legacy_name("L201.DeleteUnlimitRsrc") %>% add_precursors("water/basin_ID", "common/GCAM_region_names", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share") -> L201.DeleteUnlimitRsrc L201.Rsrc %>% add_title("Resource markets for water withdrawals") %>% add_units("NA") %>% add_comments("") %>% add_legacy_name("L201.Rsrc") %>% add_precursors("water/basin_ID", "water/basin_to_country_mapping", "common/GCAM_region_names", "common/iso_GCAM_regID", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share") -> L201.Rsrc L201.RsrcPrice %>% add_title("Base year price") %>% add_units("1975$") %>% add_comments("") %>% add_legacy_name("L201.RsrcPrice") %>% add_precursors("water/basin_ID", "water/basin_to_country_mapping", "common/GCAM_region_names", "common/iso_GCAM_regID", "L103.water_mapping_R_GLU_B_W_Ws_share", "L103.water_mapping_R_B_W_Ws_share") -> L201.RsrcPrice L201.RenewRsrcCurves_uncalibrated %>% add_title("Uncalibrated renewable resource curves") %>% add_units("bm^3, 1975$") %>% add_comments("") %>% add_legacy_name("L201.RenewRsrcCurves_uncalibrated") %>% add_precursors("L100.runoff_accessible") -> L201.RenewRsrcCurves_uncalibrated L201.GrdRenewRsrcMax_runoff %>% add_title("Maximum runoff") %>% add_units("bm^3, 1975$") %>% add_comments("Upper limit of water supply; RenewRsrc is applied to this to get renewable water") %>% add_legacy_name("L201.GrdRenewRsrcMax_runoff") %>% add_precursors("L100.runoff_max_bm3") -> L201.GrdRenewRsrcMax_runoff L201.DepRsrcCurves_ground_uniform %>% add_title("Uniform depletable groundwater curves") %>% add_units("bm^3, 1975$") %>% add_comments("") %>% add_legacy_name("L201.DepRsrcCurves_ground_uniform") %>% add_precursors("L101.groundwater_grades_uniform_bm3") -> L201.DepRsrcCurves_ground_uniform L201.RenewRsrcCurves_calib %>% add_title("Calibrated renewable water curves") %>% add_units("bm^3, 1975$") %>% add_comments("Calibrated to ensure observed groundwater is taken in calibration years") %>% add_legacy_name("L201.RenewRsrcCurves_calib") %>% add_precursors("water/basin_water_demand_1990_2015", "L101.groundwater_depletion_bm3", "L100.runoff_accessible", "L100.runoff_max_bm3") -> L201.RenewRsrcCurves_calib L201.DepRsrcCurves_ground %>% add_title("Depletable groundwater curves") %>% add_units("bm^3, 1975$") %>% add_comments("Includes historical grades") %>% add_legacy_name("L201.DepRsrcCurves_ground") %>% add_precursors("water/basin_water_demand_1990_2015", "L101.groundwater_grades_constrained_bm3") -> L201.DepRsrcCurves_ground L201.RenewRsrcTechShrwt %>% add_title("Water renewable resource technologies") %>% add_units("NA") %>% add_comments("share weight is 1") %>% add_precursors("L201.RenewRsrcCurves_calib") -> L201.RenewRsrcTechShrwt L201.RsrcTechShrwt %>% add_title("Water depletable resource technologies") %>% add_units("NA") %>% add_comments("share weight is 1") %>% add_precursors("L201.DepRsrcCurves_ground") -> L201.RsrcTechShrwt return_data(L201.DeleteUnlimitRsrc, L201.Rsrc, L201.RsrcPrice, L201.RenewRsrcCurves_uncalibrated, L201.GrdRenewRsrcMax_runoff, L201.DepRsrcCurves_ground_uniform, L201.RenewRsrcCurves_calib, L201.DepRsrcCurves_ground, L201.RenewRsrcTechShrwt, L201.RsrcTechShrwt) } else { stop("Unknown command") } }
#' @rdname join #' @export full_join.disk.frame <- function(x, y, by=NULL, copy=FALSE, ..., outdir = tempfile("tmp_disk_frame_full_join"), merge_by_chunk_id = F, overwrite = T) { ##browser stopifnot("disk.frame" %in% class(x)) overwrite_check(outdir, overwrite) if("data.frame" %in% class(y)) { # full join cannot be support for y in data.frame ncx = nchunks(x) dy = shard(y, shardby = by, nchunks = ncx, overwrite = T) dx = hard_group_by(x, by = by, overwrite = T) return(full_join.disk.frame(dx, dy, by, copy=copy, outdir=outdir, merge_by_chunk_id = T)) } else if("disk.frame" %in% class(y)) { if(is.null(merge_by_chunk_id)) { stop("both x and y are disk.frames. You need to specify merge_by_chunk_id = TRUE or FALSE explicitly") } if(is.null(by)) { by <- intersect(names(x), names(y)) } ncx = nchunks(x) ncy = nchunks(y) if (merge_by_chunk_id == F) { warning("merge_by_chunk_id = FALSE. This will take significantly longer and the preparations needed are performed eagerly which may lead to poor performance. Consider making y a data.frame or set merge_by_chunk_id = TRUE for better performance.") x = hard_group_by(x, by, nchunks = max(ncy,ncx), overwrite = T) y = hard_group_by(y, by, nchunks = max(ncy,ncx), overwrite = T) return(full_join.disk.frame(x, y, by, copy = copy, outdir = outdir, merge_by_chunk_id = T, overwrite = overwrite)) } else if ((identical(shardkey(x)$shardkey, "") & identical(shardkey(y)$shardkey, "")) | identical(shardkey(x), shardkey(y))) { res = map_by_chunk_id(x, y, ~{ ##browser if(is.null(.y)) { return(.x) } else if (is.null(.x)) { return(.y) } full_join(.x, .y, by = by, copy = copy, ..., overwrite = overwrite) }, outdir = outdir) return(res) } else { # TODO if the shardkey are the same and only the shardchunks are different then just shard again on one of them is fine stop("merge_by_chunk_id is TRUE but shardkey(x) does NOT equal to shardkey(y). You may want to perform a hard_group_by() on both x and/or y or set merge_by_chunk_id = FALSE") } } }
/R/full_join.r
permissive
jingmouren/disk.frame
R
false
false
2,203
r
#' @rdname join #' @export full_join.disk.frame <- function(x, y, by=NULL, copy=FALSE, ..., outdir = tempfile("tmp_disk_frame_full_join"), merge_by_chunk_id = F, overwrite = T) { ##browser stopifnot("disk.frame" %in% class(x)) overwrite_check(outdir, overwrite) if("data.frame" %in% class(y)) { # full join cannot be support for y in data.frame ncx = nchunks(x) dy = shard(y, shardby = by, nchunks = ncx, overwrite = T) dx = hard_group_by(x, by = by, overwrite = T) return(full_join.disk.frame(dx, dy, by, copy=copy, outdir=outdir, merge_by_chunk_id = T)) } else if("disk.frame" %in% class(y)) { if(is.null(merge_by_chunk_id)) { stop("both x and y are disk.frames. You need to specify merge_by_chunk_id = TRUE or FALSE explicitly") } if(is.null(by)) { by <- intersect(names(x), names(y)) } ncx = nchunks(x) ncy = nchunks(y) if (merge_by_chunk_id == F) { warning("merge_by_chunk_id = FALSE. This will take significantly longer and the preparations needed are performed eagerly which may lead to poor performance. Consider making y a data.frame or set merge_by_chunk_id = TRUE for better performance.") x = hard_group_by(x, by, nchunks = max(ncy,ncx), overwrite = T) y = hard_group_by(y, by, nchunks = max(ncy,ncx), overwrite = T) return(full_join.disk.frame(x, y, by, copy = copy, outdir = outdir, merge_by_chunk_id = T, overwrite = overwrite)) } else if ((identical(shardkey(x)$shardkey, "") & identical(shardkey(y)$shardkey, "")) | identical(shardkey(x), shardkey(y))) { res = map_by_chunk_id(x, y, ~{ ##browser if(is.null(.y)) { return(.x) } else if (is.null(.x)) { return(.y) } full_join(.x, .y, by = by, copy = copy, ..., overwrite = overwrite) }, outdir = outdir) return(res) } else { # TODO if the shardkey are the same and only the shardchunks are different then just shard again on one of them is fine stop("merge_by_chunk_id is TRUE but shardkey(x) does NOT equal to shardkey(y). You may want to perform a hard_group_by() on both x and/or y or set merge_by_chunk_id = FALSE") } } }
#data setup source("./R/subscripts/centroid_assignment.R") rm(list = ls()) source("./R/subscripts/data_prep.R") rm(list = ls()) #run analyses source("./R/subscripts/spatial_stats.R") rm(list = ls()) source("./R/subscripts/get_sst_data.R") rm(list = ls()) source("./R/subscripts/get_binned_vals.R") rm(list = ls()) #figures source("./R/figures/spatial_stats.R") rm(list = ls()) source("./R/figures/spatial_stats_10myr.R") rm(list = ls()) source("./R/figures/sst_plot.R") rm(list = ls()) source("./R/figures/sst_plot_10myr.R") rm(list = ls()) source("./R/figures/lat_temp_plot.R") rm(list = ls()) source("./R/figures/map_plots_raster.R") rm(list = ls()) source("./R/figures/aptian_plot.R") rm(list = ls()) source("./R/figures/centroid_histogram.R") rm(list = ls()) source("./R/figures/linear_models.R") rm(list = ls()) source("./R/figures/continent_terrestrial_plot.R") rm(list = ls())
/R/run_analyses.R
no_license
LewisAJones/StableIsotopeBias
R
false
false
885
r
#data setup source("./R/subscripts/centroid_assignment.R") rm(list = ls()) source("./R/subscripts/data_prep.R") rm(list = ls()) #run analyses source("./R/subscripts/spatial_stats.R") rm(list = ls()) source("./R/subscripts/get_sst_data.R") rm(list = ls()) source("./R/subscripts/get_binned_vals.R") rm(list = ls()) #figures source("./R/figures/spatial_stats.R") rm(list = ls()) source("./R/figures/spatial_stats_10myr.R") rm(list = ls()) source("./R/figures/sst_plot.R") rm(list = ls()) source("./R/figures/sst_plot_10myr.R") rm(list = ls()) source("./R/figures/lat_temp_plot.R") rm(list = ls()) source("./R/figures/map_plots_raster.R") rm(list = ls()) source("./R/figures/aptian_plot.R") rm(list = ls()) source("./R/figures/centroid_histogram.R") rm(list = ls()) source("./R/figures/linear_models.R") rm(list = ls()) source("./R/figures/continent_terrestrial_plot.R") rm(list = ls())
#' @title Score the FACT-B+4 #' #' @description #' Generates all of the scores of the Functional Assessment of Cancer Therapy - Breast Cancer #' (FACT-B+4, v4) for patients with Lymphedema (to be used with FACT-B) from item responses. #' #' @details #' Given a data frame that includes all of the FACT-B+4 (Version 4) items as #' variables, appropriately named, this function generates all of the FACT-B+4 #' scale scores. It is crucial that the item variables in the supplied data #' frame are named according to FACT conventions. For example, the first #' physical well-being item should be named GP1, the second GP2, and so on. #' Please refer to the materials provided by \url{http://www.facit.org} for the #' particular questionnaire you are using. In particular, refer to the left #' margin of the official questionnaire (i.e., from facit.org) for the #' appropriate item variable names. #' #' @section Note: #' Keep in mind that this function (and R in general) is case-sensitive. #' #' All variables should be in numeric or integer format. #' #' This scoring function expects missing item responses to be coded as NA, #' 8, or 9, and valid item responses to be coded as 0, 1, 2, 3, or 4. Any #' other value for any of the items will result in an error message and no #' scores. #' #' Some item variables are reverse coded for the purpose of generating the #' scale scores. The official (e.g., from \url{http://www.facit.org}) SAS #' and SPSS scoring algorithms for this questionnaire automatically replace #' the original items with their reverse-coded versions. This can be #' confusing if you accidentally run the algorithm more than once on your #' data. As its default, \code{scoreFACT_Bplus4} DOES NOT replace any of your #' original item variables with the reverse coded versions. However, for #' consistentcy with the behavior of the other versions on #' \url{http://www.facit.org}, the \code{updateItems} argument is #' provided. If set to \code{TRUE}, any item that is supposed to be #' reverse coded will be replaced with its reversed version in the data #' frame returned by \code{scoreFACT_Bplus4}. #' #' #' @param df A data frame with the FACT-B+4 items, appropriately-named. #' @param updateItems Logical, if \code{TRUE} any original item that is #' reverse coded for scoring will be replaced by its reverse coded version #' in the returned data frame, and any values of 8 or 9 will be replaced #' with NA. The default, \code{FALSE}, returns the original items #' unmodified. #' @param keepNvalid Logical, if \code{TRUE} the function #' returns an additional variable for each of the returned scale scores #' containing the number of valid, non-missing responses from each #' respondent to the items on the given scale. If \code{FALSE} (the #' default), these variables are omitted from the returned data frame. #' #' #' @return The original data frame is returned (optionally with modified #' items if \code{updateItems = TRUE}) with new variables corresponding to #' the scored scales. If \code{keepNvalid = TRUE}, for each scored scale an #' additional variable is returned that contains the number of valid #' responses each respondent made to the items making up the given scale. #' These optional variables have names of the format \code{SCALENAME_N}. #' The following scale scores are returned: #' #' \describe{ #' \item{PWB}{Physical Well-Being subscale} #' \item{SWB}{Social/Family Well-Being subscale} #' \item{EWB}{Emotional Well-Being subscale} #' \item{FWB}{Physical Well-Being subscale} #' \item{FACTG}{FACT-G Total Score (i.e., PWB+SWB+EWB+FWB)} #' \item{BCS}{Breast Cancer subscale} #' \item{ARM}{Arm subscale} #' \item{FACT_B_TOTAL}{FACT-B Total Score (i.e., PWB+SWB+EWB+FWB+BCS)} #' \item{FACT_B_TOI}{FACT-B Trial Outcome Index (e.g., PWB+FWB+BCS)} #' } #' #' @references FACT-B+4 Scoring Guidelines, available at \url{http://www.facit.org} #' #' @export #' #' @examples #' ## Setting up item names for fake data #' G_names <- c(paste0('GP', 1:7), #' paste0('GS', 1:7), #' paste0('GE', 1:6), #' paste0('GF', 1:7)) #' AC_names1 <- c('B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9') #' AC_names2 <- c('B3', 'B10', 'B11', 'B12', 'B13') #' AC_names <- c(AC_names1, AC_names2) #' itemNames <- c(G_names, AC_names) #' ## Generating random item responses for 8 fake respondents #' set.seed(6375309) #' exampleDat <- t(replicate(8, sample(0:4, size = length(itemNames), replace = TRUE))) #' ## Making half of respondents missing about 10% of items, #' ## half missing about 50%. #' miss10 <- t(replicate(4, sample(c(0, 9), prob = c(0.9, 0.1), #' size = length(itemNames), replace = TRUE))) #' miss50 <- t(replicate(4, sample(c(0, 9), prob = c(0.5, 0.5), #' size = length(itemNames), replace = TRUE))) #' missMtx <- rbind(miss10, miss50) #' ## Using 9 as the code for missing responses #' exampleDat[missMtx == 9] <- 9 #' exampleDat <- as.data.frame(cbind(ID = paste0('ID', 1:8), #' as.data.frame(exampleDat))) #' names(exampleDat) <- c('ID', itemNames) #' #' ## Returns data frame with scale scores and with original items untouched #' scoredDat <- scoreFACT_Bplus4(exampleDat) #' names(scoredDat) #' scoredDat #' ## Returns data frame with scale scores, with the appropriate items #' ## reverse scored, and with item values of 8 and 9 replaced with NA. #' ## Also illustrates the effect of setting keepNvalid = TRUE. #' scoredDat <- scoreFACT_Bplus4(exampleDat, updateItems = TRUE, keepNvalid = TRUE) #' names(scoredDat) #' ## Descriptives of scored scales #' summary(scoredDat[, c('PWB', 'SWB', 'EWB', 'FWB', 'FACTG', #' 'BCS', 'ARM', 'FACT_B_TOTAL', 'FACT_B_TOI')]) scoreFACT_Bplus4 <- function(df, updateItems = FALSE, keepNvalid = FALSE) { dfG <- scoreFACTG(df, updateItems = updateItems, keepNvalid = TRUE) dfGup <- dfG names(dfGup) <- toupper(names(dfG)) G_names <- c(paste0("GP", 1:7), paste0("GS", 1:7), paste0("GE", 1:6), paste0("GF", 1:7)) AC_names1 <- c("B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9") AC_names2 <- c("B3", "B10", "B11", "B12", "B13") AC_names <- unique(c(AC_names1, AC_names2)) revNames <- unique(c("B1", "B2", "B3", "B5", "B6", "B7", "B8", "B3", "B10", "B11", "B12", "B13")) AC_items <- df[, AC_names] if (any(!(as.matrix(AC_items) %in% c(0:4, 8, 9, NA)))) { stop("At least 1 response is out of range (i.e., not 0-4, 8, 9, or NA)") } makeMiss <- function(x) { x[x %in% c(8, 9)] <- NA return(x) } AC_items <- as.data.frame(lapply(AC_items, makeMiss)) revHelper <- function(x) { return(4 - x) } AC_items[, revNames] <- lapply(AC_items[, revNames], revHelper) valid_N <- as.data.frame(lapply(AC_items, function(x) as.numeric(!is.na(x)))) AC_N1 <- rowSums(valid_N[, AC_names1]) AC_N2 <- rowSums(valid_N[, AC_names2]) TOTAL_N <- dfG$PWB_N + dfG$SWB_N + dfG$EWB_N + dfG$FWB_N + AC_N1 AC1 <- round(rowMeans(AC_items[, AC_names1], na.rm = TRUE) * length(AC_names1), 3) AC1[AC_N1/length(AC_names1) <= 0.5] <- NA AC2 <- round(rowMeans(AC_items[, AC_names2], na.rm = TRUE) * length(AC_names2), 3) AC2[AC_N2/length(AC_names2) <= 0.5] <- NA TOTAL <- dfG$PWB + dfG$SWB + dfG$EWB + dfG$FWB + AC1 TOTAL[TOTAL_N/length(c(G_names, AC_names1)) <= 0.8] <- NA TOI <- dfG$PWB + dfG$FWB + AC1 FACT_B_TOTAL_N <- TOTAL_N BCS_N <- AC_N1 ARM_N <- AC_N2 BCS <- AC1 ARM <- AC2 FACT_B_TOTAL <- TOTAL FACT_B_TOI <- TOI if (updateItems) { dfItemPos <- unlist(sapply(AC_names, function(x) grep(x, names(dfG), ignore.case = TRUE, value = FALSE))) names(dfG)[dfItemPos] <- toupper(names(dfG)[dfItemPos]) dfG[, AC_names] <- AC_items } if (keepNvalid) { dfOut <- as.data.frame(cbind(dfG, BCS_N, ARM_N, FACT_B_TOTAL_N, ARM, BCS, FACT_B_TOTAL, FACT_B_TOI)) } else { dfG[, "PWB_N"] <- NULL dfG[, "SWB_N"] <- NULL dfG[, "EWB_N"] <- NULL dfG[, "FWB_N"] <- NULL dfG[, "FACTG_N"] <- NULL dfOut <- as.data.frame(cbind(dfG, BCS, ARM, FACT_B_TOTAL, FACT_B_TOI)) } return(dfOut) }
/R/sx-scoreFACT_Bplus4.R
permissive
raybaser/FACTscorer
R
false
false
8,239
r
#' @title Score the FACT-B+4 #' #' @description #' Generates all of the scores of the Functional Assessment of Cancer Therapy - Breast Cancer #' (FACT-B+4, v4) for patients with Lymphedema (to be used with FACT-B) from item responses. #' #' @details #' Given a data frame that includes all of the FACT-B+4 (Version 4) items as #' variables, appropriately named, this function generates all of the FACT-B+4 #' scale scores. It is crucial that the item variables in the supplied data #' frame are named according to FACT conventions. For example, the first #' physical well-being item should be named GP1, the second GP2, and so on. #' Please refer to the materials provided by \url{http://www.facit.org} for the #' particular questionnaire you are using. In particular, refer to the left #' margin of the official questionnaire (i.e., from facit.org) for the #' appropriate item variable names. #' #' @section Note: #' Keep in mind that this function (and R in general) is case-sensitive. #' #' All variables should be in numeric or integer format. #' #' This scoring function expects missing item responses to be coded as NA, #' 8, or 9, and valid item responses to be coded as 0, 1, 2, 3, or 4. Any #' other value for any of the items will result in an error message and no #' scores. #' #' Some item variables are reverse coded for the purpose of generating the #' scale scores. The official (e.g., from \url{http://www.facit.org}) SAS #' and SPSS scoring algorithms for this questionnaire automatically replace #' the original items with their reverse-coded versions. This can be #' confusing if you accidentally run the algorithm more than once on your #' data. As its default, \code{scoreFACT_Bplus4} DOES NOT replace any of your #' original item variables with the reverse coded versions. However, for #' consistentcy with the behavior of the other versions on #' \url{http://www.facit.org}, the \code{updateItems} argument is #' provided. If set to \code{TRUE}, any item that is supposed to be #' reverse coded will be replaced with its reversed version in the data #' frame returned by \code{scoreFACT_Bplus4}. #' #' #' @param df A data frame with the FACT-B+4 items, appropriately-named. #' @param updateItems Logical, if \code{TRUE} any original item that is #' reverse coded for scoring will be replaced by its reverse coded version #' in the returned data frame, and any values of 8 or 9 will be replaced #' with NA. The default, \code{FALSE}, returns the original items #' unmodified. #' @param keepNvalid Logical, if \code{TRUE} the function #' returns an additional variable for each of the returned scale scores #' containing the number of valid, non-missing responses from each #' respondent to the items on the given scale. If \code{FALSE} (the #' default), these variables are omitted from the returned data frame. #' #' #' @return The original data frame is returned (optionally with modified #' items if \code{updateItems = TRUE}) with new variables corresponding to #' the scored scales. If \code{keepNvalid = TRUE}, for each scored scale an #' additional variable is returned that contains the number of valid #' responses each respondent made to the items making up the given scale. #' These optional variables have names of the format \code{SCALENAME_N}. #' The following scale scores are returned: #' #' \describe{ #' \item{PWB}{Physical Well-Being subscale} #' \item{SWB}{Social/Family Well-Being subscale} #' \item{EWB}{Emotional Well-Being subscale} #' \item{FWB}{Physical Well-Being subscale} #' \item{FACTG}{FACT-G Total Score (i.e., PWB+SWB+EWB+FWB)} #' \item{BCS}{Breast Cancer subscale} #' \item{ARM}{Arm subscale} #' \item{FACT_B_TOTAL}{FACT-B Total Score (i.e., PWB+SWB+EWB+FWB+BCS)} #' \item{FACT_B_TOI}{FACT-B Trial Outcome Index (e.g., PWB+FWB+BCS)} #' } #' #' @references FACT-B+4 Scoring Guidelines, available at \url{http://www.facit.org} #' #' @export #' #' @examples #' ## Setting up item names for fake data #' G_names <- c(paste0('GP', 1:7), #' paste0('GS', 1:7), #' paste0('GE', 1:6), #' paste0('GF', 1:7)) #' AC_names1 <- c('B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9') #' AC_names2 <- c('B3', 'B10', 'B11', 'B12', 'B13') #' AC_names <- c(AC_names1, AC_names2) #' itemNames <- c(G_names, AC_names) #' ## Generating random item responses for 8 fake respondents #' set.seed(6375309) #' exampleDat <- t(replicate(8, sample(0:4, size = length(itemNames), replace = TRUE))) #' ## Making half of respondents missing about 10% of items, #' ## half missing about 50%. #' miss10 <- t(replicate(4, sample(c(0, 9), prob = c(0.9, 0.1), #' size = length(itemNames), replace = TRUE))) #' miss50 <- t(replicate(4, sample(c(0, 9), prob = c(0.5, 0.5), #' size = length(itemNames), replace = TRUE))) #' missMtx <- rbind(miss10, miss50) #' ## Using 9 as the code for missing responses #' exampleDat[missMtx == 9] <- 9 #' exampleDat <- as.data.frame(cbind(ID = paste0('ID', 1:8), #' as.data.frame(exampleDat))) #' names(exampleDat) <- c('ID', itemNames) #' #' ## Returns data frame with scale scores and with original items untouched #' scoredDat <- scoreFACT_Bplus4(exampleDat) #' names(scoredDat) #' scoredDat #' ## Returns data frame with scale scores, with the appropriate items #' ## reverse scored, and with item values of 8 and 9 replaced with NA. #' ## Also illustrates the effect of setting keepNvalid = TRUE. #' scoredDat <- scoreFACT_Bplus4(exampleDat, updateItems = TRUE, keepNvalid = TRUE) #' names(scoredDat) #' ## Descriptives of scored scales #' summary(scoredDat[, c('PWB', 'SWB', 'EWB', 'FWB', 'FACTG', #' 'BCS', 'ARM', 'FACT_B_TOTAL', 'FACT_B_TOI')]) scoreFACT_Bplus4 <- function(df, updateItems = FALSE, keepNvalid = FALSE) { dfG <- scoreFACTG(df, updateItems = updateItems, keepNvalid = TRUE) dfGup <- dfG names(dfGup) <- toupper(names(dfG)) G_names <- c(paste0("GP", 1:7), paste0("GS", 1:7), paste0("GE", 1:6), paste0("GF", 1:7)) AC_names1 <- c("B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9") AC_names2 <- c("B3", "B10", "B11", "B12", "B13") AC_names <- unique(c(AC_names1, AC_names2)) revNames <- unique(c("B1", "B2", "B3", "B5", "B6", "B7", "B8", "B3", "B10", "B11", "B12", "B13")) AC_items <- df[, AC_names] if (any(!(as.matrix(AC_items) %in% c(0:4, 8, 9, NA)))) { stop("At least 1 response is out of range (i.e., not 0-4, 8, 9, or NA)") } makeMiss <- function(x) { x[x %in% c(8, 9)] <- NA return(x) } AC_items <- as.data.frame(lapply(AC_items, makeMiss)) revHelper <- function(x) { return(4 - x) } AC_items[, revNames] <- lapply(AC_items[, revNames], revHelper) valid_N <- as.data.frame(lapply(AC_items, function(x) as.numeric(!is.na(x)))) AC_N1 <- rowSums(valid_N[, AC_names1]) AC_N2 <- rowSums(valid_N[, AC_names2]) TOTAL_N <- dfG$PWB_N + dfG$SWB_N + dfG$EWB_N + dfG$FWB_N + AC_N1 AC1 <- round(rowMeans(AC_items[, AC_names1], na.rm = TRUE) * length(AC_names1), 3) AC1[AC_N1/length(AC_names1) <= 0.5] <- NA AC2 <- round(rowMeans(AC_items[, AC_names2], na.rm = TRUE) * length(AC_names2), 3) AC2[AC_N2/length(AC_names2) <= 0.5] <- NA TOTAL <- dfG$PWB + dfG$SWB + dfG$EWB + dfG$FWB + AC1 TOTAL[TOTAL_N/length(c(G_names, AC_names1)) <= 0.8] <- NA TOI <- dfG$PWB + dfG$FWB + AC1 FACT_B_TOTAL_N <- TOTAL_N BCS_N <- AC_N1 ARM_N <- AC_N2 BCS <- AC1 ARM <- AC2 FACT_B_TOTAL <- TOTAL FACT_B_TOI <- TOI if (updateItems) { dfItemPos <- unlist(sapply(AC_names, function(x) grep(x, names(dfG), ignore.case = TRUE, value = FALSE))) names(dfG)[dfItemPos] <- toupper(names(dfG)[dfItemPos]) dfG[, AC_names] <- AC_items } if (keepNvalid) { dfOut <- as.data.frame(cbind(dfG, BCS_N, ARM_N, FACT_B_TOTAL_N, ARM, BCS, FACT_B_TOTAL, FACT_B_TOI)) } else { dfG[, "PWB_N"] <- NULL dfG[, "SWB_N"] <- NULL dfG[, "EWB_N"] <- NULL dfG[, "FWB_N"] <- NULL dfG[, "FACTG_N"] <- NULL dfOut <- as.data.frame(cbind(dfG, BCS, ARM, FACT_B_TOTAL, FACT_B_TOI)) } return(dfOut) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/get_prediction_daily.R \name{get_prediction_daily} \alias{get_prediction_daily} \title{使用已有系数拟合预测DAU并计算差异} \usage{ get_prediction_daily( df_list, type = "train", ring_retain_new = c(0.848, 0.9138, 0.9525, 0.9679, 0.9801, 0.9861, 0.99, 0.99), ring_retain_old = 0.98, prediction_retain_one = 0.48, life_time_year = 1, csv = FALSE, plot = TRUE, message = FALSE, smooth = FALSE, analysis = FALSE, diff_type = "mse" ) } \arguments{ \item{df_list:}{函数所需参数列表(df_list),可由get_prediction_daily()获得。} \item{type:}{"train",使用跟训练拟合有关的参数判断,以train_days为训练日期得到拟合结果再以test_df计算差异验证训练结果;"test",直接使用test_df拟合参数及计算差异。默认"train"} \item{ring_retain_new:}{新用户的各段环比参数,可通过get_ring_retain()随机获得。默认 c(0.8480, 0.9138, 0.9525, 0.9679, 0.9801, 0.9861, 0.99, 0.99)} \item{ring_retain_old:}{老用户的环比参数,可通过get_ring_retain()随机获得。默认0.98} \item{prediction_retain_one:}{计算生命周期时,预估未来新增的次日留存。默认0.48} \item{life_time_year:}{计算生命周期的时段(按年统计)。默认1} \item{csv:}{是否输出结果到csv文件,分别为预测结果(prediction_\emph{.csv)和参数(parameter_}.csv)。默认FALSE} \item{plot:}{是否绘图。默认FALSE} \item{message:}{是否输出运行中的信息。默认FALSE} \item{smooth:}{是否使用时序分析包(forecast)获取趋势,目前只支持排除7日(周)影响。默认FALSE} \item{analysis:}{是否分析新老各段新增用户的留存贡献。默认FALSE} \item{diff_type:}{怎么计算差异。默认MSE} } \value{ 预测结果(df) } \description{ 根据新新用户各段环比参数及实际次日留存计算出每日留存曲线,结合每日实际新增预测各日新用户的每日总留存,再结合老用户按老用户环比参数计算出的老用户每日留存,加和得到每日预测DAU,并与每日实际DAU加权计算得到差异。 } \examples{ get_prediction_daily() }
/man/get_prediction_daily.Rd
no_license
catlain/LTV
R
false
true
2,218
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/get_prediction_daily.R \name{get_prediction_daily} \alias{get_prediction_daily} \title{使用已有系数拟合预测DAU并计算差异} \usage{ get_prediction_daily( df_list, type = "train", ring_retain_new = c(0.848, 0.9138, 0.9525, 0.9679, 0.9801, 0.9861, 0.99, 0.99), ring_retain_old = 0.98, prediction_retain_one = 0.48, life_time_year = 1, csv = FALSE, plot = TRUE, message = FALSE, smooth = FALSE, analysis = FALSE, diff_type = "mse" ) } \arguments{ \item{df_list:}{函数所需参数列表(df_list),可由get_prediction_daily()获得。} \item{type:}{"train",使用跟训练拟合有关的参数判断,以train_days为训练日期得到拟合结果再以test_df计算差异验证训练结果;"test",直接使用test_df拟合参数及计算差异。默认"train"} \item{ring_retain_new:}{新用户的各段环比参数,可通过get_ring_retain()随机获得。默认 c(0.8480, 0.9138, 0.9525, 0.9679, 0.9801, 0.9861, 0.99, 0.99)} \item{ring_retain_old:}{老用户的环比参数,可通过get_ring_retain()随机获得。默认0.98} \item{prediction_retain_one:}{计算生命周期时,预估未来新增的次日留存。默认0.48} \item{life_time_year:}{计算生命周期的时段(按年统计)。默认1} \item{csv:}{是否输出结果到csv文件,分别为预测结果(prediction_\emph{.csv)和参数(parameter_}.csv)。默认FALSE} \item{plot:}{是否绘图。默认FALSE} \item{message:}{是否输出运行中的信息。默认FALSE} \item{smooth:}{是否使用时序分析包(forecast)获取趋势,目前只支持排除7日(周)影响。默认FALSE} \item{analysis:}{是否分析新老各段新增用户的留存贡献。默认FALSE} \item{diff_type:}{怎么计算差异。默认MSE} } \value{ 预测结果(df) } \description{ 根据新新用户各段环比参数及实际次日留存计算出每日留存曲线,结合每日实际新增预测各日新用户的每日总留存,再结合老用户按老用户环比参数计算出的老用户每日留存,加和得到每日预测DAU,并与每日实际DAU加权计算得到差异。 } \examples{ get_prediction_daily() }
# #_________________________________________________________________________80char #' plot_freq_ADSR #' #' @description Plot frequency profiles by fitted parameter of ADSR types #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' @param parameter_subsets parameter subsets passed from fit.final_space #' #' @return A frequency plot of fitted parameter values. #' #' @keywords internal plot_freq_ADSR <- function(DF, names.swp.ADSR, parameter_subsets){ . <- in.all.subset_param <- n <- swp.ADSR.value <- swp.ADSR.name <- label <- swp.center <- swp.2se <- swp.mean <- swp.50 <- swp.75 <- swp.25 <- swp.95 <- swp.05 <- freq.in <- swp.2sd <- NULL names.parameter_subsets <- names(parameter_subsets) ##### ___ i. qp freq calculation / parameter within CI & within parameter subsets ###### if (!is.null(names.parameter_subsets) & any(names.parameter_subsets %in% names.swp.ADSR)){ DF.swp.ADSR <- DF %>% dplyr::group_by( dplyr::across(names.swp.ADSR)) %>% dplyr::select(dplyr::all_of(names.swp.ADSR)) %>% as.data.frame() %>% reshape2::melt(id.vars = NULL, variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(swp.ADSR.value = unique(swp.ADSR.value), .groups = "drop_last") %>% as.data.frame() swp.ADSR.subset_range <- as.data.frame(parameter_subsets[names(parameter_subsets) %in% names.swp.ADSR]) DF.swp.ADSR$in.parameter_subsets <- TRUE for (i in 1:ncol(swp.ADSR.subset_range)){ swp.ADSR_loc <- names(swp.ADSR.subset_range)[i] DF.swp.ADSR[DF.swp.ADSR$swp.ADSR.name == swp.ADSR_loc & DF.swp.ADSR$swp.ADSR.value < min(swp.ADSR.subset_range[,swp.ADSR_loc]) , "in.parameter_subsets"] <- FALSE DF.swp.ADSR[DF.swp.ADSR$swp.ADSR.name == swp.ADSR_loc & DF.swp.ADSR$swp.ADSR.value > max(swp.ADSR.subset_range[,swp.ADSR_loc]) , "in.parameter_subsets"] <- FALSE } } # remove(swp.ADSR_loc) molten.DF.CI_fitted <- reshape2::melt(DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.all.subset_param == TRUE, c(names.swp.ADSR)], id.vars = NULL, variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") freq.molten.DF.CI_fitted <- molten.DF.CI_fitted %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% dplyr::mutate(freq = 100*n/sum(n)) %>% as.data.frame() molten.DF <- reshape2::melt(DF[, c(names.swp.ADSR, "in.all.subset_param")], id.vars = "in.all.subset_param", variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") freq.molten.DF <- molten.DF %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% dplyr::mutate(freq = 100*n/sum(n)) %>% as.data.frame() freq.molten <- dplyr::full_join(freq.molten.DF, freq.molten.DF.CI_fitted, by = c("swp.ADSR.name", "swp.ADSR.value"), suffix = c(".all", ".in")) freq.molten$freq.in.vs.all <- 100*freq.molten$n.in/freq.molten$n.all cropped_param_values <- molten.DF %>% dplyr::filter(swp.ADSR.name %in% names(parameter_subsets)) %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value, in.all.subset_param) %>% dplyr::count() %>% as.data.frame() cropped_param_values.TRUE <- cropped_param_values %>% dplyr::filter(in.all.subset_param == TRUE) %>% dplyr::select(swp.ADSR.name, swp.ADSR.value, in.all.subset_param) cropped_param_values <- cropped_param_values %>% dplyr::select(swp.ADSR.name, swp.ADSR.value) %>% dplyr::distinct() cropped_param_values <- dplyr::full_join(cropped_param_values, cropped_param_values.TRUE, by = c("swp.ADSR.name", "swp.ADSR.value") ) cropped_param_values <- cropped_param_values %>% replace(is.na(.), FALSE) freq.molten <- freq.molten %>% replace(is.na(.), 0) freq.molten <- dplyr::full_join(freq.molten, cropped_param_values, by = c("swp.ADSR.name", "swp.ADSR.value")) freq.molten <- freq.molten %>% replace(is.na(.), TRUE) param.min_max <- freq.molten %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(full_range.min = min(swp.ADSR.value), full_range.max = max(swp.ADSR.value), .groups = "drop_last") %>% as.data.frame() stats.molten.DF.CI_fitted <- molten.DF.CI_fitted %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(n = dplyr::n(), swp.min = min(swp.ADSR.value, na.rm = T), swp.max = max(swp.ADSR.value, na.rm = T), swp.05 = stats::quantile(swp.ADSR.value, .05), swp.25 = stats::quantile(swp.ADSR.value, .25), swp.50 = stats::quantile(swp.ADSR.value, .5), swp.75 = stats::quantile(swp.ADSR.value, .75), swp.95 = stats::quantile(swp.ADSR.value, .95), swp.mean = mean(swp.ADSR.value, na.rm = T), swp.2sd = 2*stats::sd(swp.ADSR.value, na.rm = T), swp.2se = swp.2sd/sqrt(n) , .groups = "drop_last") %>% as.data.frame() center.swp.param <- molten.DF %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(swp.center = min(swp.ADSR.value, na.rm = T)+.5*(max(swp.ADSR.value, na.rm = T)-min(swp.ADSR.value, na.rm = T)), .groups = "drop_last") %>% as.data.frame() stats.molten.DF.CI_fitted <- dplyr::full_join(stats.molten.DF.CI_fitted, center.swp.param, by = "swp.ADSR.name") stats.molten.DF.CI_fitted <- dplyr::full_join(stats.molten.DF.CI_fitted, param.min_max, by = "swp.ADSR.name") stats.molten.DF.CI_fitted$mag_order <- round(-log10(stats.molten.DF.CI_fitted$full_range.max-stats.molten.DF.CI_fitted$full_range.min)) stats.molten.DF.CI_fitted[stats.molten.DF.CI_fitted$mag_order < 0, "mag_order"] <- 0 stats.molten.DF.CI_fitted[stats.molten.DF.CI_fitted$mag_order == Inf, "mag_order"] <- 0 stats.molten.DF.CI_fitted$label <- paste0(dec_n(stats.molten.DF.CI_fitted$swp.mean, stats.molten.DF.CI_fitted$mag_order+2), " \u00B1 ", dec_n(.5*stats.molten.DF.CI_fitted$swp.2sd, stats.molten.DF.CI_fitted$mag_order+2), " (", dec_n(stats.molten.DF.CI_fitted$swp.2se, stats.molten.DF.CI_fitted$mag_order+2), ")" ) max.freq.molten <- freq.molten %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::filter(freq.in == max(freq.in)) %>% dplyr::arrange (swp.ADSR.name, swp.ADSR.value, freq.in) %>% as.data.frame() stats.molten.DF.CI_fitted.max <- dplyr::full_join(stats.molten.DF.CI_fitted, max.freq.molten[, c("swp.ADSR.name", "swp.ADSR.value", "freq.in")], by = "swp.ADSR.name") stats.molten.DF.CI_fitted.max$freq_max.label <- paste0(dec_n(stats.molten.DF.CI_fitted.max$swp.ADSR.value, stats.molten.DF.CI_fitted.max$mag_order+2)) remove(molten.DF, center.swp.param, cropped_param_values, cropped_param_values.TRUE, freq.molten.DF.CI_fitted, freq.molten.DF, max.freq.molten, param.min_max) quiet(gc()) ##### ___ ii. plot qp CI fit frequencies #### boxplot_y <- -5 mean_y <- -11 annotation_y <- -20 lower_border_y <- -20 plot.freq_ADSR <- ggplot2::ggplot(freq.molten, ggplot2::aes(x = swp.ADSR.value, y = freq.in, color = swp.ADSR.name, fill = swp.ADSR.name))+ ggplot2::geom_hline(linetype = 1, size = .25, yintercept = 0)+ ggplot2::geom_rect(ggplot2::aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 0), fill = "gray95", color =NA)+ # ggplot2::geom_point(size = 1, alpha = 1)+ # ggplot2::geom_area(data = freq.molten[freq.molten$in.all.subset_param == TRUE, ], # alpha = .25)+ ggplot2::geom_linerange(ggplot2::aes(ymin = 0, ymax = freq.in), size = 2, linetype = 1)+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), plot.caption = ggplot2::element_text(hjust = 0), strip.text = ggplot2::element_text(face="bold"), panel.grid = ggplot2::element_blank() # plot.title.position = "plot", #NEW parameter. Apply for subtitle too. # plot.caption.position = "plot" )+ ggplot2::facet_wrap(. ~ swp.ADSR.name, scales = "free_x", ncol = round(1.1*length(levels(freq.molten$swp.ADSR.name))/2) )+ ggplot2::labs(title = "Frequency distributions of CI fitted quantitative parameter ", y = "frequence of runs within observed CIs of all boxes (\u0025)", x = "sweeped parameter values", caption = paste(#"Proportion of fits:", dec_n(fraction_of_fitting_sim, 1), "\u0025", "Upper part: Frequence curves with parameter value of maximum frequence.", " \n", "Lower part: (up) Horizontal distribution boxplot (5, 25, 50, 75, 95\u0025) with median (IQR); ", "(mid) Horizontal mean with 1sd and 2se error bar; ", "\n", "(down) Value of mean \u00B1 1sd (2se).", "\n", "Crosses mark values standing outside a parameter subset.", sep = "") )+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, # boxplot / 2SD / 2SE inherit.aes = F, ggplot2::aes(y = boxplot_y, xmin = swp.05, xmax = swp.95, color = swp.ADSR.name), size = 1, alpha = 1, height = 0)+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, inherit.aes = F, ggplot2::aes(y = boxplot_y, xmin = swp.25, xmax = swp.75, color = swp.ADSR.name), size = 3, alpha = 1, height = 0)+ ggplot2::geom_point(data = stats.molten.DF.CI_fitted, ggplot2::aes(y = boxplot_y, x = swp.50), color = "black", size = 2, shape = 24)+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, # mean / 2SD / 2SE inherit.aes = F, ggplot2::aes(y = mean_y, xmin = swp.mean-.5*swp.2sd, xmax = swp.mean+.5*swp.2sd, color = swp.ADSR.name), size = 1, alpha = 1, height = 0)+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, inherit.aes = F, ggplot2::aes(y = mean_y, xmin = swp.mean-swp.2se, xmax = swp.mean+swp.2se, color = swp.ADSR.name), size = 3, alpha = 1, height = 0)+ ggplot2::geom_point(data = stats.molten.DF.CI_fitted, ggplot2::aes(y = mean_y, x = swp.mean), color = "black", size = 2, shape = 25)+ ggplot2::geom_text(data = stats.molten.DF.CI_fitted, ggplot2::aes(x = swp.center, y = annotation_y, hjust = 0.5, vjust = 0, label = label), size = 3)+ ggplot2::scale_y_continuous(limits=c(lower_border_y, 100), breaks=seq(0, 100, by = 10))+ ggplot2::coord_cartesian(ylim = c(lower_border_y, 1.0*max(freq.molten$freq.in))) # ggrepel::geom_label_repel(data = stats.molten.DF.CI_fitted.max, # fill = "white", # nudge_y = 15, # vjust = 0, # direction = c("y"), # # hjust = 0, # size = 2.5, # angle = 45, # segment.linetype = 3, # label.size = NA, # ggplot2::aes(x = swp.ADSR.value, # y = freq.in, # label = freq_max.label)) if (exists("DF.swp.ADSR")){ plot.freq_ADSR <- plot.freq_ADSR + ggplot2::geom_point(inherit.aes = F, data = DF.swp.ADSR[DF.swp.ADSR$in.parameter_subsets == FALSE, ], ggplot2::aes(x = swp.ADSR.value, y = 0), shape = 4, size = 2, color = "black" ) } freq.molten.export <- freq.molten[,c("swp.ADSR.name", "in.all.subset_param", "swp.ADSR.value", "freq.in", "n.all", "n.in")] names(freq.molten.export) <- c("Quantitative parameter", "Manually subset", "Parameter value", "Frequence in CI-fit (\u0025)", "n all simulations", "n CI-fitted simulations") stats.report <- stats.molten.DF.CI_fitted return(list(plot = plot.freq_ADSR, stats = stats.molten.DF.CI_fitted, freqs = stats.report)) } # #_________________________________________________________________________80char #' plot_freq_flux #' #' @description Plot frequency profiles by fitted flux lists #' #' @param DF fit.final_space data frame #' @param parameter_subsets fitted flux lists subsets passed from fit.final_space #' #' @return A frequency plot of fitted parameter values. #' #' @keywords internal plot_freq_flux <- function(DF, parameter_subsets){ in.subset.swp.flux_list_name <- freq.in <- . <- n <- in.all_fit_boxes.obs.CI <- in.all.subset_param <- swp.flux_list_name <- NULL names.parameter_subsets <- names(parameter_subsets) DF.flux_counts.all <- DF %>% dplyr::group_by(swp.flux_list_name) %>% dplyr::summarise(n.all = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.flux_counts.in_out <- DF %>% dplyr::filter(in.all.subset_param == TRUE) %>% dplyr::group_by(swp.flux_list_name, in.all_fit_boxes.obs.CI) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.flux_freq.in <- DF.flux_counts.in_out[DF.flux_counts.in_out$in.all_fit_boxes.obs.CI == TRUE, ] %>% dplyr::mutate(freq.in = 100*n/sum(n)) %>% as.data.frame() DF.flux_freq.out <- DF.flux_counts.in_out[DF.flux_counts.in_out$in.all_fit_boxes.obs.CI == FALSE, ] %>% dplyr::mutate(freq.out = 100*n/sum(n)) %>% as.data.frame() DF.flux_freq <- dplyr::full_join(DF.flux_freq.in, DF.flux_freq.out, by = "swp.flux_list_name", suffix = c(".in", ".out")) DF.flux_freq <- dplyr::full_join(DF.flux_counts.all, DF.flux_freq, by = "swp.flux_list_name", suffix = c(".all", "")) DF.flux_freq <- DF.flux_freq %>% replace(is.na(.), 0) plot.freq_flux <- ggplot2::ggplot(DF.flux_freq, ggplot2::aes(x = swp.flux_list_name, y = freq.in, label= swp.flux_list_name))+ ggplot2::geom_col(size = 1, alpha =.25, fill = "red")+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", # axis.title.y = ggplot2::element_blank(), axis.ticks.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_blank(), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0) )+ ggplot2::geom_text(ggplot2::aes(x = swp.flux_list_name, y = 0), hjust = 0, size = 2)+ ggplot2::labs(title = "Frequency distribution of CI fitted flux lists", y = "frequence of fit within all CIs (\u0025)", x = "flux list name")+ ggplot2::coord_flip() if (!is.null(names.parameter_subsets) & "swp.flux_list_name" %in% names.parameter_subsets){ DF.flux_counts.parameter_subsets <- DF %>% dplyr::group_by(swp.flux_list_name, in.subset.swp.flux_list_name) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() if (nrow(DF.flux_counts.parameter_subsets[DF.flux_counts.parameter_subsets$in.subset.swp.flux_list_name == FALSE, ]) > 0){ plot.freq_flux <- plot.freq_flux + ggplot2::geom_point(inherit.aes = F, data = DF.flux_counts.parameter_subsets[DF.flux_counts.parameter_subsets$in.subset.swp.flux_list_name == FALSE, ], ggplot2::aes(x = swp.flux_list_name, y = -2), shape = 4, size = 2, color = "black") + ggplot2::labs(caption = "Crosses mark values standing outside a parameter subset.") } } DF.flux_freq.export <- DF.flux_freq[, c("swp.flux_list_name", "freq.in", "n.all", "n.in")] names(DF.flux_freq.export) <- c("Flux list name", "Frequence in CI-fit (\u0025)", "n all simulations", "n CI-fitted simulations" ) return(list(plot = plot.freq_flux, freqs = DF.flux_freq.export)) } # #_________________________________________________________________________80char #' plot_freq_coeff #' #' @description Plot frequency profiles by fitted coeff lists #' #' @param DF fit.final_space data frame #' @param parameter_subsets fitted coeff lists subsets passed from fit.final_space #' #' @return A frequency plot of fitted parameter values. #' #' @keywords internal plot_freq_coeff <- function(DF, parameter_subsets){ in.subset.swp.coeff_list_name <- freq.in <- . <- n <- in.all_fit_boxes.obs.CI <- in.all.subset_param <- swp.coeff_list_name <- NULL names.parameter_subsets <- names(parameter_subsets) DF.coeff_counts.all <- DF %>% dplyr::group_by(swp.coeff_list_name) %>% dplyr::summarise(n.all = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.coeff_counts.in_out <- DF %>% dplyr::filter(in.all.subset_param == TRUE) %>% dplyr::group_by(swp.coeff_list_name, in.all_fit_boxes.obs.CI) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.coeff_freq.in <- DF.coeff_counts.in_out[DF.coeff_counts.in_out$in.all_fit_boxes.obs.CI == TRUE, ] %>% dplyr::mutate(freq.in = 100*n/sum(n)) %>% as.data.frame() DF.coeff_freq.out <- DF.coeff_counts.in_out[DF.coeff_counts.in_out$in.all_fit_boxes.obs.CI == FALSE, ] %>% dplyr::mutate(freq.out = 100*n/sum(n)) %>% as.data.frame() DF.coeff_freq <- dplyr::full_join(DF.coeff_freq.in, DF.coeff_freq.out, by = "swp.coeff_list_name", suffix = c(".in", ".out")) DF.coeff_freq <- dplyr::full_join(DF.coeff_counts.all, DF.coeff_freq, by = "swp.coeff_list_name", suffix = c(".all", "")) DF.coeff_freq <- DF.coeff_freq %>% replace(is.na(.), 0) plot.freq_coeff <- ggplot2::ggplot(DF.coeff_freq, ggplot2::aes(x = swp.coeff_list_name, y = freq.in, label= swp.coeff_list_name))+ ggplot2::geom_col(size = 1, alpha =.25, fill = "red")+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", # axis.title.y = ggplot2::element_blank(), axis.ticks.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_blank(), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot" )+ ggplot2::geom_text(ggplot2::aes(x = swp.coeff_list_name, y = 0), hjust = 0)+ ggplot2::labs(title = "Frequency distribution of CI fitted coeff. lists", y = "frequence of fit within all CIs (\u0025)", x = "coeff list name")+ ggplot2::coord_flip() if (!is.null(names.parameter_subsets) & "swp.coeff_list_name" %in% names.parameter_subsets){ DF.coeff_counts.parameter_subsets <- DF %>% dplyr::group_by(swp.coeff_list_name, in.subset.swp.coeff_list_name) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() if (nrow(DF.coeff_counts.parameter_subsets[DF.coeff_counts.parameter_subsets$in.subset.swp.coeff_list_name == FALSE, ]) > 0){ plot.freq_coeff <- plot.freq_coeff + ggplot2::geom_point(inherit.aes = F, data = DF.coeff_counts.parameter_subsets[DF.coeff_counts.parameter_subsets$in.subset.swp.coeff_list_name == FALSE, ], ggplot2::aes(x = swp.coeff_list_name, y = -2), shape = 4, size = 2, color = "black") + ggplot2::labs(caption = "Crosses mark values standing outside a parameter subset.") } } DF.coeff_freq.export <- DF.coeff_freq[, c("swp.coeff_list_name", "freq.in", "n.all", "n.in")] names(DF.coeff_freq.export) <- c("Coeff list name", "Frequence in CI-fit (\u0025)", "n all simulations", "n CI-fitted simulations" ) return(list(plot = plot.freq_coeff, freqs = DF.coeff_freq)) } # #_________________________________________________________________________80char #' plot_sim_obs #' #' @description Plot simulations against observations #' #' @param DF fit.final_space data frame #' @param bx.fit list of boxes fitted and unfitted groups and subgroups passed from fit.final_space #' @param fit.counts counts of simulations by groups passed from fit.final_space #' #' @return A plot of fitted simulated delta values against observations #' #' @keywords internal plot_sim_obs <- function(DF, bx.fit, fit.counts){ X.CI <- Y.75 <- Y.25 <- Y.50 <- Y.max <- Y.min <- ymax <- ymin <- x <- Y <- X <- sim.delta <- obs.CI <- obs.delta <- in.boxes_to_fit <- BOX_ID <- n <- SERIES_RUN_ID <- in.all.subset_param <- in.all_fit_boxes.obs.CI <- NULL run_fit_proportions <- DF %>% dplyr::group_by(in.all_fit_boxes.obs.CI, in.all.subset_param, SERIES_RUN_ID) %>% dplyr::count() %>% as.data.frame() %>% dplyr::count(in.all_fit_boxes.obs.CI, in.all.subset_param) %>% dplyr::summarise(in.all_fit_boxes.obs.CI = in.all_fit_boxes.obs.CI, in.all.subset_param = in.all.subset_param, n = n, freq = 100*n/sum(n), .groups = "drop_last") frac_of_runs_in_CI_parameter_subsets <- run_fit_proportions[run_fit_proportions$in.all_fit_boxes.obs.CI == TRUE & run_fit_proportions$in.all.subset_param == TRUE, "freq"] frac_of_runs_in_CI <- sum(run_fit_proportions[run_fit_proportions$in.all_fit_boxes.obs.CI == TRUE, "freq"]) tot_runs <- sum(run_fit_proportions[ , "n"]) remove(run_fit_proportions) sim_obs.mean <- DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ] %>% dplyr::group_by(BOX_ID, in.boxes_to_fit) %>% dplyr::summarise(X = mean(obs.delta), X.CI = mean(obs.CI), Y = mean(sim.delta), Y.05 = stats::quantile(sim.delta, .05), Y.25 = stats::quantile(sim.delta, .25), Y.50 = stats::quantile(sim.delta, .50), Y.75 = stats::quantile(sim.delta, .75), Y.95 = stats::quantile(sim.delta, .95), Y.min = min(sim.delta, na.rm = T), Y.max = max(sim.delta, na.rm = T), .groups = "drop_last") %>% as.data.frame() sim_obs.mean$X.provided <- FALSE sim_obs.mean[!is.nan(sim_obs.mean$X), "X.provided"] <- TRUE nudge_y.range <- abs(max(DF$sim.delta)-min(DF$sim.delta)) nudge_x.range <- abs(max(DF$obs.delta, na.rm = T)-min(DF$obs.delta, na.rm = T)) # box_lists <- sim_obs.mean %>% # dplyr::group_by(in.boxes_to_fit, X.provided) %>% # dplyr::summarise(boxes = paste0(sort(as.character(BOX_ID)), collapse = ", "), .groups = "drop_last") %>% # as.data.frame() # box_lists$label <- NaN # box_lists[box_lists$in.boxes_to_fit == TRUE & box_lists$X.provided == TRUE, "label"] <- "Targetted: " # box_lists[box_lists$in.boxes_to_fit == FALSE & box_lists$X.provided == TRUE, "label"] <- "Excluded: " # box_lists[box_lists$X.provided == FALSE, "label"] <- "Missing obs.: " # box_lists_caption <- paste0(paste(paste(box_lists$label, box_lists$boxes, sep = ""), # collapse = " \n"), "\n", report.CIfit) # box_lists_caption <- if (all(bx.fit$targetted == bx.fit$targetted_initial)){ list_box_lists_caption <- paste0("Targets : ", paste(bx.fit$targetted, collapse = " - ")) } else { list_box_lists_caption <- paste0("Initial targets : ", paste(bx.fit$targetted_initial, collapse = " - ")) if (length(bx.fit$targetted_no_obs) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Missing obs : ", paste(bx.fit$targetted_no_obs, collapse = " - "))) } if (length(bx.fit$targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Targets : ", paste(bx.fit$targetted, collapse = " - "))) } } if (length(bx.fit$not_targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Not targets : ", paste(bx.fit$not_targetted, collapse = " - "))) } if (length(bx.fit$CI_fit.successful) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Successful fit : ", paste(bx.fit$CI_fit.successful, collapse = " - "))) } if (length(bx.fit$CI_fit.failed) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("No fit : ", paste(bx.fit$CI_fit.failed, collapse = " - "))) } box_lists_caption <- paste(list_box_lists_caption, collapse = "\n") # lm reports lm_report <- corr_stats(data_lm = DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.boxes_to_fit == TRUE & DF$in.all.subset_param == TRUE, ], X = "obs.delta", Y = "sim.delta") %>% as.list() lm_report.text <- paste0("LM (2se): ", " y = ", dec_n(lm_report$pear.slope, 3), " ( \u00B1 ", dec_n(lm_report$pear.slope.2se, 3), " ) * x + ", dec_n(lm_report$pear.yint, 3), " ( \u00B1 ", dec_n(lm_report$pear.yint.2se, 3), " ) ", "\n", "Pear. R2 = ", dec_n(lm_report$pear.R2, 3), " ", lm_report$pear.signif, "; ", "Spear. rho = ", dec_n(lm_report$spear.Rho, 3), " ", lm_report$spear.signif, "\n", "n = ", dec_n(lm_report$n, 0) ) lm_report.text.x = min(sim_obs.mean$X-sim_obs.mean$X.CI, na.rm=T) lm_report.text.y = max(sim_obs.mean$Y.max) linerange <- clear_subset(DF[DF$BOX_ID %in% bx.fit$observed, ]) %>% dplyr::group_by(BOX_ID) %>% dplyr::summarise(x = unique(obs.delta), ymin = min(sim.delta, na.rm = T), ymax = max(sim.delta, na.rm = T), .groups = "drop_last") %>% as.data.frame() plot.sim_obs <- ggplot2::ggplot(data = sim_obs.mean, ggplot2::aes(x = X, y = Y ))+ ggplot2::geom_abline(slope = 1, linetype = 2)+ ggplot2::geom_abline(intercept = lm_report$pear.yint, slope = lm_report$pear.slope, linetype = 1, color = "blue")+ ggplot2::scale_shape_manual(values = c(23, 21))+ ggplot2::geom_linerange(data = linerange, inherit.aes = F, ggplot2::aes(x = x, y = ymin, ymin = ymin, ymax = ymax, color = BOX_ID), linetype = 2, size = 0.25, alpha = 0.5) + # ggplot2::geom_jitter(data = DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & # DF$in.all.subset_param == TRUE & # DF$BOX_ID %in% bx.fit$observed, ], shape = 43, size = 0.2, # ggplot2::aes(x = obs.delta, y = sim.delta, color = BOX_ID), na.rm = T, # width = (max(sim_obs.mean$X + sim_obs.mean$X.CI, na.rm = T) - min(sim_obs.mean$X - sim_obs.mean$X.CI, na.rm = T))/100 )+ # ggplot2::scale_alpha_continuous(range = c(0.1,.5))+ # stat_bin_2d(inherit.aes = F, # data = clear_subset(DF[DF$BOX_ID %in% bx.fit$observed, ]), # ggplot2::aes(x = obs.delta, y = sim.delta, alpha = ..ndensity.., fill = BOX_ID), # bins = 200, na.rm = T)+ ggplot2::geom_errorbar(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes(x = X, ymin = Y.min, ymax = Y.max, color = BOX_ID), size = 1, width = 0)+ ggplot2::geom_errorbar(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes(x = X, y = Y.50, ymin = Y.25, ymax = Y.75, color = BOX_ID), size = 3, width = 0)+ ggplot2::geom_errorbarh(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes( y = Y.50, xmin = X - X.CI, xmax = X + X.CI, color = BOX_ID), size = 1, na.rm = T, height = 0)+ ggplot2::geom_point(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes(y = Y.50, x = X, fill = BOX_ID, shape = as.factor(in.boxes_to_fit) ), color = "black", size = 3, na.rm = T )+ ggplot2::theme_linedraw()+ ggplot2::labs(title = "Simulation vs. Observation", subtitle = box_lists_caption, caption = paste(fit.counts$sims.all, " simulations - ", fit.counts$sims.in.CIfit.param_subsets, " fitted simulations - ", fit.counts$sim_delta.fitted_boxes, " fitted delta values", "\n", "Symbols show the medians of fitted boxes (circles) and non fitted boxes (diamonds)", "\n", "Horizontal bars: confidence interval on observations.", "\n", "Dashed light vertical bars: full extant of simulations.","\n", "Solid thin and thick vertical bars: Full and interquartile (25-75\u0025) range of predicted compositions.","\n", "Lines: black dashed line is identity; blue solid line is linear regression of all CI-fitted sim-obs pairs.", sep = ""), x = expression(paste("Observed ", delta^{"i/j"},"X" )), y = expression(paste("Simulated ", delta^{"i/j"},"X" )))+ ggplot2::theme(legend.position = "None", plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank(), plot.subtitle = ggplot2::element_text(size = 7) ) + ggplot2::annotate(geom = "text", x = lm_report.text.x, y = lm_report.text.y, label = lm_report.text, hjust = 0, vjust = 1)+ ggrepel::geom_label_repel(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), # inherit.aes = F, ggplot2::aes(x = X - X.CI, y = Y.50, label = BOX_ID, color = BOX_ID), nudge_y = 0, fill = "white", segment.color = "gray75", nudge_x = -0.09*nudge_x.range)+ ggplot2::scale_x_continuous(labels = dec_2)+ ggplot2::scale_y_continuous(labels = dec_2)+ ggplot2::coord_equal(ylim = c(min(sim_obs.mean$Y.min), max(sim_obs.mean$Y.max))) return(plot.sim_obs) } # #_________________________________________________________________________80char #' plot_sim_distrib #' #' @description Plot distributions of all and fitted simulations #' #' @param DF fit.final_space data frame #' @param fit.counts counts of simulations by groups passed from fit.final_space #' @param observations data frame of observations #' @param bx.fit list of boxes fitted and unfitted groups and subgroups passed from fit.final_space #' #' @return A plot of distributions of all and fitted simulations #' #' @keywords internal plot_sim_distrib <- function(DF, fit.counts, observations, bx.fit){ obs.CI <- obs.delta <- sim.delta.mean <- sim.delta <- BOX_ID <- NULL # box_lists_caption <- if (all(bx.fit$targetted == bx.fit$targetted_initial)){ list_box_lists_caption <- paste0("Targets : ", paste(bx.fit$targetted, collapse = " - ")) } else { list_box_lists_caption <- paste0("Initial targets : ", paste(bx.fit$targetted_initial, collapse = " - ")) if (length(bx.fit$targetted_no_obs) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Missing obs : ", paste(bx.fit$targetted_no_obs, collapse = " - "))) } if (length(bx.fit$targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Targets : ", paste(bx.fit$targetted, collapse = " - "))) } } if (length(bx.fit$not_targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Not targets : ", paste(bx.fit$not_targetted, collapse = " - "))) } if (length(bx.fit$CI_fit.successful) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Successful fit : ", paste(bx.fit$CI_fit.successful, collapse = " - "))) } if (length(bx.fit$CI_fit.failed) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("No fit : ", paste(bx.fit$CI_fit.failed, collapse = " - "))) } box_lists_caption <- paste(list_box_lists_caption, collapse = "\n") BOX_ID_facet_labels <- DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ] %>% dplyr::group_by(BOX_ID) %>% dplyr::summarise(sim.delta.mean = mean(sim.delta)) %>% dplyr::arrange(sim.delta.mean) %>% as.data.frame() %>% dplyr::select(BOX_ID) %>% as.vector() BOX_ID_facet_labels <- BOX_ID_facet_labels$BOX_ID %>% as.character() fit.limits <- DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ] %>% dplyr::summarise(sim.delta.min = min(sim.delta), sim.delta.max = max(sim.delta)) all_sims.limits <- DF %>% dplyr::summarise(sim.delta.min = min(sim.delta), sim.delta.max = max(sim.delta)) plot.sim_distrib <- ggplot2::ggplot(DF, ggplot2::aes(x = stats::reorder(BOX_ID, obs.delta), y = sim.delta, groups = BOX_ID, # y = ..ndensity.., # y = ..prop.., # fill = BOX_ID # height = stat(density) )) + ggplot2::geom_hline(yintercept = 0, linetype = 2, color = "gray75", size = 0.5)+ ggplot2::theme_linedraw()+ ggplot2::geom_violin(alpha = 1, fill = "gray90", draw_quantiles = c(0.5), scale = "width", color = "black", size = 0.25, trim = T, adjust = .5) + # ggplot2::geom_jitter(data = DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ], # size = .01, color = "blue", alpha = .25, # shape = 46, width = 0.1) + ggplot2::geom_violin(data = DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ], # ggplot2::aes(fill = BOX_ID), fill = "blue", # alpha = 0.5, draw_quantiles = c(0.5), scale = "width", size = .25, color = "blue", alpha = 0.15, trim = T, adjust = .5)+ ggplot2::geom_errorbar(data = observations, na.rm = T, ggplot2::aes(x = BOX_ID, y = obs.delta, ymin = obs.delta - obs.CI, ymax = obs.delta + obs.CI), color = "red", width = 0, size = .5 )+ ggplot2::geom_point(data = observations, na.rm = T, ggplot2::aes(x = BOX_ID, y = obs.delta), size = 2, shape = 23, color = "black", fill = "red")+ ggplot2::labs(title = "Distributions of simulated isotope compositions", subtitle = box_lists_caption, caption = paste(fit.counts$sims.all, " simulations - ", fit.counts$sims.in.CIfit.param_subsets, " fitted simulations - ", "\n", "Gray shaded violins show the density distributions of all simulated compositions.", "\n", "Blue shaded violins show the density distributions of all CI-fitted predicted compositions.", "\n", "Medians are shown as horizontal bars in violin distributions.", "\n", "Jittered points in background correspond to all simulated compositions predicted by CI-fitting.", "\n", "Red diamonds and error bars show the average and confidence intervals of observed compositions.", sep = ""), x = expression(paste("Observed ", delta^{"i/j"},"X" )))+ ggplot2::scale_y_continuous(labels = dec_2)+ ggplot2::theme(legend.position = "None", axis.title.x = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank(), plot.subtitle = ggplot2::element_text(size = 7) )+ ggplot2::coord_fixed(ratio = 2) return(plot.sim_distrib) } # #_________________________________________________________________________80char #' plot_LS_surfaces_ADSR #' #' @description Plot surfaces of summed squared residuals. #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' #' @return A plot of surfaces of summed squared residuals for each ADSR parameter. #' #' @keywords internal plot_LS_surfaces_ADSR <- function(DF, names.swp.ADSR){ swp.ADSR.name <- swp.ADSR.value <- SSR <- quantile <- Y.0 <- Y.20 <- Y.40 <- Y.60 <- Y.80 <- Y.100 <- Y.min <- Y.max <- Y.1 <- Y.2 <- Y.3 <- Y.4 <- Y.5 <- Y.6 <- Y.7 <- Y.8 <- Y.9 <- Y.10 <- Y.30 <- Y.50 <- Y.70 <- Y.90 <- NULL #### ___ i. with CI fit & parameter_subsets #### DF.melt.CI <- reshape2::melt(DF[DF$in.all.subset_param == TRUE & DF$in.all_fit_boxes.obs.CI == TRUE, ], id.vars = names(DF)[!(names(DF) %in% names.swp.ADSR)], variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") DF.melt.CI.envelope <- DF.melt.CI %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() lt_loc <- 1 size_loc <- 0.25 ribbon.y.min <- .75*10**((log10(min(DF.melt.CI$SSR)))) plot.surface_qp_CI <- ggplot2::ggplot(DF.melt.CI.envelope, mapping = ggplot2::aes(x = swp.ADSR.value, y = Y.0))+ ggplot2::geom_point(DF.melt.CI, mapping = ggplot2::aes(x = swp.ADSR.value, y = SSR), inherit.aes = F, shape = 18, alpha = .1, cex = 0.5)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.0), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.10), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.30), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.50), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.70), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.90), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::facet_wrap(swp.ADSR.name ~ . , scales = "free_x", ncol = round(1.1*length(levels(DF.melt.CI.envelope$swp.ADSR.name))/2))+ ggplot2::theme_linedraw()+ ggplot2::scale_y_log10()+ ggplot2::geom_ribbon(inherit.aes = F, data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, ymin = ribbon.y.min, ymax = Y.min), alpha = .2, fill = "chartreuse3")+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0))+ ggplot2::labs(title = "Fit residuals of CI fitted simulations", caption = paste0(" Fit method: summed squares of residuals.", " \n ", "Green lines show percentiles of distributions, from 0 to 100\u0025." )) # plot.surface_qp_CI #### ___ ii. without CI fit & parameter_subsets #### DF.melt.envelope <- reshape2::melt(DF, id.vars = names(DF)[!(names(DF) %in% names.swp.ADSR)], variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.1 = stats::quantile(SSR, 0.01), Y.2 = stats::quantile(SSR, 0.02), Y.3 = stats::quantile(SSR, 0.03), Y.4 = stats::quantile(SSR, 0.04), Y.5 = stats::quantile(SSR, 0.05), Y.6 = stats::quantile(SSR, 0.06), Y.7 = stats::quantile(SSR, 0.07), Y.8 = stats::quantile(SSR, 0.08), Y.9 = stats::quantile(SSR, 0.09), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() quiet(gc()) lt_loc <- 1 size_loc <- 0.25 ribbon.y.min <- .75*10**((log10(min(DF$SSR)))) plot.surface_qp_all <- ggplot2::ggplot(DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.min))+ ggplot2::geom_linerange(data = DF.melt.envelope, ggplot2::aes(x= swp.ADSR.value, ymin = Y.min, ymax = Y.max), inherit.aes = F, alpha = .1)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.0), #0 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.1), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.2), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.3), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.4), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.5), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.6), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.7), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.8), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.9), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.10), #10 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.30), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.50), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.70), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.90), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::facet_wrap(swp.ADSR.name ~ . , scales = "free_x")+ ggplot2::theme_linedraw()+ ggplot2::scale_y_log10()+ ggplot2::geom_point(data = DF.melt.CI, inherit.aes = F, ggplot2::aes(x = swp.ADSR.value, y = SSR), shape = 18, alpha = 1, color = "red", cex = 0.5)+ ggplot2::geom_ribbon(inherit.aes = F, data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, ymin = ribbon.y.min, ymax = Y.min), alpha = .2, fill = "chartreuse3")+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0))+ ggplot2::labs(title = "Fit residuals of all simulations", caption = paste0(" Fit method: summed squares of residuals.", " \n ", "Green lines show percentiles of distributions, from 0 to 100\u0025.", " \n", " Red dots corresponds to the runs fitted within observed CI and parameter subsets." )) # plot.surface_qp_all # remove(DF.melt, DF.melt.CI, DF.melt.CI.envelope, DF.melt.envelope, lt_loc, size_loc ) return(list(plot.all = plot.surface_qp_all, plot.CI = plot.surface_qp_CI)) } # #_________________________________________________________________________80char #' plot_LS_surfaces_lists #' #' @description Plot surfaces of summed squared residuals. #' #' @param DF fit.final_space data frame #' @param names.swp.lists names of swept list parameters (flux and coeff lists), as vector #' #' @return A plot of surfaces of summed squared residuals for flux lists and coeff lists. #' #' @keywords internal plot_LS_surfaces_lists <- function(DF, names.swp.lists){ names.swp.list.name <- names.swp.list.ID.start_text <- names.swp.list.ID.label <- SSR <- quantile <- Y.min <- Y.max <- Y.0 <- Y.20 <- Y.40 <- Y.60 <- Y.80 <- Y.100 <- Y.1 <- Y.2 <- Y.3 <- Y.4 <- Y.5 <- Y.6 <- Y.7 <- Y.8 <- Y.9 <- Y.10 <- Y.30 <- Y.50 <- Y.70 <- Y.90 <- NULL #### ___ i. with CI fit & param subset #### DF.melt.CI <- reshape2::melt(DF[DF$in.all.subset_param == TRUE & DF$in.all_fit_boxes.obs.CI == TRUE, ], id.vars = names(DF)[!(names(DF) %in% names.swp.lists)], variable.name = "names.swp.list.name", value.name = "names.swp.list.ID") # relabel if lists are numbered names.swp.list.ID <- DF.melt.CI$names.swp.list.ID names.swp.list.ID.end_number <- stringr::str_extract(names.swp.list.ID, "(\\d+$)") if (!any(is.na(names.swp.list.ID.end_number))){ DF.melt.CI$names.swp.list.ID.end_number <- as.numeric(names.swp.list.ID.end_number) DF.melt.CI$names.swp.list.ID.start_text <- gsub("^\\d+|\\d+$", "", names.swp.list.ID) DF.melt.CI$names.swp.list.ID.label <- as.factor(DF.melt.CI$names.swp.list.ID.end_number) x_axis_labels <- DF.melt.CI %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.start_text) %>% dplyr::summarise(n.list = paste(sort(unique(names.swp.list.ID.end_number)), collapse = ", "), .groups = "drop_last") %>% as.data.frame() x_axis_labels <- paste(x_axis_labels$names.swp.list.name, ":", x_axis_labels$names.swp.list.ID.start_text, "(", x_axis_labels$n.list, ")") } else { DF.melt.CI$names.swp.list.ID.label <- DF.melt.CI$names.swp.list.ID x_axis_labels <- "See x axis" } DF.melt.CI.envelope <- DF.melt.CI %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.label) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.1 = stats::quantile(SSR, 0.01), Y.2 = stats::quantile(SSR, 0.02), Y.3 = stats::quantile(SSR, 0.03), Y.4 = stats::quantile(SSR, 0.04), Y.5 = stats::quantile(SSR, 0.05), Y.6 = stats::quantile(SSR, 0.06), Y.7 = stats::quantile(SSR, 0.07), Y.8 = stats::quantile(SSR, 0.08), Y.9 = stats::quantile(SSR, 0.09), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() lt_loc <- 1 size_loc <- 0.25 plot.surface_lists_CI <- ggplot2::ggplot(DF.melt.CI.envelope, ggplot2::aes(x = (names.swp.list.ID.label), y = Y.min))+ ggplot2::geom_linerange(data = DF.melt.CI.envelope, ggplot2::aes(x= (names.swp.list.ID.label), ymin = Y.min, ymax = Y.max), inherit.aes = F, alpha = .1)+ ggplot2::facet_wrap(names.swp.list.name ~ . , scales = "free_x")+ ggplot2::theme_linedraw()+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.0), #0 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.1), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.2), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.3), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.4), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.5), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.6), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.7), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.8), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.9), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.10), #10 # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.30), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.50), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.70), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.90), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_segment(inherit.aes = F, data = DF.melt.CI.envelope, ggplot2::aes(x = names.swp.list.ID.label, xend = names.swp.list.ID.label, y = .1*min(Y.min), yend = Y.min), size = 5, color = "darkgreen", alpha = .7) + # ggplot2::scale_y_log10()+`` ggplot2::scale_y_log10()+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank())+ ggplot2::labs(title = "Fit residuals of CI fitted simulations", x = "list labels", caption = paste0(" Fit method: summed squares of residuals.", "\n ", "Green lines show percentiles of distributions, from 0 to 100\u0025.", "\n ", "x axis labels:", "\n ", paste(x_axis_labels, collapse = "\n ") )) #### ___ ii. without CI fit & param subset #### DF.melt <- reshape2::melt(DF, id.vars = names(DF)[!(names(DF) %in% names.swp.lists)], variable.name = "names.swp.list.name", value.name = "names.swp.list.ID") # relabel if lists are numbered names.swp.list.ID <- DF.melt$names.swp.list.ID names.swp.list.ID.end_number <- stringr::str_extract(names.swp.list.ID, "(\\d+$)") if (!any(is.na(names.swp.list.ID.end_number))){ DF.melt$names.swp.list.ID.end_number <- as.numeric(names.swp.list.ID.end_number) DF.melt$names.swp.list.ID.start_text <- gsub("^\\d+|\\d+$", "", names.swp.list.ID) DF.melt$names.swp.list.ID.label <- as.factor(DF.melt$names.swp.list.ID.end_number) x_axis_labels <- DF.melt %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.start_text) %>% dplyr::summarise(n.list = paste(sort(unique(names.swp.list.ID.end_number)), collapse = ", "), .groups = "drop_last") %>% as.data.frame() x_axis_labels <- paste(x_axis_labels$names.swp.list.name, ":", x_axis_labels$names.swp.list.ID.start_text, "(", x_axis_labels$n.list, ")") } else { DF.melt$names.swp.list.ID.label <- DF.melt$names.swp.list.ID x_axis_labels <- "See x axis" } DF.melt.envelope <- DF.melt %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.label) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.1 = stats::quantile(SSR, 0.01), Y.2 = stats::quantile(SSR, 0.02), Y.3 = stats::quantile(SSR, 0.03), Y.4 = stats::quantile(SSR, 0.04), Y.5 = stats::quantile(SSR, 0.05), Y.6 = stats::quantile(SSR, 0.06), Y.7 = stats::quantile(SSR, 0.07), Y.8 = stats::quantile(SSR, 0.08), Y.9 = stats::quantile(SSR, 0.09), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() lt_loc <- 1 size_loc <- 0.25 plot.surface_lists_all <- ggplot2::ggplot(DF.melt.envelope, ggplot2::aes(x = names.swp.list.ID.label, y = Y.min))+ ggplot2::geom_linerange(data = DF.melt.envelope, ggplot2::aes(x= names.swp.list.ID.label, ymin = Y.min, ymax = Y.max), inherit.aes = F, alpha = .1)+ ggplot2::facet_wrap(names.swp.list.name ~ . , scales = "free_x")+ ggplot2::theme_linedraw()+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.0), #0 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.1), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.2), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.3), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.4), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.5), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.6), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.7), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.8), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.9), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.10), #10 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.30), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.50), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.70), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.90), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_segment(inherit.aes = F, data = DF.melt.envelope, ggplot2::aes(x = names.swp.list.ID.label, xend = names.swp.list.ID.label, y = .1*min(Y.min), yend = Y.min), size = 5, color = "darkgreen", alpha = .7) + ggplot2::geom_point(data = DF.melt.CI, inherit.aes = F, ggplot2::aes(x = names.swp.list.ID.label, y = SSR), shape = 18, alpha = 1, color = "red", cex = 0.5)+ # ggplot2::scale_y_log10()+`` ggplot2::scale_y_log10()+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank())+ ggplot2::labs(title = "Fit residuals of all simulations", x = "list labels", caption = paste0(" Fit method: summed squares of residuals.", "\n ", "Green lines show percentiles of distributions, from 0 to 100\u0025.", "\n ", "Red dots corresponds to the runs fitted within observed CI and parameter subsets.", "\n ", "x axis labels:", "\n ", paste(x_axis_labels, collapse = "\n ") )) return(list(plot.surface_lists_all = plot.surface_lists_all, plot.surface_lists_CI = plot.surface_lists_CI)) } # #_________________________________________________________________________80char #' plot_correlogram_all_CIfit #' #' @description Plot correlogram of CI fitted ADSR parameter values #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' #' @return A correlogram of CI fitted ADSR parameter values #' #' @keywords internal plot_correlogram_all_CIfit <- function(DF, names.swp.ADSR){ X.ID <- Y.ID <- spear.rho <- spear.p <- spear.p.signif <- label.swp.ADSR <- NULL # prepare labels for diagonal of correlograms ADSR_starts_with <- c(paste("swp", c("A", "D", "S", "R"), sep = "."), "custom") decomposed.names.swp.ADSR <- data.frame(names.swp.ADSR = names.swp.ADSR, type.swp.ADSR = NaN, def.swp.ADSR = NaN) decomposed.names.swp.ADSR$def.swp.ADSR <- stringr::str_remove_all(decomposed.names.swp.ADSR$names.swp.ADSR, pattern = paste(paste0(ADSR_starts_with, "."), collapse = "|")) for (j in 1:nrow(decomposed.names.swp.ADSR)){ decomposed.names.swp.ADSR[j, "type.swp.ADSR"] <- stringr::str_remove(decomposed.names.swp.ADSR[j, "names.swp.ADSR"], pattern = paste0(".", decomposed.names.swp.ADSR[j, "def.swp.ADSR"])) } decomposed.names.swp.ADSR$label.swp.ADSR <- paste0(decomposed.names.swp.ADSR$type.swp.ADSR, " \n ", decomposed.names.swp.ADSR$def.swp.ADSR) decomposed.names.swp.ADSR$X.ID <- decomposed.names.swp.ADSR$names.swp.ADSR decomposed.names.swp.ADSR$Y.ID <- decomposed.names.swp.ADSR$names.swp.ADSR decomposed.names.swp.ADSR$label.swp.ADSR <- stringr::str_replace_all(decomposed.names.swp.ADSR$label.swp.ADSR, pattern = "/", replacement = "\n / \n") #### ___ i. prepare data: standardize (center, scale) #### all.ADRS <- DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.all.subset_param == TRUE, c("SSR", names.swp.ADSR)] standardized.all.ADRS <- all.ADRS %>% scale(scale = TRUE, center = TRUE) %>% as.data.frame() %>% dplyr::select_if(~!all(is.na(.))) my_data <- standardized.all.ADRS if (ncol(my_data) >= 3){ # XID_facet_order <- unique(pairs$V1) # YID_facet_order <- unique(pairs$V2) ID_facet_order <- sort(names(my_data), decreasing = T) ID_facet_order <- c(ID_facet_order[!ID_facet_order %in% c("SSR")], "SSR") pairs <- as.data.frame(t(utils::combn(ID_facet_order,2))) for (k1 in 1:nrow(pairs)){ X <- pairs[k1, 1] Y <- pairs[k1,2] if (k1 == 1){ my_data_pairs <- my_data[, c(X,Y)] my_data_pairs$X.ID <- X my_data_pairs$Y.ID <- Y names(my_data_pairs) <- c("X", "Y", "X.ID", "Y.ID") my_data_pairs <- my_data_pairs[,c("X.ID","X", "Y.ID", "Y")] } else { my_data_pairs.loc <- my_data[, c(X,Y)] my_data_pairs.loc$X.ID <- X my_data_pairs.loc$Y.ID <- Y names(my_data_pairs.loc) <- c("X", "Y", "X.ID", "Y.ID") my_data_pairs.loc <- my_data_pairs.loc[,c("X.ID","X", "Y.ID", "Y")] my_data_pairs <- dplyr::bind_rows(my_data_pairs, my_data_pairs.loc) } } my_data_pairs$X.ID <- as.factor(my_data_pairs$X.ID) my_data_pairs$Y.ID <- as.factor(my_data_pairs$Y.ID) ## in centered normalized parameter values summary.my_data_pairs <- my_data_pairs %>% dplyr::group_by(X.ID, Y.ID) %>% dplyr::summarise(n = dplyr::n(), spear.rho = stats::cor(X, Y, method = "spearman"), spear.p = stats::cor.test(X, Y, method = "spearman", na.rm = T, exact = F)$p.value, pear.r = stats::cor(X, Y, method = "pearson"), pear.p = stats::cor.test(X, Y, method = "pearson")$p.value, .groups = "drop_last" ) %>% as.data.frame() summary.my_data_pairs[, c("spear.p.signif", "pear.p.signif")] <- significance_pval_df(summary.my_data_pairs[, c("spear.p", "pear.p")]) my_data_pairs <- dplyr::right_join(my_data_pairs, summary.my_data_pairs, by = c("X.ID", "Y.ID")) # my_data_pairs$X.ID = factor(my_data_pairs$X.ID, levels = XID_facet_order) # my_data_pairs$Y.ID = factor(my_data_pairs$Y.ID, levels = YID_facet_order) XY_labels <- decomposed.names.swp.ADSR[,c("X.ID", "Y.ID", "label.swp.ADSR")] XY_labels[nrow(XY_labels)+1, ] <- "SSR" names(summary.my_data_pairs)[names(summary.my_data_pairs) %in% c("X.ID", "Y.ID")] <- c("Y.ID", "X.ID") Y.max <- ceiling(max(abs(my_data_pairs$Y))) X.max <- ceiling(max(abs(my_data_pairs$X))) XY_labels <- XY_labels[XY_labels$X.ID %in% unique(c(as.character(unique(my_data_pairs$X.ID)), as.character(unique(my_data_pairs$Y.ID)))), ] #### ___ ii. plot correlations qp within CI fitted & param subset #### distinct.my_data_pairs <- my_data_pairs %>% dplyr::distinct() plot.correlogram.CI_fit <- ggplot2::ggplot(data = my_data_pairs, ggplot2::aes(x = X, y = Y ))+ ggplot2::geom_point(inherit.aes = F, data = summary.my_data_pairs, shape = 15, ggplot2::aes(x = 0, y = 0, color = abs(spear.rho), size = abs(spear.rho), alpha = (-log10(spear.p)/max(-log10(my_data_pairs$spear.p[my_data_pairs$spear.p!=0])))))+ ggplot2::scale_size_continuous(range = c(1,18))+ ggplot2::scale_colour_gradient(low = "white", high = "orange")+ ggplot2::scale_fill_gradient(low = "white", high = "black")+ # ggplot2::geom_point(data = distinct.my_data_pairs, # shape = 21, # stroke = 0, # color = "black", # fill = "black" # )+ ggplot2::geom_bin2d()+ ggplot2::stat_smooth(method = "loess", se = F, formula = "y ~ x", size = .5, ggplot2::aes(alpha = abs(spear.rho)) )+ ggplot2::labs(title = "Full correlogram", subtitle = "for all CI-fitted quantitative parameters and SSR (sums of squared residuals)", caption = paste("Statistics are Spearman absolute rho (size and color of central square) and p-value significance.", " \n", "Blue line is smooth loess method.", sep = "" ) )+ # egg::theme_article()+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", strip.text.x = ggplot2::element_blank(), strip.text.y = ggplot2::element_blank(), axis.title = ggplot2::element_blank(), axis.text = ggplot2::element_blank(), axis.ticks = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), panel.grid.minor = ggplot2::element_blank() )+ ggplot2::facet_grid( factor(Y.ID, levels = ID_facet_order) ~ factor(X.ID, levels = ID_facet_order))+ ggplot2::geom_text(data = summary.my_data_pairs, ggplot2::aes(x = 0, y = .7*Y.max, label = spear.p.signif), hjust = 0.5, vjust = 0)+ ggplot2::geom_text(data = summary.my_data_pairs, ggplot2::aes(x = 0, y = -.8*Y.max, label = paste("|rho| =", dec_n(abs(spear.rho), 3))), size = 2, hjust = 0.5, vjust = 0.5)+ ggplot2::scale_y_continuous(limits = c(-Y.max,Y.max))+ ggplot2::scale_x_continuous(limits = c(-X.max,X.max))+ ggplot2::geom_text(inherit.aes = F, data = XY_labels, ggplot2::aes(x = 0, y = 0, label = label.swp.ADSR), vjust = 0.5, size = 3) # plot.correlogram.CI_fit return(plot.correlogram.CI_fit) } } # #_________________________________________________________________________80char #' plot_lda #' #' @description Plot linear discriminant analysis by quartiles of summed squared residuals for all ADSR parameters #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' #' @return A linear discriminant analysis by quartiles of summed squared residuals for all ADSR parameters #' #' @keywords internal plot_lda <- function(DF, names.swp.ADSR){ ..level.. <- LD2 <- LD1 <- SSR <- NULL all.ADRS <- DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.all.subset_param == TRUE, c("SSR", names.swp.ADSR)] standardized.all.ADRS <- all.ADRS %>% scale(center = TRUE, scale = TRUE) %>% as.data.frame() %>% dplyr::select_if(~!all(is.na(.))) if (ncol(standardized.all.ADRS) >= 4){ dat <- standardized.all.ADRS names(dat) <- stringr::str_replace_all(names(dat), pattern = "/", replacement = "_") dat_num_vars <- names(dat) lda_dat_num_vars <- dat_num_vars[!dat_num_vars %in% "SSR"] dat <- dat %>% dplyr::mutate(cut=cut(include.lowest = T, SSR, breaks = as.vector(stats::quantile(dat$SSR)), labels = c("SSR 0-25\u0025","SSR 25-50\u0025","SSR 50-75\u0025", "SSR 75-100\u0025"))) lda_dat_num_vars <- dat_num_vars[!dat_num_vars %in% "SSR"] linear <- MASS::lda(cut ~ ., dat[, c(lda_dat_num_vars, "cut")]) Proportion_of_trace <- linear$svd^2/sum(linear$svd^2) lda_plot <- cbind(dat[, c(dat_num_vars, "cut")], stats::predict(linear, dat[, c(dat_num_vars, "cut")])$x) # define data to plot col<- grDevices::colorRampPalette(c("chartreuse2", "brown1"))(4) cols <- c("SSR 0-25\u0025" = col[1], "SSR 25-50\u0025" = col[2], "SSR 50-75\u0025" = col[3], "SSR 75-100\u0025" = col[4]) # circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){ # r = diameter / 2 # tt <- seq(0,2*pi,length.out = npoints) # xx <- center[1] + r * cos(tt) # yy <- center[2] + r * sin(tt) # return(data.frame(x = xx, y = yy)) # } # circ <- circleFun(c(0,0), 2*max(abs(linear$scaling[,1:2])) ,npoints = 500) if (nrow(lda_plot) <= 1000 ){ plot.lda <- ggplot2::ggplot(lda_plot, ggplot2::aes(LD1, LD2, color = cut)) + ggplot2::geom_point() } else { plot.lda <- ggplot2::ggplot(lda_plot, ggplot2::aes(LD1, LD2, color = cut)) + ggplot2::stat_density_2d(color = NA, geom = "polygon", ggplot2::aes(alpha = ..level.., fill = cut)) } plot.lda <- plot.lda + ggplot2::stat_ellipse(geom="polygon", ggplot2::aes(fill = cut), # fill = NA, alpha = 0.2, show.legend = FALSE, level = .5)+ # egg::theme_article()+ ggplot2::theme_classic()+ # ggforce::geom_mark_hull(alpha = 0.1, # expand = .001, # linetype = 2, # radius = 0, # concavity = 10, # con.cap = 1)+ ggplot2::scale_color_manual(values = cols) + ggplot2::scale_fill_manual(values = cols) + ggplot2::geom_segment(data = as.data.frame(linear$scaling), ggplot2::aes(x = 0, xend = LD1, y = 0, yend = LD2), arrow = ggplot2::arrow(length = ggplot2::unit(0.025, "npc"), type = "open"), lwd = 1, color = "black", inherit.aes = F) + ggrepel::geom_label_repel(data = as.data.frame(linear$scaling), ggplot2::aes(x = LD1*1.3, y = LD2*1.3, label = lda_dat_num_vars), # check_overlap = F, force = 1, size = 3, label.size = NA, fill = NA, inherit.aes = F)+ ggplot2::labs(x = paste0("LD 1 (", dec_n(100*Proportion_of_trace[1], 2), "\u0025)"), y = paste0("LD 2 (", dec_n(100*Proportion_of_trace[2], 2), "\u0025)"), title = "Linear discriminant analysis of quantitative parameters for least squares best fits", caption = paste0("SSR categories correspond to inter-quantiles groups of the sum of squared residuals (SSR).", "\n", "Ellipses show 50\u0025 distribution."))+ ggplot2::theme(legend.position = "bottom", plot.caption = ggplot2::element_text(hjust = 0) ) plot.lda } else { rlang::inform("\U2139 Not enough continuous parameters for Linear Discriminant Analysis.") } }
/R/plots_fit_final_space.R
no_license
cran/isobxr
R
false
false
82,673
r
# #_________________________________________________________________________80char #' plot_freq_ADSR #' #' @description Plot frequency profiles by fitted parameter of ADSR types #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' @param parameter_subsets parameter subsets passed from fit.final_space #' #' @return A frequency plot of fitted parameter values. #' #' @keywords internal plot_freq_ADSR <- function(DF, names.swp.ADSR, parameter_subsets){ . <- in.all.subset_param <- n <- swp.ADSR.value <- swp.ADSR.name <- label <- swp.center <- swp.2se <- swp.mean <- swp.50 <- swp.75 <- swp.25 <- swp.95 <- swp.05 <- freq.in <- swp.2sd <- NULL names.parameter_subsets <- names(parameter_subsets) ##### ___ i. qp freq calculation / parameter within CI & within parameter subsets ###### if (!is.null(names.parameter_subsets) & any(names.parameter_subsets %in% names.swp.ADSR)){ DF.swp.ADSR <- DF %>% dplyr::group_by( dplyr::across(names.swp.ADSR)) %>% dplyr::select(dplyr::all_of(names.swp.ADSR)) %>% as.data.frame() %>% reshape2::melt(id.vars = NULL, variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(swp.ADSR.value = unique(swp.ADSR.value), .groups = "drop_last") %>% as.data.frame() swp.ADSR.subset_range <- as.data.frame(parameter_subsets[names(parameter_subsets) %in% names.swp.ADSR]) DF.swp.ADSR$in.parameter_subsets <- TRUE for (i in 1:ncol(swp.ADSR.subset_range)){ swp.ADSR_loc <- names(swp.ADSR.subset_range)[i] DF.swp.ADSR[DF.swp.ADSR$swp.ADSR.name == swp.ADSR_loc & DF.swp.ADSR$swp.ADSR.value < min(swp.ADSR.subset_range[,swp.ADSR_loc]) , "in.parameter_subsets"] <- FALSE DF.swp.ADSR[DF.swp.ADSR$swp.ADSR.name == swp.ADSR_loc & DF.swp.ADSR$swp.ADSR.value > max(swp.ADSR.subset_range[,swp.ADSR_loc]) , "in.parameter_subsets"] <- FALSE } } # remove(swp.ADSR_loc) molten.DF.CI_fitted <- reshape2::melt(DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.all.subset_param == TRUE, c(names.swp.ADSR)], id.vars = NULL, variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") freq.molten.DF.CI_fitted <- molten.DF.CI_fitted %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% dplyr::mutate(freq = 100*n/sum(n)) %>% as.data.frame() molten.DF <- reshape2::melt(DF[, c(names.swp.ADSR, "in.all.subset_param")], id.vars = "in.all.subset_param", variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") freq.molten.DF <- molten.DF %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% dplyr::mutate(freq = 100*n/sum(n)) %>% as.data.frame() freq.molten <- dplyr::full_join(freq.molten.DF, freq.molten.DF.CI_fitted, by = c("swp.ADSR.name", "swp.ADSR.value"), suffix = c(".all", ".in")) freq.molten$freq.in.vs.all <- 100*freq.molten$n.in/freq.molten$n.all cropped_param_values <- molten.DF %>% dplyr::filter(swp.ADSR.name %in% names(parameter_subsets)) %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value, in.all.subset_param) %>% dplyr::count() %>% as.data.frame() cropped_param_values.TRUE <- cropped_param_values %>% dplyr::filter(in.all.subset_param == TRUE) %>% dplyr::select(swp.ADSR.name, swp.ADSR.value, in.all.subset_param) cropped_param_values <- cropped_param_values %>% dplyr::select(swp.ADSR.name, swp.ADSR.value) %>% dplyr::distinct() cropped_param_values <- dplyr::full_join(cropped_param_values, cropped_param_values.TRUE, by = c("swp.ADSR.name", "swp.ADSR.value") ) cropped_param_values <- cropped_param_values %>% replace(is.na(.), FALSE) freq.molten <- freq.molten %>% replace(is.na(.), 0) freq.molten <- dplyr::full_join(freq.molten, cropped_param_values, by = c("swp.ADSR.name", "swp.ADSR.value")) freq.molten <- freq.molten %>% replace(is.na(.), TRUE) param.min_max <- freq.molten %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(full_range.min = min(swp.ADSR.value), full_range.max = max(swp.ADSR.value), .groups = "drop_last") %>% as.data.frame() stats.molten.DF.CI_fitted <- molten.DF.CI_fitted %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(n = dplyr::n(), swp.min = min(swp.ADSR.value, na.rm = T), swp.max = max(swp.ADSR.value, na.rm = T), swp.05 = stats::quantile(swp.ADSR.value, .05), swp.25 = stats::quantile(swp.ADSR.value, .25), swp.50 = stats::quantile(swp.ADSR.value, .5), swp.75 = stats::quantile(swp.ADSR.value, .75), swp.95 = stats::quantile(swp.ADSR.value, .95), swp.mean = mean(swp.ADSR.value, na.rm = T), swp.2sd = 2*stats::sd(swp.ADSR.value, na.rm = T), swp.2se = swp.2sd/sqrt(n) , .groups = "drop_last") %>% as.data.frame() center.swp.param <- molten.DF %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::summarise(swp.center = min(swp.ADSR.value, na.rm = T)+.5*(max(swp.ADSR.value, na.rm = T)-min(swp.ADSR.value, na.rm = T)), .groups = "drop_last") %>% as.data.frame() stats.molten.DF.CI_fitted <- dplyr::full_join(stats.molten.DF.CI_fitted, center.swp.param, by = "swp.ADSR.name") stats.molten.DF.CI_fitted <- dplyr::full_join(stats.molten.DF.CI_fitted, param.min_max, by = "swp.ADSR.name") stats.molten.DF.CI_fitted$mag_order <- round(-log10(stats.molten.DF.CI_fitted$full_range.max-stats.molten.DF.CI_fitted$full_range.min)) stats.molten.DF.CI_fitted[stats.molten.DF.CI_fitted$mag_order < 0, "mag_order"] <- 0 stats.molten.DF.CI_fitted[stats.molten.DF.CI_fitted$mag_order == Inf, "mag_order"] <- 0 stats.molten.DF.CI_fitted$label <- paste0(dec_n(stats.molten.DF.CI_fitted$swp.mean, stats.molten.DF.CI_fitted$mag_order+2), " \u00B1 ", dec_n(.5*stats.molten.DF.CI_fitted$swp.2sd, stats.molten.DF.CI_fitted$mag_order+2), " (", dec_n(stats.molten.DF.CI_fitted$swp.2se, stats.molten.DF.CI_fitted$mag_order+2), ")" ) max.freq.molten <- freq.molten %>% dplyr::group_by(swp.ADSR.name) %>% dplyr::filter(freq.in == max(freq.in)) %>% dplyr::arrange (swp.ADSR.name, swp.ADSR.value, freq.in) %>% as.data.frame() stats.molten.DF.CI_fitted.max <- dplyr::full_join(stats.molten.DF.CI_fitted, max.freq.molten[, c("swp.ADSR.name", "swp.ADSR.value", "freq.in")], by = "swp.ADSR.name") stats.molten.DF.CI_fitted.max$freq_max.label <- paste0(dec_n(stats.molten.DF.CI_fitted.max$swp.ADSR.value, stats.molten.DF.CI_fitted.max$mag_order+2)) remove(molten.DF, center.swp.param, cropped_param_values, cropped_param_values.TRUE, freq.molten.DF.CI_fitted, freq.molten.DF, max.freq.molten, param.min_max) quiet(gc()) ##### ___ ii. plot qp CI fit frequencies #### boxplot_y <- -5 mean_y <- -11 annotation_y <- -20 lower_border_y <- -20 plot.freq_ADSR <- ggplot2::ggplot(freq.molten, ggplot2::aes(x = swp.ADSR.value, y = freq.in, color = swp.ADSR.name, fill = swp.ADSR.name))+ ggplot2::geom_hline(linetype = 1, size = .25, yintercept = 0)+ ggplot2::geom_rect(ggplot2::aes(xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 0), fill = "gray95", color =NA)+ # ggplot2::geom_point(size = 1, alpha = 1)+ # ggplot2::geom_area(data = freq.molten[freq.molten$in.all.subset_param == TRUE, ], # alpha = .25)+ ggplot2::geom_linerange(ggplot2::aes(ymin = 0, ymax = freq.in), size = 2, linetype = 1)+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), plot.caption = ggplot2::element_text(hjust = 0), strip.text = ggplot2::element_text(face="bold"), panel.grid = ggplot2::element_blank() # plot.title.position = "plot", #NEW parameter. Apply for subtitle too. # plot.caption.position = "plot" )+ ggplot2::facet_wrap(. ~ swp.ADSR.name, scales = "free_x", ncol = round(1.1*length(levels(freq.molten$swp.ADSR.name))/2) )+ ggplot2::labs(title = "Frequency distributions of CI fitted quantitative parameter ", y = "frequence of runs within observed CIs of all boxes (\u0025)", x = "sweeped parameter values", caption = paste(#"Proportion of fits:", dec_n(fraction_of_fitting_sim, 1), "\u0025", "Upper part: Frequence curves with parameter value of maximum frequence.", " \n", "Lower part: (up) Horizontal distribution boxplot (5, 25, 50, 75, 95\u0025) with median (IQR); ", "(mid) Horizontal mean with 1sd and 2se error bar; ", "\n", "(down) Value of mean \u00B1 1sd (2se).", "\n", "Crosses mark values standing outside a parameter subset.", sep = "") )+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, # boxplot / 2SD / 2SE inherit.aes = F, ggplot2::aes(y = boxplot_y, xmin = swp.05, xmax = swp.95, color = swp.ADSR.name), size = 1, alpha = 1, height = 0)+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, inherit.aes = F, ggplot2::aes(y = boxplot_y, xmin = swp.25, xmax = swp.75, color = swp.ADSR.name), size = 3, alpha = 1, height = 0)+ ggplot2::geom_point(data = stats.molten.DF.CI_fitted, ggplot2::aes(y = boxplot_y, x = swp.50), color = "black", size = 2, shape = 24)+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, # mean / 2SD / 2SE inherit.aes = F, ggplot2::aes(y = mean_y, xmin = swp.mean-.5*swp.2sd, xmax = swp.mean+.5*swp.2sd, color = swp.ADSR.name), size = 1, alpha = 1, height = 0)+ ggplot2::geom_errorbarh(data = stats.molten.DF.CI_fitted, inherit.aes = F, ggplot2::aes(y = mean_y, xmin = swp.mean-swp.2se, xmax = swp.mean+swp.2se, color = swp.ADSR.name), size = 3, alpha = 1, height = 0)+ ggplot2::geom_point(data = stats.molten.DF.CI_fitted, ggplot2::aes(y = mean_y, x = swp.mean), color = "black", size = 2, shape = 25)+ ggplot2::geom_text(data = stats.molten.DF.CI_fitted, ggplot2::aes(x = swp.center, y = annotation_y, hjust = 0.5, vjust = 0, label = label), size = 3)+ ggplot2::scale_y_continuous(limits=c(lower_border_y, 100), breaks=seq(0, 100, by = 10))+ ggplot2::coord_cartesian(ylim = c(lower_border_y, 1.0*max(freq.molten$freq.in))) # ggrepel::geom_label_repel(data = stats.molten.DF.CI_fitted.max, # fill = "white", # nudge_y = 15, # vjust = 0, # direction = c("y"), # # hjust = 0, # size = 2.5, # angle = 45, # segment.linetype = 3, # label.size = NA, # ggplot2::aes(x = swp.ADSR.value, # y = freq.in, # label = freq_max.label)) if (exists("DF.swp.ADSR")){ plot.freq_ADSR <- plot.freq_ADSR + ggplot2::geom_point(inherit.aes = F, data = DF.swp.ADSR[DF.swp.ADSR$in.parameter_subsets == FALSE, ], ggplot2::aes(x = swp.ADSR.value, y = 0), shape = 4, size = 2, color = "black" ) } freq.molten.export <- freq.molten[,c("swp.ADSR.name", "in.all.subset_param", "swp.ADSR.value", "freq.in", "n.all", "n.in")] names(freq.molten.export) <- c("Quantitative parameter", "Manually subset", "Parameter value", "Frequence in CI-fit (\u0025)", "n all simulations", "n CI-fitted simulations") stats.report <- stats.molten.DF.CI_fitted return(list(plot = plot.freq_ADSR, stats = stats.molten.DF.CI_fitted, freqs = stats.report)) } # #_________________________________________________________________________80char #' plot_freq_flux #' #' @description Plot frequency profiles by fitted flux lists #' #' @param DF fit.final_space data frame #' @param parameter_subsets fitted flux lists subsets passed from fit.final_space #' #' @return A frequency plot of fitted parameter values. #' #' @keywords internal plot_freq_flux <- function(DF, parameter_subsets){ in.subset.swp.flux_list_name <- freq.in <- . <- n <- in.all_fit_boxes.obs.CI <- in.all.subset_param <- swp.flux_list_name <- NULL names.parameter_subsets <- names(parameter_subsets) DF.flux_counts.all <- DF %>% dplyr::group_by(swp.flux_list_name) %>% dplyr::summarise(n.all = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.flux_counts.in_out <- DF %>% dplyr::filter(in.all.subset_param == TRUE) %>% dplyr::group_by(swp.flux_list_name, in.all_fit_boxes.obs.CI) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.flux_freq.in <- DF.flux_counts.in_out[DF.flux_counts.in_out$in.all_fit_boxes.obs.CI == TRUE, ] %>% dplyr::mutate(freq.in = 100*n/sum(n)) %>% as.data.frame() DF.flux_freq.out <- DF.flux_counts.in_out[DF.flux_counts.in_out$in.all_fit_boxes.obs.CI == FALSE, ] %>% dplyr::mutate(freq.out = 100*n/sum(n)) %>% as.data.frame() DF.flux_freq <- dplyr::full_join(DF.flux_freq.in, DF.flux_freq.out, by = "swp.flux_list_name", suffix = c(".in", ".out")) DF.flux_freq <- dplyr::full_join(DF.flux_counts.all, DF.flux_freq, by = "swp.flux_list_name", suffix = c(".all", "")) DF.flux_freq <- DF.flux_freq %>% replace(is.na(.), 0) plot.freq_flux <- ggplot2::ggplot(DF.flux_freq, ggplot2::aes(x = swp.flux_list_name, y = freq.in, label= swp.flux_list_name))+ ggplot2::geom_col(size = 1, alpha =.25, fill = "red")+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", # axis.title.y = ggplot2::element_blank(), axis.ticks.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_blank(), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0) )+ ggplot2::geom_text(ggplot2::aes(x = swp.flux_list_name, y = 0), hjust = 0, size = 2)+ ggplot2::labs(title = "Frequency distribution of CI fitted flux lists", y = "frequence of fit within all CIs (\u0025)", x = "flux list name")+ ggplot2::coord_flip() if (!is.null(names.parameter_subsets) & "swp.flux_list_name" %in% names.parameter_subsets){ DF.flux_counts.parameter_subsets <- DF %>% dplyr::group_by(swp.flux_list_name, in.subset.swp.flux_list_name) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() if (nrow(DF.flux_counts.parameter_subsets[DF.flux_counts.parameter_subsets$in.subset.swp.flux_list_name == FALSE, ]) > 0){ plot.freq_flux <- plot.freq_flux + ggplot2::geom_point(inherit.aes = F, data = DF.flux_counts.parameter_subsets[DF.flux_counts.parameter_subsets$in.subset.swp.flux_list_name == FALSE, ], ggplot2::aes(x = swp.flux_list_name, y = -2), shape = 4, size = 2, color = "black") + ggplot2::labs(caption = "Crosses mark values standing outside a parameter subset.") } } DF.flux_freq.export <- DF.flux_freq[, c("swp.flux_list_name", "freq.in", "n.all", "n.in")] names(DF.flux_freq.export) <- c("Flux list name", "Frequence in CI-fit (\u0025)", "n all simulations", "n CI-fitted simulations" ) return(list(plot = plot.freq_flux, freqs = DF.flux_freq.export)) } # #_________________________________________________________________________80char #' plot_freq_coeff #' #' @description Plot frequency profiles by fitted coeff lists #' #' @param DF fit.final_space data frame #' @param parameter_subsets fitted coeff lists subsets passed from fit.final_space #' #' @return A frequency plot of fitted parameter values. #' #' @keywords internal plot_freq_coeff <- function(DF, parameter_subsets){ in.subset.swp.coeff_list_name <- freq.in <- . <- n <- in.all_fit_boxes.obs.CI <- in.all.subset_param <- swp.coeff_list_name <- NULL names.parameter_subsets <- names(parameter_subsets) DF.coeff_counts.all <- DF %>% dplyr::group_by(swp.coeff_list_name) %>% dplyr::summarise(n.all = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.coeff_counts.in_out <- DF %>% dplyr::filter(in.all.subset_param == TRUE) %>% dplyr::group_by(swp.coeff_list_name, in.all_fit_boxes.obs.CI) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() DF.coeff_freq.in <- DF.coeff_counts.in_out[DF.coeff_counts.in_out$in.all_fit_boxes.obs.CI == TRUE, ] %>% dplyr::mutate(freq.in = 100*n/sum(n)) %>% as.data.frame() DF.coeff_freq.out <- DF.coeff_counts.in_out[DF.coeff_counts.in_out$in.all_fit_boxes.obs.CI == FALSE, ] %>% dplyr::mutate(freq.out = 100*n/sum(n)) %>% as.data.frame() DF.coeff_freq <- dplyr::full_join(DF.coeff_freq.in, DF.coeff_freq.out, by = "swp.coeff_list_name", suffix = c(".in", ".out")) DF.coeff_freq <- dplyr::full_join(DF.coeff_counts.all, DF.coeff_freq, by = "swp.coeff_list_name", suffix = c(".all", "")) DF.coeff_freq <- DF.coeff_freq %>% replace(is.na(.), 0) plot.freq_coeff <- ggplot2::ggplot(DF.coeff_freq, ggplot2::aes(x = swp.coeff_list_name, y = freq.in, label= swp.coeff_list_name))+ ggplot2::geom_col(size = 1, alpha =.25, fill = "red")+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", # axis.title.y = ggplot2::element_blank(), axis.ticks.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_blank(), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot" )+ ggplot2::geom_text(ggplot2::aes(x = swp.coeff_list_name, y = 0), hjust = 0)+ ggplot2::labs(title = "Frequency distribution of CI fitted coeff. lists", y = "frequence of fit within all CIs (\u0025)", x = "coeff list name")+ ggplot2::coord_flip() if (!is.null(names.parameter_subsets) & "swp.coeff_list_name" %in% names.parameter_subsets){ DF.coeff_counts.parameter_subsets <- DF %>% dplyr::group_by(swp.coeff_list_name, in.subset.swp.coeff_list_name) %>% dplyr::summarise(n = dplyr::n(), .groups = 'drop_last') %>% as.data.frame() if (nrow(DF.coeff_counts.parameter_subsets[DF.coeff_counts.parameter_subsets$in.subset.swp.coeff_list_name == FALSE, ]) > 0){ plot.freq_coeff <- plot.freq_coeff + ggplot2::geom_point(inherit.aes = F, data = DF.coeff_counts.parameter_subsets[DF.coeff_counts.parameter_subsets$in.subset.swp.coeff_list_name == FALSE, ], ggplot2::aes(x = swp.coeff_list_name, y = -2), shape = 4, size = 2, color = "black") + ggplot2::labs(caption = "Crosses mark values standing outside a parameter subset.") } } DF.coeff_freq.export <- DF.coeff_freq[, c("swp.coeff_list_name", "freq.in", "n.all", "n.in")] names(DF.coeff_freq.export) <- c("Coeff list name", "Frequence in CI-fit (\u0025)", "n all simulations", "n CI-fitted simulations" ) return(list(plot = plot.freq_coeff, freqs = DF.coeff_freq)) } # #_________________________________________________________________________80char #' plot_sim_obs #' #' @description Plot simulations against observations #' #' @param DF fit.final_space data frame #' @param bx.fit list of boxes fitted and unfitted groups and subgroups passed from fit.final_space #' @param fit.counts counts of simulations by groups passed from fit.final_space #' #' @return A plot of fitted simulated delta values against observations #' #' @keywords internal plot_sim_obs <- function(DF, bx.fit, fit.counts){ X.CI <- Y.75 <- Y.25 <- Y.50 <- Y.max <- Y.min <- ymax <- ymin <- x <- Y <- X <- sim.delta <- obs.CI <- obs.delta <- in.boxes_to_fit <- BOX_ID <- n <- SERIES_RUN_ID <- in.all.subset_param <- in.all_fit_boxes.obs.CI <- NULL run_fit_proportions <- DF %>% dplyr::group_by(in.all_fit_boxes.obs.CI, in.all.subset_param, SERIES_RUN_ID) %>% dplyr::count() %>% as.data.frame() %>% dplyr::count(in.all_fit_boxes.obs.CI, in.all.subset_param) %>% dplyr::summarise(in.all_fit_boxes.obs.CI = in.all_fit_boxes.obs.CI, in.all.subset_param = in.all.subset_param, n = n, freq = 100*n/sum(n), .groups = "drop_last") frac_of_runs_in_CI_parameter_subsets <- run_fit_proportions[run_fit_proportions$in.all_fit_boxes.obs.CI == TRUE & run_fit_proportions$in.all.subset_param == TRUE, "freq"] frac_of_runs_in_CI <- sum(run_fit_proportions[run_fit_proportions$in.all_fit_boxes.obs.CI == TRUE, "freq"]) tot_runs <- sum(run_fit_proportions[ , "n"]) remove(run_fit_proportions) sim_obs.mean <- DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ] %>% dplyr::group_by(BOX_ID, in.boxes_to_fit) %>% dplyr::summarise(X = mean(obs.delta), X.CI = mean(obs.CI), Y = mean(sim.delta), Y.05 = stats::quantile(sim.delta, .05), Y.25 = stats::quantile(sim.delta, .25), Y.50 = stats::quantile(sim.delta, .50), Y.75 = stats::quantile(sim.delta, .75), Y.95 = stats::quantile(sim.delta, .95), Y.min = min(sim.delta, na.rm = T), Y.max = max(sim.delta, na.rm = T), .groups = "drop_last") %>% as.data.frame() sim_obs.mean$X.provided <- FALSE sim_obs.mean[!is.nan(sim_obs.mean$X), "X.provided"] <- TRUE nudge_y.range <- abs(max(DF$sim.delta)-min(DF$sim.delta)) nudge_x.range <- abs(max(DF$obs.delta, na.rm = T)-min(DF$obs.delta, na.rm = T)) # box_lists <- sim_obs.mean %>% # dplyr::group_by(in.boxes_to_fit, X.provided) %>% # dplyr::summarise(boxes = paste0(sort(as.character(BOX_ID)), collapse = ", "), .groups = "drop_last") %>% # as.data.frame() # box_lists$label <- NaN # box_lists[box_lists$in.boxes_to_fit == TRUE & box_lists$X.provided == TRUE, "label"] <- "Targetted: " # box_lists[box_lists$in.boxes_to_fit == FALSE & box_lists$X.provided == TRUE, "label"] <- "Excluded: " # box_lists[box_lists$X.provided == FALSE, "label"] <- "Missing obs.: " # box_lists_caption <- paste0(paste(paste(box_lists$label, box_lists$boxes, sep = ""), # collapse = " \n"), "\n", report.CIfit) # box_lists_caption <- if (all(bx.fit$targetted == bx.fit$targetted_initial)){ list_box_lists_caption <- paste0("Targets : ", paste(bx.fit$targetted, collapse = " - ")) } else { list_box_lists_caption <- paste0("Initial targets : ", paste(bx.fit$targetted_initial, collapse = " - ")) if (length(bx.fit$targetted_no_obs) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Missing obs : ", paste(bx.fit$targetted_no_obs, collapse = " - "))) } if (length(bx.fit$targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Targets : ", paste(bx.fit$targetted, collapse = " - "))) } } if (length(bx.fit$not_targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Not targets : ", paste(bx.fit$not_targetted, collapse = " - "))) } if (length(bx.fit$CI_fit.successful) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Successful fit : ", paste(bx.fit$CI_fit.successful, collapse = " - "))) } if (length(bx.fit$CI_fit.failed) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("No fit : ", paste(bx.fit$CI_fit.failed, collapse = " - "))) } box_lists_caption <- paste(list_box_lists_caption, collapse = "\n") # lm reports lm_report <- corr_stats(data_lm = DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.boxes_to_fit == TRUE & DF$in.all.subset_param == TRUE, ], X = "obs.delta", Y = "sim.delta") %>% as.list() lm_report.text <- paste0("LM (2se): ", " y = ", dec_n(lm_report$pear.slope, 3), " ( \u00B1 ", dec_n(lm_report$pear.slope.2se, 3), " ) * x + ", dec_n(lm_report$pear.yint, 3), " ( \u00B1 ", dec_n(lm_report$pear.yint.2se, 3), " ) ", "\n", "Pear. R2 = ", dec_n(lm_report$pear.R2, 3), " ", lm_report$pear.signif, "; ", "Spear. rho = ", dec_n(lm_report$spear.Rho, 3), " ", lm_report$spear.signif, "\n", "n = ", dec_n(lm_report$n, 0) ) lm_report.text.x = min(sim_obs.mean$X-sim_obs.mean$X.CI, na.rm=T) lm_report.text.y = max(sim_obs.mean$Y.max) linerange <- clear_subset(DF[DF$BOX_ID %in% bx.fit$observed, ]) %>% dplyr::group_by(BOX_ID) %>% dplyr::summarise(x = unique(obs.delta), ymin = min(sim.delta, na.rm = T), ymax = max(sim.delta, na.rm = T), .groups = "drop_last") %>% as.data.frame() plot.sim_obs <- ggplot2::ggplot(data = sim_obs.mean, ggplot2::aes(x = X, y = Y ))+ ggplot2::geom_abline(slope = 1, linetype = 2)+ ggplot2::geom_abline(intercept = lm_report$pear.yint, slope = lm_report$pear.slope, linetype = 1, color = "blue")+ ggplot2::scale_shape_manual(values = c(23, 21))+ ggplot2::geom_linerange(data = linerange, inherit.aes = F, ggplot2::aes(x = x, y = ymin, ymin = ymin, ymax = ymax, color = BOX_ID), linetype = 2, size = 0.25, alpha = 0.5) + # ggplot2::geom_jitter(data = DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & # DF$in.all.subset_param == TRUE & # DF$BOX_ID %in% bx.fit$observed, ], shape = 43, size = 0.2, # ggplot2::aes(x = obs.delta, y = sim.delta, color = BOX_ID), na.rm = T, # width = (max(sim_obs.mean$X + sim_obs.mean$X.CI, na.rm = T) - min(sim_obs.mean$X - sim_obs.mean$X.CI, na.rm = T))/100 )+ # ggplot2::scale_alpha_continuous(range = c(0.1,.5))+ # stat_bin_2d(inherit.aes = F, # data = clear_subset(DF[DF$BOX_ID %in% bx.fit$observed, ]), # ggplot2::aes(x = obs.delta, y = sim.delta, alpha = ..ndensity.., fill = BOX_ID), # bins = 200, na.rm = T)+ ggplot2::geom_errorbar(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes(x = X, ymin = Y.min, ymax = Y.max, color = BOX_ID), size = 1, width = 0)+ ggplot2::geom_errorbar(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes(x = X, y = Y.50, ymin = Y.25, ymax = Y.75, color = BOX_ID), size = 3, width = 0)+ ggplot2::geom_errorbarh(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes( y = Y.50, xmin = X - X.CI, xmax = X + X.CI, color = BOX_ID), size = 1, na.rm = T, height = 0)+ ggplot2::geom_point(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), inherit.aes = F, ggplot2::aes(y = Y.50, x = X, fill = BOX_ID, shape = as.factor(in.boxes_to_fit) ), color = "black", size = 3, na.rm = T )+ ggplot2::theme_linedraw()+ ggplot2::labs(title = "Simulation vs. Observation", subtitle = box_lists_caption, caption = paste(fit.counts$sims.all, " simulations - ", fit.counts$sims.in.CIfit.param_subsets, " fitted simulations - ", fit.counts$sim_delta.fitted_boxes, " fitted delta values", "\n", "Symbols show the medians of fitted boxes (circles) and non fitted boxes (diamonds)", "\n", "Horizontal bars: confidence interval on observations.", "\n", "Dashed light vertical bars: full extant of simulations.","\n", "Solid thin and thick vertical bars: Full and interquartile (25-75\u0025) range of predicted compositions.","\n", "Lines: black dashed line is identity; blue solid line is linear regression of all CI-fitted sim-obs pairs.", sep = ""), x = expression(paste("Observed ", delta^{"i/j"},"X" )), y = expression(paste("Simulated ", delta^{"i/j"},"X" )))+ ggplot2::theme(legend.position = "None", plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank(), plot.subtitle = ggplot2::element_text(size = 7) ) + ggplot2::annotate(geom = "text", x = lm_report.text.x, y = lm_report.text.y, label = lm_report.text, hjust = 0, vjust = 1)+ ggrepel::geom_label_repel(data = clear_subset(sim_obs.mean[sim_obs.mean$BOX_ID %in% bx.fit$observed, ]), # inherit.aes = F, ggplot2::aes(x = X - X.CI, y = Y.50, label = BOX_ID, color = BOX_ID), nudge_y = 0, fill = "white", segment.color = "gray75", nudge_x = -0.09*nudge_x.range)+ ggplot2::scale_x_continuous(labels = dec_2)+ ggplot2::scale_y_continuous(labels = dec_2)+ ggplot2::coord_equal(ylim = c(min(sim_obs.mean$Y.min), max(sim_obs.mean$Y.max))) return(plot.sim_obs) } # #_________________________________________________________________________80char #' plot_sim_distrib #' #' @description Plot distributions of all and fitted simulations #' #' @param DF fit.final_space data frame #' @param fit.counts counts of simulations by groups passed from fit.final_space #' @param observations data frame of observations #' @param bx.fit list of boxes fitted and unfitted groups and subgroups passed from fit.final_space #' #' @return A plot of distributions of all and fitted simulations #' #' @keywords internal plot_sim_distrib <- function(DF, fit.counts, observations, bx.fit){ obs.CI <- obs.delta <- sim.delta.mean <- sim.delta <- BOX_ID <- NULL # box_lists_caption <- if (all(bx.fit$targetted == bx.fit$targetted_initial)){ list_box_lists_caption <- paste0("Targets : ", paste(bx.fit$targetted, collapse = " - ")) } else { list_box_lists_caption <- paste0("Initial targets : ", paste(bx.fit$targetted_initial, collapse = " - ")) if (length(bx.fit$targetted_no_obs) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Missing obs : ", paste(bx.fit$targetted_no_obs, collapse = " - "))) } if (length(bx.fit$targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Targets : ", paste(bx.fit$targetted, collapse = " - "))) } } if (length(bx.fit$not_targetted) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Not targets : ", paste(bx.fit$not_targetted, collapse = " - "))) } if (length(bx.fit$CI_fit.successful) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("Successful fit : ", paste(bx.fit$CI_fit.successful, collapse = " - "))) } if (length(bx.fit$CI_fit.failed) > 0) { list_box_lists_caption <- c(list_box_lists_caption, paste0("No fit : ", paste(bx.fit$CI_fit.failed, collapse = " - "))) } box_lists_caption <- paste(list_box_lists_caption, collapse = "\n") BOX_ID_facet_labels <- DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ] %>% dplyr::group_by(BOX_ID) %>% dplyr::summarise(sim.delta.mean = mean(sim.delta)) %>% dplyr::arrange(sim.delta.mean) %>% as.data.frame() %>% dplyr::select(BOX_ID) %>% as.vector() BOX_ID_facet_labels <- BOX_ID_facet_labels$BOX_ID %>% as.character() fit.limits <- DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ] %>% dplyr::summarise(sim.delta.min = min(sim.delta), sim.delta.max = max(sim.delta)) all_sims.limits <- DF %>% dplyr::summarise(sim.delta.min = min(sim.delta), sim.delta.max = max(sim.delta)) plot.sim_distrib <- ggplot2::ggplot(DF, ggplot2::aes(x = stats::reorder(BOX_ID, obs.delta), y = sim.delta, groups = BOX_ID, # y = ..ndensity.., # y = ..prop.., # fill = BOX_ID # height = stat(density) )) + ggplot2::geom_hline(yintercept = 0, linetype = 2, color = "gray75", size = 0.5)+ ggplot2::theme_linedraw()+ ggplot2::geom_violin(alpha = 1, fill = "gray90", draw_quantiles = c(0.5), scale = "width", color = "black", size = 0.25, trim = T, adjust = .5) + # ggplot2::geom_jitter(data = DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ], # size = .01, color = "blue", alpha = .25, # shape = 46, width = 0.1) + ggplot2::geom_violin(data = DF[DF$in.all_fit_boxes.obs.CI == "TRUE" & DF$in.all.subset_param == TRUE, ], # ggplot2::aes(fill = BOX_ID), fill = "blue", # alpha = 0.5, draw_quantiles = c(0.5), scale = "width", size = .25, color = "blue", alpha = 0.15, trim = T, adjust = .5)+ ggplot2::geom_errorbar(data = observations, na.rm = T, ggplot2::aes(x = BOX_ID, y = obs.delta, ymin = obs.delta - obs.CI, ymax = obs.delta + obs.CI), color = "red", width = 0, size = .5 )+ ggplot2::geom_point(data = observations, na.rm = T, ggplot2::aes(x = BOX_ID, y = obs.delta), size = 2, shape = 23, color = "black", fill = "red")+ ggplot2::labs(title = "Distributions of simulated isotope compositions", subtitle = box_lists_caption, caption = paste(fit.counts$sims.all, " simulations - ", fit.counts$sims.in.CIfit.param_subsets, " fitted simulations - ", "\n", "Gray shaded violins show the density distributions of all simulated compositions.", "\n", "Blue shaded violins show the density distributions of all CI-fitted predicted compositions.", "\n", "Medians are shown as horizontal bars in violin distributions.", "\n", "Jittered points in background correspond to all simulated compositions predicted by CI-fitting.", "\n", "Red diamonds and error bars show the average and confidence intervals of observed compositions.", sep = ""), x = expression(paste("Observed ", delta^{"i/j"},"X" )))+ ggplot2::scale_y_continuous(labels = dec_2)+ ggplot2::theme(legend.position = "None", axis.title.x = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank(), plot.subtitle = ggplot2::element_text(size = 7) )+ ggplot2::coord_fixed(ratio = 2) return(plot.sim_distrib) } # #_________________________________________________________________________80char #' plot_LS_surfaces_ADSR #' #' @description Plot surfaces of summed squared residuals. #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' #' @return A plot of surfaces of summed squared residuals for each ADSR parameter. #' #' @keywords internal plot_LS_surfaces_ADSR <- function(DF, names.swp.ADSR){ swp.ADSR.name <- swp.ADSR.value <- SSR <- quantile <- Y.0 <- Y.20 <- Y.40 <- Y.60 <- Y.80 <- Y.100 <- Y.min <- Y.max <- Y.1 <- Y.2 <- Y.3 <- Y.4 <- Y.5 <- Y.6 <- Y.7 <- Y.8 <- Y.9 <- Y.10 <- Y.30 <- Y.50 <- Y.70 <- Y.90 <- NULL #### ___ i. with CI fit & parameter_subsets #### DF.melt.CI <- reshape2::melt(DF[DF$in.all.subset_param == TRUE & DF$in.all_fit_boxes.obs.CI == TRUE, ], id.vars = names(DF)[!(names(DF) %in% names.swp.ADSR)], variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") DF.melt.CI.envelope <- DF.melt.CI %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() lt_loc <- 1 size_loc <- 0.25 ribbon.y.min <- .75*10**((log10(min(DF.melt.CI$SSR)))) plot.surface_qp_CI <- ggplot2::ggplot(DF.melt.CI.envelope, mapping = ggplot2::aes(x = swp.ADSR.value, y = Y.0))+ ggplot2::geom_point(DF.melt.CI, mapping = ggplot2::aes(x = swp.ADSR.value, y = SSR), inherit.aes = F, shape = 18, alpha = .1, cex = 0.5)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.0), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.10), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.30), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.50), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.70), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.90), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::facet_wrap(swp.ADSR.name ~ . , scales = "free_x", ncol = round(1.1*length(levels(DF.melt.CI.envelope$swp.ADSR.name))/2))+ ggplot2::theme_linedraw()+ ggplot2::scale_y_log10()+ ggplot2::geom_ribbon(inherit.aes = F, data = DF.melt.CI.envelope, ggplot2::aes(x = swp.ADSR.value, ymin = ribbon.y.min, ymax = Y.min), alpha = .2, fill = "chartreuse3")+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0))+ ggplot2::labs(title = "Fit residuals of CI fitted simulations", caption = paste0(" Fit method: summed squares of residuals.", " \n ", "Green lines show percentiles of distributions, from 0 to 100\u0025." )) # plot.surface_qp_CI #### ___ ii. without CI fit & parameter_subsets #### DF.melt.envelope <- reshape2::melt(DF, id.vars = names(DF)[!(names(DF) %in% names.swp.ADSR)], variable.name = "swp.ADSR.name", value.name = "swp.ADSR.value") %>% dplyr::group_by(swp.ADSR.name, swp.ADSR.value) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.1 = stats::quantile(SSR, 0.01), Y.2 = stats::quantile(SSR, 0.02), Y.3 = stats::quantile(SSR, 0.03), Y.4 = stats::quantile(SSR, 0.04), Y.5 = stats::quantile(SSR, 0.05), Y.6 = stats::quantile(SSR, 0.06), Y.7 = stats::quantile(SSR, 0.07), Y.8 = stats::quantile(SSR, 0.08), Y.9 = stats::quantile(SSR, 0.09), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() quiet(gc()) lt_loc <- 1 size_loc <- 0.25 ribbon.y.min <- .75*10**((log10(min(DF$SSR)))) plot.surface_qp_all <- ggplot2::ggplot(DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.min))+ ggplot2::geom_linerange(data = DF.melt.envelope, ggplot2::aes(x= swp.ADSR.value, ymin = Y.min, ymax = Y.max), inherit.aes = F, alpha = .1)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.0), #0 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.1), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.2), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.3), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.4), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.5), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.6), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.7), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.8), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.9), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.10), #10 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.30), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.50), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.70), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.90), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::facet_wrap(swp.ADSR.name ~ . , scales = "free_x")+ ggplot2::theme_linedraw()+ ggplot2::scale_y_log10()+ ggplot2::geom_point(data = DF.melt.CI, inherit.aes = F, ggplot2::aes(x = swp.ADSR.value, y = SSR), shape = 18, alpha = 1, color = "red", cex = 0.5)+ ggplot2::geom_ribbon(inherit.aes = F, data = DF.melt.envelope, ggplot2::aes(x = swp.ADSR.value, ymin = ribbon.y.min, ymax = Y.min), alpha = .2, fill = "chartreuse3")+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), panel.grid = ggplot2::element_blank(), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0))+ ggplot2::labs(title = "Fit residuals of all simulations", caption = paste0(" Fit method: summed squares of residuals.", " \n ", "Green lines show percentiles of distributions, from 0 to 100\u0025.", " \n", " Red dots corresponds to the runs fitted within observed CI and parameter subsets." )) # plot.surface_qp_all # remove(DF.melt, DF.melt.CI, DF.melt.CI.envelope, DF.melt.envelope, lt_loc, size_loc ) return(list(plot.all = plot.surface_qp_all, plot.CI = plot.surface_qp_CI)) } # #_________________________________________________________________________80char #' plot_LS_surfaces_lists #' #' @description Plot surfaces of summed squared residuals. #' #' @param DF fit.final_space data frame #' @param names.swp.lists names of swept list parameters (flux and coeff lists), as vector #' #' @return A plot of surfaces of summed squared residuals for flux lists and coeff lists. #' #' @keywords internal plot_LS_surfaces_lists <- function(DF, names.swp.lists){ names.swp.list.name <- names.swp.list.ID.start_text <- names.swp.list.ID.label <- SSR <- quantile <- Y.min <- Y.max <- Y.0 <- Y.20 <- Y.40 <- Y.60 <- Y.80 <- Y.100 <- Y.1 <- Y.2 <- Y.3 <- Y.4 <- Y.5 <- Y.6 <- Y.7 <- Y.8 <- Y.9 <- Y.10 <- Y.30 <- Y.50 <- Y.70 <- Y.90 <- NULL #### ___ i. with CI fit & param subset #### DF.melt.CI <- reshape2::melt(DF[DF$in.all.subset_param == TRUE & DF$in.all_fit_boxes.obs.CI == TRUE, ], id.vars = names(DF)[!(names(DF) %in% names.swp.lists)], variable.name = "names.swp.list.name", value.name = "names.swp.list.ID") # relabel if lists are numbered names.swp.list.ID <- DF.melt.CI$names.swp.list.ID names.swp.list.ID.end_number <- stringr::str_extract(names.swp.list.ID, "(\\d+$)") if (!any(is.na(names.swp.list.ID.end_number))){ DF.melt.CI$names.swp.list.ID.end_number <- as.numeric(names.swp.list.ID.end_number) DF.melt.CI$names.swp.list.ID.start_text <- gsub("^\\d+|\\d+$", "", names.swp.list.ID) DF.melt.CI$names.swp.list.ID.label <- as.factor(DF.melt.CI$names.swp.list.ID.end_number) x_axis_labels <- DF.melt.CI %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.start_text) %>% dplyr::summarise(n.list = paste(sort(unique(names.swp.list.ID.end_number)), collapse = ", "), .groups = "drop_last") %>% as.data.frame() x_axis_labels <- paste(x_axis_labels$names.swp.list.name, ":", x_axis_labels$names.swp.list.ID.start_text, "(", x_axis_labels$n.list, ")") } else { DF.melt.CI$names.swp.list.ID.label <- DF.melt.CI$names.swp.list.ID x_axis_labels <- "See x axis" } DF.melt.CI.envelope <- DF.melt.CI %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.label) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.1 = stats::quantile(SSR, 0.01), Y.2 = stats::quantile(SSR, 0.02), Y.3 = stats::quantile(SSR, 0.03), Y.4 = stats::quantile(SSR, 0.04), Y.5 = stats::quantile(SSR, 0.05), Y.6 = stats::quantile(SSR, 0.06), Y.7 = stats::quantile(SSR, 0.07), Y.8 = stats::quantile(SSR, 0.08), Y.9 = stats::quantile(SSR, 0.09), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() lt_loc <- 1 size_loc <- 0.25 plot.surface_lists_CI <- ggplot2::ggplot(DF.melt.CI.envelope, ggplot2::aes(x = (names.swp.list.ID.label), y = Y.min))+ ggplot2::geom_linerange(data = DF.melt.CI.envelope, ggplot2::aes(x= (names.swp.list.ID.label), ymin = Y.min, ymax = Y.max), inherit.aes = F, alpha = .1)+ ggplot2::facet_wrap(names.swp.list.name ~ . , scales = "free_x")+ ggplot2::theme_linedraw()+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.0), #0 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.1), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.2), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.3), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.4), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.5), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.6), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.7), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.8), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.9), # color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.10), #10 # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.30), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.50), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.70), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ # ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.90), # color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.CI.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_segment(inherit.aes = F, data = DF.melt.CI.envelope, ggplot2::aes(x = names.swp.list.ID.label, xend = names.swp.list.ID.label, y = .1*min(Y.min), yend = Y.min), size = 5, color = "darkgreen", alpha = .7) + # ggplot2::scale_y_log10()+`` ggplot2::scale_y_log10()+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank())+ ggplot2::labs(title = "Fit residuals of CI fitted simulations", x = "list labels", caption = paste0(" Fit method: summed squares of residuals.", "\n ", "Green lines show percentiles of distributions, from 0 to 100\u0025.", "\n ", "x axis labels:", "\n ", paste(x_axis_labels, collapse = "\n ") )) #### ___ ii. without CI fit & param subset #### DF.melt <- reshape2::melt(DF, id.vars = names(DF)[!(names(DF) %in% names.swp.lists)], variable.name = "names.swp.list.name", value.name = "names.swp.list.ID") # relabel if lists are numbered names.swp.list.ID <- DF.melt$names.swp.list.ID names.swp.list.ID.end_number <- stringr::str_extract(names.swp.list.ID, "(\\d+$)") if (!any(is.na(names.swp.list.ID.end_number))){ DF.melt$names.swp.list.ID.end_number <- as.numeric(names.swp.list.ID.end_number) DF.melt$names.swp.list.ID.start_text <- gsub("^\\d+|\\d+$", "", names.swp.list.ID) DF.melt$names.swp.list.ID.label <- as.factor(DF.melt$names.swp.list.ID.end_number) x_axis_labels <- DF.melt %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.start_text) %>% dplyr::summarise(n.list = paste(sort(unique(names.swp.list.ID.end_number)), collapse = ", "), .groups = "drop_last") %>% as.data.frame() x_axis_labels <- paste(x_axis_labels$names.swp.list.name, ":", x_axis_labels$names.swp.list.ID.start_text, "(", x_axis_labels$n.list, ")") } else { DF.melt$names.swp.list.ID.label <- DF.melt$names.swp.list.ID x_axis_labels <- "See x axis" } DF.melt.envelope <- DF.melt %>% dplyr::group_by(names.swp.list.name, names.swp.list.ID.label) %>% dplyr::summarise(Y.min = min(SSR), Y.max = max(SSR), Y.0 = stats::quantile(SSR, 0), Y.1 = stats::quantile(SSR, 0.01), Y.2 = stats::quantile(SSR, 0.02), Y.3 = stats::quantile(SSR, 0.03), Y.4 = stats::quantile(SSR, 0.04), Y.5 = stats::quantile(SSR, 0.05), Y.6 = stats::quantile(SSR, 0.06), Y.7 = stats::quantile(SSR, 0.07), Y.8 = stats::quantile(SSR, 0.08), Y.9 = stats::quantile(SSR, 0.09), Y.10 = stats::quantile(SSR, 0.1), Y.20 = stats::quantile(SSR, 0.20), Y.30 = stats::quantile(SSR, 0.30), Y.40 = stats::quantile(SSR, 0.40), Y.50 = stats::quantile(SSR, 0.50), Y.60 = stats::quantile(SSR, 0.60), Y.70 = stats::quantile(SSR, 0.70), Y.80 = stats::quantile(SSR, 0.80), Y.90 = stats::quantile(SSR, 0.90), Y.100 = stats::quantile(SSR, 1), .groups = 'drop_last') %>% as.data.frame() lt_loc <- 1 size_loc <- 0.25 plot.surface_lists_all <- ggplot2::ggplot(DF.melt.envelope, ggplot2::aes(x = names.swp.list.ID.label, y = Y.min))+ ggplot2::geom_linerange(data = DF.melt.envelope, ggplot2::aes(x= names.swp.list.ID.label, ymin = Y.min, ymax = Y.max), inherit.aes = F, alpha = .1)+ ggplot2::facet_wrap(names.swp.list.name ~ . , scales = "free_x")+ ggplot2::theme_linedraw()+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.0), #0 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.1), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.2), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.3), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.4), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.5), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.6), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.7), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.8), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.9), color = "chartreuse4", linetype = lt_loc , size = size_loc/2)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.10), #10 color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.20), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.30), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.40), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.50), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.60), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.70), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.80), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.90), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_line(data = DF.melt.envelope, ggplot2::aes(group = 1, x = as.factor(names.swp.list.ID.label), y = Y.100), color = "chartreuse4", linetype = lt_loc , size = size_loc)+ ggplot2::geom_segment(inherit.aes = F, data = DF.melt.envelope, ggplot2::aes(x = names.swp.list.ID.label, xend = names.swp.list.ID.label, y = .1*min(Y.min), yend = Y.min), size = 5, color = "darkgreen", alpha = .7) + ggplot2::geom_point(data = DF.melt.CI, inherit.aes = F, ggplot2::aes(x = names.swp.list.ID.label, y = SSR), shape = 18, alpha = 1, color = "red", cex = 0.5)+ # ggplot2::scale_y_log10()+`` ggplot2::scale_y_log10()+ ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot", plot.caption = ggplot2::element_text(hjust = 0), panel.grid = ggplot2::element_blank())+ ggplot2::labs(title = "Fit residuals of all simulations", x = "list labels", caption = paste0(" Fit method: summed squares of residuals.", "\n ", "Green lines show percentiles of distributions, from 0 to 100\u0025.", "\n ", "Red dots corresponds to the runs fitted within observed CI and parameter subsets.", "\n ", "x axis labels:", "\n ", paste(x_axis_labels, collapse = "\n ") )) return(list(plot.surface_lists_all = plot.surface_lists_all, plot.surface_lists_CI = plot.surface_lists_CI)) } # #_________________________________________________________________________80char #' plot_correlogram_all_CIfit #' #' @description Plot correlogram of CI fitted ADSR parameter values #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' #' @return A correlogram of CI fitted ADSR parameter values #' #' @keywords internal plot_correlogram_all_CIfit <- function(DF, names.swp.ADSR){ X.ID <- Y.ID <- spear.rho <- spear.p <- spear.p.signif <- label.swp.ADSR <- NULL # prepare labels for diagonal of correlograms ADSR_starts_with <- c(paste("swp", c("A", "D", "S", "R"), sep = "."), "custom") decomposed.names.swp.ADSR <- data.frame(names.swp.ADSR = names.swp.ADSR, type.swp.ADSR = NaN, def.swp.ADSR = NaN) decomposed.names.swp.ADSR$def.swp.ADSR <- stringr::str_remove_all(decomposed.names.swp.ADSR$names.swp.ADSR, pattern = paste(paste0(ADSR_starts_with, "."), collapse = "|")) for (j in 1:nrow(decomposed.names.swp.ADSR)){ decomposed.names.swp.ADSR[j, "type.swp.ADSR"] <- stringr::str_remove(decomposed.names.swp.ADSR[j, "names.swp.ADSR"], pattern = paste0(".", decomposed.names.swp.ADSR[j, "def.swp.ADSR"])) } decomposed.names.swp.ADSR$label.swp.ADSR <- paste0(decomposed.names.swp.ADSR$type.swp.ADSR, " \n ", decomposed.names.swp.ADSR$def.swp.ADSR) decomposed.names.swp.ADSR$X.ID <- decomposed.names.swp.ADSR$names.swp.ADSR decomposed.names.swp.ADSR$Y.ID <- decomposed.names.swp.ADSR$names.swp.ADSR decomposed.names.swp.ADSR$label.swp.ADSR <- stringr::str_replace_all(decomposed.names.swp.ADSR$label.swp.ADSR, pattern = "/", replacement = "\n / \n") #### ___ i. prepare data: standardize (center, scale) #### all.ADRS <- DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.all.subset_param == TRUE, c("SSR", names.swp.ADSR)] standardized.all.ADRS <- all.ADRS %>% scale(scale = TRUE, center = TRUE) %>% as.data.frame() %>% dplyr::select_if(~!all(is.na(.))) my_data <- standardized.all.ADRS if (ncol(my_data) >= 3){ # XID_facet_order <- unique(pairs$V1) # YID_facet_order <- unique(pairs$V2) ID_facet_order <- sort(names(my_data), decreasing = T) ID_facet_order <- c(ID_facet_order[!ID_facet_order %in% c("SSR")], "SSR") pairs <- as.data.frame(t(utils::combn(ID_facet_order,2))) for (k1 in 1:nrow(pairs)){ X <- pairs[k1, 1] Y <- pairs[k1,2] if (k1 == 1){ my_data_pairs <- my_data[, c(X,Y)] my_data_pairs$X.ID <- X my_data_pairs$Y.ID <- Y names(my_data_pairs) <- c("X", "Y", "X.ID", "Y.ID") my_data_pairs <- my_data_pairs[,c("X.ID","X", "Y.ID", "Y")] } else { my_data_pairs.loc <- my_data[, c(X,Y)] my_data_pairs.loc$X.ID <- X my_data_pairs.loc$Y.ID <- Y names(my_data_pairs.loc) <- c("X", "Y", "X.ID", "Y.ID") my_data_pairs.loc <- my_data_pairs.loc[,c("X.ID","X", "Y.ID", "Y")] my_data_pairs <- dplyr::bind_rows(my_data_pairs, my_data_pairs.loc) } } my_data_pairs$X.ID <- as.factor(my_data_pairs$X.ID) my_data_pairs$Y.ID <- as.factor(my_data_pairs$Y.ID) ## in centered normalized parameter values summary.my_data_pairs <- my_data_pairs %>% dplyr::group_by(X.ID, Y.ID) %>% dplyr::summarise(n = dplyr::n(), spear.rho = stats::cor(X, Y, method = "spearman"), spear.p = stats::cor.test(X, Y, method = "spearman", na.rm = T, exact = F)$p.value, pear.r = stats::cor(X, Y, method = "pearson"), pear.p = stats::cor.test(X, Y, method = "pearson")$p.value, .groups = "drop_last" ) %>% as.data.frame() summary.my_data_pairs[, c("spear.p.signif", "pear.p.signif")] <- significance_pval_df(summary.my_data_pairs[, c("spear.p", "pear.p")]) my_data_pairs <- dplyr::right_join(my_data_pairs, summary.my_data_pairs, by = c("X.ID", "Y.ID")) # my_data_pairs$X.ID = factor(my_data_pairs$X.ID, levels = XID_facet_order) # my_data_pairs$Y.ID = factor(my_data_pairs$Y.ID, levels = YID_facet_order) XY_labels <- decomposed.names.swp.ADSR[,c("X.ID", "Y.ID", "label.swp.ADSR")] XY_labels[nrow(XY_labels)+1, ] <- "SSR" names(summary.my_data_pairs)[names(summary.my_data_pairs) %in% c("X.ID", "Y.ID")] <- c("Y.ID", "X.ID") Y.max <- ceiling(max(abs(my_data_pairs$Y))) X.max <- ceiling(max(abs(my_data_pairs$X))) XY_labels <- XY_labels[XY_labels$X.ID %in% unique(c(as.character(unique(my_data_pairs$X.ID)), as.character(unique(my_data_pairs$Y.ID)))), ] #### ___ ii. plot correlations qp within CI fitted & param subset #### distinct.my_data_pairs <- my_data_pairs %>% dplyr::distinct() plot.correlogram.CI_fit <- ggplot2::ggplot(data = my_data_pairs, ggplot2::aes(x = X, y = Y ))+ ggplot2::geom_point(inherit.aes = F, data = summary.my_data_pairs, shape = 15, ggplot2::aes(x = 0, y = 0, color = abs(spear.rho), size = abs(spear.rho), alpha = (-log10(spear.p)/max(-log10(my_data_pairs$spear.p[my_data_pairs$spear.p!=0])))))+ ggplot2::scale_size_continuous(range = c(1,18))+ ggplot2::scale_colour_gradient(low = "white", high = "orange")+ ggplot2::scale_fill_gradient(low = "white", high = "black")+ # ggplot2::geom_point(data = distinct.my_data_pairs, # shape = 21, # stroke = 0, # color = "black", # fill = "black" # )+ ggplot2::geom_bin2d()+ ggplot2::stat_smooth(method = "loess", se = F, formula = "y ~ x", size = .5, ggplot2::aes(alpha = abs(spear.rho)) )+ ggplot2::labs(title = "Full correlogram", subtitle = "for all CI-fitted quantitative parameters and SSR (sums of squared residuals)", caption = paste("Statistics are Spearman absolute rho (size and color of central square) and p-value significance.", " \n", "Blue line is smooth loess method.", sep = "" ) )+ # egg::theme_article()+ ggplot2::theme_linedraw()+ ggplot2::theme(legend.position = "None", strip.text.x = ggplot2::element_blank(), strip.text.y = ggplot2::element_blank(), axis.title = ggplot2::element_blank(), axis.text = ggplot2::element_blank(), axis.ticks = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), panel.grid.minor = ggplot2::element_blank() )+ ggplot2::facet_grid( factor(Y.ID, levels = ID_facet_order) ~ factor(X.ID, levels = ID_facet_order))+ ggplot2::geom_text(data = summary.my_data_pairs, ggplot2::aes(x = 0, y = .7*Y.max, label = spear.p.signif), hjust = 0.5, vjust = 0)+ ggplot2::geom_text(data = summary.my_data_pairs, ggplot2::aes(x = 0, y = -.8*Y.max, label = paste("|rho| =", dec_n(abs(spear.rho), 3))), size = 2, hjust = 0.5, vjust = 0.5)+ ggplot2::scale_y_continuous(limits = c(-Y.max,Y.max))+ ggplot2::scale_x_continuous(limits = c(-X.max,X.max))+ ggplot2::geom_text(inherit.aes = F, data = XY_labels, ggplot2::aes(x = 0, y = 0, label = label.swp.ADSR), vjust = 0.5, size = 3) # plot.correlogram.CI_fit return(plot.correlogram.CI_fit) } } # #_________________________________________________________________________80char #' plot_lda #' #' @description Plot linear discriminant analysis by quartiles of summed squared residuals for all ADSR parameters #' #' @param DF fit.final_space data frame #' @param names.swp.ADSR names of swept ADSR parameters (alpha, delta, size, rayleigh, custom expressions), as vector #' #' @return A linear discriminant analysis by quartiles of summed squared residuals for all ADSR parameters #' #' @keywords internal plot_lda <- function(DF, names.swp.ADSR){ ..level.. <- LD2 <- LD1 <- SSR <- NULL all.ADRS <- DF[DF$in.all_fit_boxes.obs.CI == TRUE & DF$in.all.subset_param == TRUE, c("SSR", names.swp.ADSR)] standardized.all.ADRS <- all.ADRS %>% scale(center = TRUE, scale = TRUE) %>% as.data.frame() %>% dplyr::select_if(~!all(is.na(.))) if (ncol(standardized.all.ADRS) >= 4){ dat <- standardized.all.ADRS names(dat) <- stringr::str_replace_all(names(dat), pattern = "/", replacement = "_") dat_num_vars <- names(dat) lda_dat_num_vars <- dat_num_vars[!dat_num_vars %in% "SSR"] dat <- dat %>% dplyr::mutate(cut=cut(include.lowest = T, SSR, breaks = as.vector(stats::quantile(dat$SSR)), labels = c("SSR 0-25\u0025","SSR 25-50\u0025","SSR 50-75\u0025", "SSR 75-100\u0025"))) lda_dat_num_vars <- dat_num_vars[!dat_num_vars %in% "SSR"] linear <- MASS::lda(cut ~ ., dat[, c(lda_dat_num_vars, "cut")]) Proportion_of_trace <- linear$svd^2/sum(linear$svd^2) lda_plot <- cbind(dat[, c(dat_num_vars, "cut")], stats::predict(linear, dat[, c(dat_num_vars, "cut")])$x) # define data to plot col<- grDevices::colorRampPalette(c("chartreuse2", "brown1"))(4) cols <- c("SSR 0-25\u0025" = col[1], "SSR 25-50\u0025" = col[2], "SSR 50-75\u0025" = col[3], "SSR 75-100\u0025" = col[4]) # circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){ # r = diameter / 2 # tt <- seq(0,2*pi,length.out = npoints) # xx <- center[1] + r * cos(tt) # yy <- center[2] + r * sin(tt) # return(data.frame(x = xx, y = yy)) # } # circ <- circleFun(c(0,0), 2*max(abs(linear$scaling[,1:2])) ,npoints = 500) if (nrow(lda_plot) <= 1000 ){ plot.lda <- ggplot2::ggplot(lda_plot, ggplot2::aes(LD1, LD2, color = cut)) + ggplot2::geom_point() } else { plot.lda <- ggplot2::ggplot(lda_plot, ggplot2::aes(LD1, LD2, color = cut)) + ggplot2::stat_density_2d(color = NA, geom = "polygon", ggplot2::aes(alpha = ..level.., fill = cut)) } plot.lda <- plot.lda + ggplot2::stat_ellipse(geom="polygon", ggplot2::aes(fill = cut), # fill = NA, alpha = 0.2, show.legend = FALSE, level = .5)+ # egg::theme_article()+ ggplot2::theme_classic()+ # ggforce::geom_mark_hull(alpha = 0.1, # expand = .001, # linetype = 2, # radius = 0, # concavity = 10, # con.cap = 1)+ ggplot2::scale_color_manual(values = cols) + ggplot2::scale_fill_manual(values = cols) + ggplot2::geom_segment(data = as.data.frame(linear$scaling), ggplot2::aes(x = 0, xend = LD1, y = 0, yend = LD2), arrow = ggplot2::arrow(length = ggplot2::unit(0.025, "npc"), type = "open"), lwd = 1, color = "black", inherit.aes = F) + ggrepel::geom_label_repel(data = as.data.frame(linear$scaling), ggplot2::aes(x = LD1*1.3, y = LD2*1.3, label = lda_dat_num_vars), # check_overlap = F, force = 1, size = 3, label.size = NA, fill = NA, inherit.aes = F)+ ggplot2::labs(x = paste0("LD 1 (", dec_n(100*Proportion_of_trace[1], 2), "\u0025)"), y = paste0("LD 2 (", dec_n(100*Proportion_of_trace[2], 2), "\u0025)"), title = "Linear discriminant analysis of quantitative parameters for least squares best fits", caption = paste0("SSR categories correspond to inter-quantiles groups of the sum of squared residuals (SSR).", "\n", "Ellipses show 50\u0025 distribution."))+ ggplot2::theme(legend.position = "bottom", plot.caption = ggplot2::element_text(hjust = 0) ) plot.lda } else { rlang::inform("\U2139 Not enough continuous parameters for Linear Discriminant Analysis.") } }
corr <- function(directory, threshold = 0) { files_list <- list.files(directory, full.names=TRUE) data_list <- lapply(files_list, read.csv) accept <- complete(directory)$nobs > threshold corrCount <- function(x) { cor(x[complete.cases(x), c("sulfate", "nitrate")])[1, 2] } sapply(data_list[accept], corrCount) }
/corr.R
no_license
DataPete/Coursera-R-Programming
R
false
false
395
r
corr <- function(directory, threshold = 0) { files_list <- list.files(directory, full.names=TRUE) data_list <- lapply(files_list, read.csv) accept <- complete(directory)$nobs > threshold corrCount <- function(x) { cor(x[complete.cases(x), c("sulfate", "nitrate")])[1, 2] } sapply(data_list[accept], corrCount) }
#Source functions library(proto) ##Make Query scquery <- function(inquery,year) { #format string query <- paste("query=",inquery,sep = "") #url encoding #reform query to html encoded queryF <- gsub(x = query,"\\(","%28") queryF <- gsub(x = queryF,"\\)","%29") queryF <- gsub(x = queryF,"\\+","%20") ###Query Parameters #Institution token - cannot be viewed in browser, save in file outside of git. inst.token <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/InstToken.txt") apiKey <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/apikey.txt") #format string str <- "https://api.elsevier.com/content/search/scopus?&httpAccept=application/xml&view=complete&count=100" #fields f <- "field=prism:publicationName,dc:title,dc:creator,citedby-count,prism:coverDate,author,dc:identifier" #bind toget <- paste(str,queryF,sep = "&") #bind to the year toget <- paste(toget,year,sep = "&date=") #add in api and institutional key toget <- paste(toget,"&apiKey=",apiKey,sep = "") toget <- paste(toget,"&insttoken=",inst.token,sep = "") #add fields toget <- paste(toget,f,sep = "&") #Request query #call response <- GET(toget) return(response) } ## sc_parse <- function(response) { #Does the response have data? if (!response$status_code == 200) { return("Invalid Query") } xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) names(ns)[1] <- "xmlns" #set namespaces e <- xpathSApply(xmltop,"//xmlns:entry/xmlns:error",xmlValue,namespaces = ns) if (length(e) == 1) { return(NA) } #Format Results ##Get journal journal <- xpathSApply(xmltop,"//prism:publicationName",xmlValue,namespaces = ns) ##All authors #how many articles are there? lresponse <- length(getNodeSet(xmltop,"//xmlns:entry",namespaces = ns,xmlValue)) #loop through each article and get author list allauthors <- list() for (x in 1:lresponse) { #make an xpath statement xpath <- paste("//xmlns:entry[",x,"]//xmlns:author/xmlns:authid",sep = "") allauthors[[x]] <- as.list(xpathSApply(xmltop,xpath,xmlValue,namespaces = ns)) } names(allauthors) <- xpathSApply(xmltop,"//xmlns:entry//dc:identifier",xmlValue,namespaces = ns) #if missing allauthors[lapply(allauthors,length) == 0] <- "Unknown" ##Citation Count citation <- as.numeric( xpathSApply( xmltop,"//xmlns:entry//xmlns:citedby-count",xmlValue,namespaces = ns ) ) ##Year Year <- years(xpathSApply( xmltop,"//xmlns:entry//prism:coverDate",xmlValue,namespaces = ns )) #Indentifier DOI <- xpathSApply(xmltop,"//xmlns:entry//dc:identifier",xmlValue,namespaces = ns) #Bind article level statistics artdf <- data.frame( Journal = journal,Citations = citation,Year = Year,DOI = DOI ) #melt and combine allauthors <- melt(allauthors) colnames(allauthors) <- c("Author","Order","DOI") #Match journal to classification #legacy name change artmatch <- artdf if (nrow(artmatch) == 0) { artmatch <- artdf[paste("The",artdf$Journal) %in% j_class$Publication,] } #merge into final table dat <- droplevels(merge(allauthors,artmatch)) return(dat) } #How many results from a query, used to loop until complete getCount <- function(response) { xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) names(ns)[1] <- "xmlns" #Get total results tresults <- as.numeric(xpathSApply(xmltop,"//opensearch:totalResults",xmlValue,namespaces = ns)) return(tresults) } currentCount <- function(response) { xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) names(ns)[1] <- "xmlns" #Get current results total tresults <- length(xpathSApply(xmltop,"//xmlns:entry",xmlValue,namespaces = ns)) return(tresults) } #run for each year allyears <- function(query,yearrange) { out <- list() for (y in 1:length(yearrange)) { yeardat <- list() #Iterators tcount <- 0 r <- 1 #Get initial query response <- scquery(inquery = query,yearrange[y]) if (!response$status_code == 200) { next } #How many results are there? tresults <- getCount(response) #How many results did we get? tcount <- tcount + currentCount(response) yeardat[[r]] <- response #break function if no response if (tresults == 0) { yeardat[[r]] <- NA next } #Iterate until we get all results while (!tcount == tresults) { r = r + 1 newrequest <- paste(response[[1]],"&start=",tcount,sep = "") newresponse <- GET(newrequest) if (!newresponse$status_code == 200) { break } yeardat[[r]] <- newresponse tcount <- tcount + currentCount(newresponse) } #remove blank yeardat <- yeardat[!sapply(yeardat,length) == 0] #remove if only one hit yeardat <- yeardat[!lapply(yeardat,currentCount) == 1] #bind the yeardat out[[y]] <- rbind_all(lapply(yeardat,sc_parse)) print(paste(str_extract(query,"\\(.*?\\)"),yearrange[y])) } dat <- rbind_all(out[!sapply(out,length) == 1]) return(dat) } #helper function for standardizing caps .simpleCap <- function(x) { s <- strsplit(x, " ")[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "", collapse = " ") } getSourceID <- function(inquery) { # query <- paste("title=",inquery,sep = "") #url encoding #reform query to html encoded queryF <- gsub(x = query,"\\(","%28") queryF <- gsub(x = queryF,"\\)","%29") queryF <- gsub(x = queryF,"\\+","%20") ###Query Parameters #Institution token - cannot be viewed in browser, save in file outside of git. inst.token <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/InstToken.txt") apiKey <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/apikey.txt") #format string toget <- "https://api.elsevier.com/content/serial/title?&httpAccept=application/xml&count=100" #bind toget <- paste(toget,queryF,sep = "&") #add in api and institutional key toget <- paste(toget,"&apiKey=",apiKey,sep = "") toget <- paste(toget,"&insttoken=",inst.token,sep = "") #Request query #call response <- GET(toget) } parseSource <- function(response,inquery) { if (!response$status_code == 200) { return(NA) } xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) #Get current results total title <- xpathSApply(xmltop,"//dc:title",xmlValue,namespaces = ns) ID <- xpathSApply(xmltop,"//source-id",xmlValue,namespaces = ns) if (length(title) == 0) { return(NA) } r <- data.frame(title = title,ID = ID,query = inquery) #just get the one that matches r <- r[toupper(r$title) %in% toupper(gsub(inquery,pattern = "\\+",replacement = " ")),] return(r) } ##Horizontal ggplot geom_bar_horz <- function (mapping = NULL, data = NULL, stat = "bin", position = "stack", ...) { GeomBar_horz$new( mapping = mapping, data = data, stat = stat, position = position, ... ) } GeomBar_horz <- proto(ggplot2:::Geom, { objname <- "bar_horz" default_stat <- function(.) StatBin default_pos <- function(.) PositionStack default_aes <- function(.) aes( colour = NA, fill = "grey20", size = 0.5, linetype = 1, weight = 1, alpha = NA ) required_aes <- c("y") reparameterise <- function(., df, params) { df$width <- df$width %||% params$width %||% (resolution(df$x, FALSE) * 0.9) OUT <- transform( df, xmin = pmin(x, 0), xmax = pmax(x, 0), ymin = y - .45, ymax = y + .45, width = NULL ) return(OUT) } draw_groups <- function(., data, scales, coordinates, ...) { GeomRect$draw_groups(data, scales, coordinates, ...) } guide_geom <- function(.) "polygon" }) ##Calculate network stats from df calcN <- function(x) { x <- droplevels(x) siteXspp <- as.data.frame.array(table(x$Author,x$Class)) topics <- 1 - as.matrix(vegdist(t(siteXspp),"horn")) g <- graph.adjacency(topics,"undirected",weighted = TRUE) g <- simplify(g) # set labels and degrees of vertices V(g)$label <- V(g)$name V(g)$degree <- degree(g) layout1 <- layout.fruchterman.reingold(g) V(g)$label.color <- rgb(0, 0, .2, .8) V(g)$frame.color <- NA egam = E(g)$weight / max(E(g)$weight) E(g)$color <- rgb(0,1,0,alpha = E(g)$weight / max(E(g)$weight),maxColorValue = 1) ramp <- colorRamp(c("blue","red"),alpha = T) E(g)$color = apply(ramp(E(g)$weight), 1, function(x) rgb(x[1] / 255,x[2] / 255,x[3] / 255,alpha = T)) # plot the graph in layout1 layout1 <- layout.fruchterman.reingold(g) #If you need to delete g.copy <- delete.edges(g, which(E(g)$weight < .05)) #width width <- (E(g.copy)$weight / max(E(g.copy)$weight)) * 8 #label sizes V(g.copy)$label.cex <- V(g.copy)$degree / max(V(g.copy)$degree) * 1 + .2 plot(g.copy,vertex.size = 6,edge.width = width) between_class <- betweenness(g.copy) degree_class <- degree(g.copy) closeness_class <- closeness(g.copy) eigenV <- evcent(g.copy)$vector vdat <- data.frame( Class = names(between_class),Between = between_class,Degree = degree_class,Closeness = closeness_class,Eigen = eigenV ) return(vdat) } CalcG <- function(x) { x <- droplevels(x) siteXspp <- as.data.frame.array(table(x$Author,x$Class)) topics <- 1 - as.matrix(vegdist(t(siteXspp),"horn")) g <- graph.adjacency(topics,"undirected",weighted = TRUE) g <- simplify(g) # set labels and degrees of vertices V(g)$label <- V(g)$name V(g)$degree <- degree(g) layout1 <- layout.fruchterman.reingold(g) V(g)$label.color <- rgb(0, 0, .2, .8) V(g)$frame.color <- NA egam = E(g)$weight / max(E(g)$weight) E(g)$color <- rgb(0,1,0,alpha = E(g)$weight / max(E(g)$weight),maxColorValue = 1) ramp <- colorRamp(c("blue","red"),alpha = T) E(g)$color = apply(ramp(E(g)$weight), 1, function(x) rgb(x[1] / 255,x[2] / 255,x[3] / 255,alpha = T)) # plot the graph in layout1 layout1 <- layout.fruchterman.reingold(g) #If you need to delete g.copy <- delete.edges(g, which(E(g)$weight < .05)) #width width <- (E(g.copy)$weight / max(E(g.copy)$weight)) * 8 #label sizes V(g.copy)$label.cex <- V(g.copy)$degree / max(V(g.copy)$degree) * 1 + .2 #connectance gdensity <- graph.density(g.copy) } CalcDD <- function(x) { x <- droplevels(x) siteXspp <- as.data.frame.array(table(x$Author,x$Class)) topics <- 1 - as.matrix(vegdist(t(siteXspp),"horn")) g <- graph.adjacency(topics,"undirected",weighted = TRUE) g <- simplify(g) # set labels and degrees of vertices V(g)$label <- V(g)$name V(g)$degree <- degree(g) layout1 <- layout.fruchterman.reingold(g) V(g)$label.color <- rgb(0, 0, .2, .8) V(g)$frame.color <- NA egam = E(g)$weight / max(E(g)$weight) E(g)$color <- rgb(0,1,0,alpha = E(g)$weight / max(E(g)$weight),maxColorValue = 1) ramp <- colorRamp(c("blue","red"),alpha = T) E(g)$color = apply(ramp(E(g)$weight), 1, function(x) rgb(x[1] / 255,x[2] / 255,x[3] / 255,alpha = T)) # plot the graph in layout1 layout1 <- layout.fruchterman.reingold(g) #If you need to delete g.copy <- delete.edges(g, which(E(g)$weight < .05)) #width width <- (E(g.copy)$weight / max(E(g.copy)$weight)) * 8 #label sizes V(g.copy)$label.cex <- V(g.copy)$degree / max(V(g.copy)$degree) * 1 + .2 dd <- degree.distribution(g.copy) return(as.matrix(dd)) } shead <- function(tab) { dbGetQuery(d$con,paste("SELECT * FROM",tab,"limit 10")) } queryscopus <- function(runs = 20,size = 20) { #create a data holder cl <- makeCluster(size,"SOCK") registerDoSNOW(cl) #write a test query that you know works to ensure you have space tq <- scquery("AUK","2014") #set placement of journal jp <- read.table("Data/JournalSection.txt")$x #update new #how many journals to run? #if last run ended in exceed query, run 0! jp <- (max(jp) + 1):(max(jp) + runs) print(jp) #are there any runs left if (length(journaldf$ID) < min(jp)) { return(FALSE) } if (tq$status_code == 200) { dat <- foreach( x = jp,.errorhandling = "pass",.packages = c( "httr","XML","proto","reshape2","plyr","dplyr","chron","stringr" ),.export = "journaldf" ) %dopar% { #get functions source("Funtions.R") #get articles from a journal and parse it q <- paste("source-id(",journaldf$ID[x],")",sep = "") #call query responses <- allyears(query = q,yearrange = 1995:1996) #parse result return(responses) } stopCluster(cl) #if we ran out of calls, figure out where, using a test query tq <- scquery("AUK","2014") if (!tq$status_code == 200) { dat <- dat[sapply(dat,function(x) { max(as.numeric(as.character(x$Year))) }) == 2014] } #bind journals, remove no matched #correct runs have length of 6 df <- rbind_all(dat[lapply(dat,length) == 6]) #Standardize capitalization df$Journal <- sapply(df$Journal,.simpleCap) if (nrow(df) == 0) { write.table(jp,"Data/JournalSection.txt") return(TRUE) } #turn unknowns to NA, it was just a place holder df[df$Author %in% "Unknown","Author"] <- NA #write.table(df,"C:/Users/Ben/Dropbox/FacultyNetwork/ParsedDataID.csv",append=T,col.names=F,row.names=F,sep=",") df <- df[!is.na(df$DOI),] print(dim(df)) #open database connection d<-src_sqlite(path = "C:/Users/Ben/Dropbox/FacultyNetwork/Meta.sqlite3") #write journal and DOI table to the JA table towrite <- df %>% distinct(DOI) %>% select(DOI,Journal) db_insert_into(con = d$con,table = "JA",values = as.data.frame(towrite)) towrite <- df %>% distinct(DOI) %>% select(DOI,Author,Order,Citations,Year) db_insert_into(con = d$con,table = "Meta",values = as.data.frame(towrite)) write.table(jp,"Data/JournalSection.txt") #manually remove objects to be sure rm(df,towrite,dat) gc() return(TRUE) } else { print("Quota Exceeded") return(FALSE) } } #test query function testquery <- function() { tq <- scquery("AUK","2014") return(tq) }
/Funtions.R
no_license
bw4sz/FacultyNetwork
R
false
false
15,272
r
#Source functions library(proto) ##Make Query scquery <- function(inquery,year) { #format string query <- paste("query=",inquery,sep = "") #url encoding #reform query to html encoded queryF <- gsub(x = query,"\\(","%28") queryF <- gsub(x = queryF,"\\)","%29") queryF <- gsub(x = queryF,"\\+","%20") ###Query Parameters #Institution token - cannot be viewed in browser, save in file outside of git. inst.token <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/InstToken.txt") apiKey <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/apikey.txt") #format string str <- "https://api.elsevier.com/content/search/scopus?&httpAccept=application/xml&view=complete&count=100" #fields f <- "field=prism:publicationName,dc:title,dc:creator,citedby-count,prism:coverDate,author,dc:identifier" #bind toget <- paste(str,queryF,sep = "&") #bind to the year toget <- paste(toget,year,sep = "&date=") #add in api and institutional key toget <- paste(toget,"&apiKey=",apiKey,sep = "") toget <- paste(toget,"&insttoken=",inst.token,sep = "") #add fields toget <- paste(toget,f,sep = "&") #Request query #call response <- GET(toget) return(response) } ## sc_parse <- function(response) { #Does the response have data? if (!response$status_code == 200) { return("Invalid Query") } xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) names(ns)[1] <- "xmlns" #set namespaces e <- xpathSApply(xmltop,"//xmlns:entry/xmlns:error",xmlValue,namespaces = ns) if (length(e) == 1) { return(NA) } #Format Results ##Get journal journal <- xpathSApply(xmltop,"//prism:publicationName",xmlValue,namespaces = ns) ##All authors #how many articles are there? lresponse <- length(getNodeSet(xmltop,"//xmlns:entry",namespaces = ns,xmlValue)) #loop through each article and get author list allauthors <- list() for (x in 1:lresponse) { #make an xpath statement xpath <- paste("//xmlns:entry[",x,"]//xmlns:author/xmlns:authid",sep = "") allauthors[[x]] <- as.list(xpathSApply(xmltop,xpath,xmlValue,namespaces = ns)) } names(allauthors) <- xpathSApply(xmltop,"//xmlns:entry//dc:identifier",xmlValue,namespaces = ns) #if missing allauthors[lapply(allauthors,length) == 0] <- "Unknown" ##Citation Count citation <- as.numeric( xpathSApply( xmltop,"//xmlns:entry//xmlns:citedby-count",xmlValue,namespaces = ns ) ) ##Year Year <- years(xpathSApply( xmltop,"//xmlns:entry//prism:coverDate",xmlValue,namespaces = ns )) #Indentifier DOI <- xpathSApply(xmltop,"//xmlns:entry//dc:identifier",xmlValue,namespaces = ns) #Bind article level statistics artdf <- data.frame( Journal = journal,Citations = citation,Year = Year,DOI = DOI ) #melt and combine allauthors <- melt(allauthors) colnames(allauthors) <- c("Author","Order","DOI") #Match journal to classification #legacy name change artmatch <- artdf if (nrow(artmatch) == 0) { artmatch <- artdf[paste("The",artdf$Journal) %in% j_class$Publication,] } #merge into final table dat <- droplevels(merge(allauthors,artmatch)) return(dat) } #How many results from a query, used to loop until complete getCount <- function(response) { xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) names(ns)[1] <- "xmlns" #Get total results tresults <- as.numeric(xpathSApply(xmltop,"//opensearch:totalResults",xmlValue,namespaces = ns)) return(tresults) } currentCount <- function(response) { xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) names(ns)[1] <- "xmlns" #Get current results total tresults <- length(xpathSApply(xmltop,"//xmlns:entry",xmlValue,namespaces = ns)) return(tresults) } #run for each year allyears <- function(query,yearrange) { out <- list() for (y in 1:length(yearrange)) { yeardat <- list() #Iterators tcount <- 0 r <- 1 #Get initial query response <- scquery(inquery = query,yearrange[y]) if (!response$status_code == 200) { next } #How many results are there? tresults <- getCount(response) #How many results did we get? tcount <- tcount + currentCount(response) yeardat[[r]] <- response #break function if no response if (tresults == 0) { yeardat[[r]] <- NA next } #Iterate until we get all results while (!tcount == tresults) { r = r + 1 newrequest <- paste(response[[1]],"&start=",tcount,sep = "") newresponse <- GET(newrequest) if (!newresponse$status_code == 200) { break } yeardat[[r]] <- newresponse tcount <- tcount + currentCount(newresponse) } #remove blank yeardat <- yeardat[!sapply(yeardat,length) == 0] #remove if only one hit yeardat <- yeardat[!lapply(yeardat,currentCount) == 1] #bind the yeardat out[[y]] <- rbind_all(lapply(yeardat,sc_parse)) print(paste(str_extract(query,"\\(.*?\\)"),yearrange[y])) } dat <- rbind_all(out[!sapply(out,length) == 1]) return(dat) } #helper function for standardizing caps .simpleCap <- function(x) { s <- strsplit(x, " ")[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "", collapse = " ") } getSourceID <- function(inquery) { # query <- paste("title=",inquery,sep = "") #url encoding #reform query to html encoded queryF <- gsub(x = query,"\\(","%28") queryF <- gsub(x = queryF,"\\)","%29") queryF <- gsub(x = queryF,"\\+","%20") ###Query Parameters #Institution token - cannot be viewed in browser, save in file outside of git. inst.token <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/InstToken.txt") apiKey <- readLines("C:/Users/Ben/Dropbox/FacultyNetwork/apikey.txt") #format string toget <- "https://api.elsevier.com/content/serial/title?&httpAccept=application/xml&count=100" #bind toget <- paste(toget,queryF,sep = "&") #add in api and institutional key toget <- paste(toget,"&apiKey=",apiKey,sep = "") toget <- paste(toget,"&insttoken=",inst.token,sep = "") #Request query #call response <- GET(toget) } parseSource <- function(response,inquery) { if (!response$status_code == 200) { return(NA) } xml <- xmlInternalTreeParse(response) xmltop <- xmlRoot(xml) #define name spaces nsDefs <- xmlNamespaceDefinitions(xmltop) ns <- structure(sapply(nsDefs, function(x) x$uri), names = names(nsDefs)) #Get current results total title <- xpathSApply(xmltop,"//dc:title",xmlValue,namespaces = ns) ID <- xpathSApply(xmltop,"//source-id",xmlValue,namespaces = ns) if (length(title) == 0) { return(NA) } r <- data.frame(title = title,ID = ID,query = inquery) #just get the one that matches r <- r[toupper(r$title) %in% toupper(gsub(inquery,pattern = "\\+",replacement = " ")),] return(r) } ##Horizontal ggplot geom_bar_horz <- function (mapping = NULL, data = NULL, stat = "bin", position = "stack", ...) { GeomBar_horz$new( mapping = mapping, data = data, stat = stat, position = position, ... ) } GeomBar_horz <- proto(ggplot2:::Geom, { objname <- "bar_horz" default_stat <- function(.) StatBin default_pos <- function(.) PositionStack default_aes <- function(.) aes( colour = NA, fill = "grey20", size = 0.5, linetype = 1, weight = 1, alpha = NA ) required_aes <- c("y") reparameterise <- function(., df, params) { df$width <- df$width %||% params$width %||% (resolution(df$x, FALSE) * 0.9) OUT <- transform( df, xmin = pmin(x, 0), xmax = pmax(x, 0), ymin = y - .45, ymax = y + .45, width = NULL ) return(OUT) } draw_groups <- function(., data, scales, coordinates, ...) { GeomRect$draw_groups(data, scales, coordinates, ...) } guide_geom <- function(.) "polygon" }) ##Calculate network stats from df calcN <- function(x) { x <- droplevels(x) siteXspp <- as.data.frame.array(table(x$Author,x$Class)) topics <- 1 - as.matrix(vegdist(t(siteXspp),"horn")) g <- graph.adjacency(topics,"undirected",weighted = TRUE) g <- simplify(g) # set labels and degrees of vertices V(g)$label <- V(g)$name V(g)$degree <- degree(g) layout1 <- layout.fruchterman.reingold(g) V(g)$label.color <- rgb(0, 0, .2, .8) V(g)$frame.color <- NA egam = E(g)$weight / max(E(g)$weight) E(g)$color <- rgb(0,1,0,alpha = E(g)$weight / max(E(g)$weight),maxColorValue = 1) ramp <- colorRamp(c("blue","red"),alpha = T) E(g)$color = apply(ramp(E(g)$weight), 1, function(x) rgb(x[1] / 255,x[2] / 255,x[3] / 255,alpha = T)) # plot the graph in layout1 layout1 <- layout.fruchterman.reingold(g) #If you need to delete g.copy <- delete.edges(g, which(E(g)$weight < .05)) #width width <- (E(g.copy)$weight / max(E(g.copy)$weight)) * 8 #label sizes V(g.copy)$label.cex <- V(g.copy)$degree / max(V(g.copy)$degree) * 1 + .2 plot(g.copy,vertex.size = 6,edge.width = width) between_class <- betweenness(g.copy) degree_class <- degree(g.copy) closeness_class <- closeness(g.copy) eigenV <- evcent(g.copy)$vector vdat <- data.frame( Class = names(between_class),Between = between_class,Degree = degree_class,Closeness = closeness_class,Eigen = eigenV ) return(vdat) } CalcG <- function(x) { x <- droplevels(x) siteXspp <- as.data.frame.array(table(x$Author,x$Class)) topics <- 1 - as.matrix(vegdist(t(siteXspp),"horn")) g <- graph.adjacency(topics,"undirected",weighted = TRUE) g <- simplify(g) # set labels and degrees of vertices V(g)$label <- V(g)$name V(g)$degree <- degree(g) layout1 <- layout.fruchterman.reingold(g) V(g)$label.color <- rgb(0, 0, .2, .8) V(g)$frame.color <- NA egam = E(g)$weight / max(E(g)$weight) E(g)$color <- rgb(0,1,0,alpha = E(g)$weight / max(E(g)$weight),maxColorValue = 1) ramp <- colorRamp(c("blue","red"),alpha = T) E(g)$color = apply(ramp(E(g)$weight), 1, function(x) rgb(x[1] / 255,x[2] / 255,x[3] / 255,alpha = T)) # plot the graph in layout1 layout1 <- layout.fruchterman.reingold(g) #If you need to delete g.copy <- delete.edges(g, which(E(g)$weight < .05)) #width width <- (E(g.copy)$weight / max(E(g.copy)$weight)) * 8 #label sizes V(g.copy)$label.cex <- V(g.copy)$degree / max(V(g.copy)$degree) * 1 + .2 #connectance gdensity <- graph.density(g.copy) } CalcDD <- function(x) { x <- droplevels(x) siteXspp <- as.data.frame.array(table(x$Author,x$Class)) topics <- 1 - as.matrix(vegdist(t(siteXspp),"horn")) g <- graph.adjacency(topics,"undirected",weighted = TRUE) g <- simplify(g) # set labels and degrees of vertices V(g)$label <- V(g)$name V(g)$degree <- degree(g) layout1 <- layout.fruchterman.reingold(g) V(g)$label.color <- rgb(0, 0, .2, .8) V(g)$frame.color <- NA egam = E(g)$weight / max(E(g)$weight) E(g)$color <- rgb(0,1,0,alpha = E(g)$weight / max(E(g)$weight),maxColorValue = 1) ramp <- colorRamp(c("blue","red"),alpha = T) E(g)$color = apply(ramp(E(g)$weight), 1, function(x) rgb(x[1] / 255,x[2] / 255,x[3] / 255,alpha = T)) # plot the graph in layout1 layout1 <- layout.fruchterman.reingold(g) #If you need to delete g.copy <- delete.edges(g, which(E(g)$weight < .05)) #width width <- (E(g.copy)$weight / max(E(g.copy)$weight)) * 8 #label sizes V(g.copy)$label.cex <- V(g.copy)$degree / max(V(g.copy)$degree) * 1 + .2 dd <- degree.distribution(g.copy) return(as.matrix(dd)) } shead <- function(tab) { dbGetQuery(d$con,paste("SELECT * FROM",tab,"limit 10")) } queryscopus <- function(runs = 20,size = 20) { #create a data holder cl <- makeCluster(size,"SOCK") registerDoSNOW(cl) #write a test query that you know works to ensure you have space tq <- scquery("AUK","2014") #set placement of journal jp <- read.table("Data/JournalSection.txt")$x #update new #how many journals to run? #if last run ended in exceed query, run 0! jp <- (max(jp) + 1):(max(jp) + runs) print(jp) #are there any runs left if (length(journaldf$ID) < min(jp)) { return(FALSE) } if (tq$status_code == 200) { dat <- foreach( x = jp,.errorhandling = "pass",.packages = c( "httr","XML","proto","reshape2","plyr","dplyr","chron","stringr" ),.export = "journaldf" ) %dopar% { #get functions source("Funtions.R") #get articles from a journal and parse it q <- paste("source-id(",journaldf$ID[x],")",sep = "") #call query responses <- allyears(query = q,yearrange = 1995:1996) #parse result return(responses) } stopCluster(cl) #if we ran out of calls, figure out where, using a test query tq <- scquery("AUK","2014") if (!tq$status_code == 200) { dat <- dat[sapply(dat,function(x) { max(as.numeric(as.character(x$Year))) }) == 2014] } #bind journals, remove no matched #correct runs have length of 6 df <- rbind_all(dat[lapply(dat,length) == 6]) #Standardize capitalization df$Journal <- sapply(df$Journal,.simpleCap) if (nrow(df) == 0) { write.table(jp,"Data/JournalSection.txt") return(TRUE) } #turn unknowns to NA, it was just a place holder df[df$Author %in% "Unknown","Author"] <- NA #write.table(df,"C:/Users/Ben/Dropbox/FacultyNetwork/ParsedDataID.csv",append=T,col.names=F,row.names=F,sep=",") df <- df[!is.na(df$DOI),] print(dim(df)) #open database connection d<-src_sqlite(path = "C:/Users/Ben/Dropbox/FacultyNetwork/Meta.sqlite3") #write journal and DOI table to the JA table towrite <- df %>% distinct(DOI) %>% select(DOI,Journal) db_insert_into(con = d$con,table = "JA",values = as.data.frame(towrite)) towrite <- df %>% distinct(DOI) %>% select(DOI,Author,Order,Citations,Year) db_insert_into(con = d$con,table = "Meta",values = as.data.frame(towrite)) write.table(jp,"Data/JournalSection.txt") #manually remove objects to be sure rm(df,towrite,dat) gc() return(TRUE) } else { print("Quota Exceeded") return(FALSE) } } #test query function testquery <- function() { tq <- scquery("AUK","2014") return(tq) }
library(mxnet) #1. Generate example data (equal length data) set.seed(0) data(austres) seqs = as.numeric(t(austres)) random.start = sample(1:(length(seqs)-10), 50, replace = TRUE) seqs.array = sapply(random.start, function(x) {seqs[x+0:10]}) X.array = array(seqs.array[-11,], dim = c(10, 50)) Y.array = array(seqs.array[-1,], dim = c(10, 50)) #2. Define the model architecture #This architecture is builded by simple recurrent unit. #2 inputs: 1 for X; 1 for the last prediction status batch_size = 5 seq_len = 10 num_hidden = 3 simple_recurrent_unit = function (new_data, last_status = NULL, params = NULL, first = TRUE) { if (first) { out = new_data } else { LIST = list(new_data, last_status) LIST$dim = 2 LIST$num.args = 2 concat_LIST = mxnet:::mx.varg.symbol.Concat(LIST) FC_WEIGHT = mx.symbol.FullyConnected(data = concat_LIST, num.hidden = 1, weight = params$highway_weight, bias = params$highway_bias) sigmoid_WEIGHT = mx.symbol.Activation(data = FC_WEIGHT, act.type = 'sigmoid') reshape_WEIGHT = mx.symbol.reshape(sigmoid_WEIGHT, shape = c(1, 1, 1, batch_size)) out = mx.symbol.broadcast_mul(reshape_WEIGHT, new_data) + mx.symbol.broadcast_mul(1 - reshape_WEIGHT, last_status) } return(out) } data = mx.symbol.Variable(name = 'data') label = mx.symbol.Variable(name = 'label') PARAMS = list(highway_weights = mx.symbol.Variable(name = 'highway_weight'), highway_bias = mx.symbol.Variable(name = 'highway_bias')) #Tip-1: The squeeze_axis is in the order of 0, 1, 2, ... but not 1, 2, 3, ... # You need to know the dimention number here is in contrast. # For example, if your data shape is 3-dimention, the squeeze_axis should be # in order of 2, 1, 0; if your data shape is 4-dimention, the squeeze_axis # should be in order of 3, 2, 1, 0; Now our data shape is 2-dimention and # we want to split it by the first dimention. The squeeze_axis is in order of # 1, 0 in this data, so we need to assign 1 in this example. #Tip-2: Please use 'mx.symbol.infer.shape' function to check the output datashape sub_data = mx.symbol.SliceChannel(data = data, num_outputs = seq_len, squeeze_axis = 1) #mx.symbol.infer.shape(sub_data, data = c(seq_len, batch_size))$out.shapes output_list = list() for (i in 1:seq_len) { New_data = mx.symbol.reshape(sub_data[[i]], shape = c(1, 1, 1, batch_size)) if (i == 1) { output_list[[i]] = simple_recurrent_unit(new_data = New_data, params = PARAMS) } else { output_list[[i]] = simple_recurrent_unit(new_data = New_data, last_status = output_list[[i-1]], params = PARAMS, first = FALSE) } #output_list[[i]] = mx.symbol.reshape(output, shape = c(num_hidden, 1, 1, batch_size)) } #Tip-3: The 'dim' meaning the conbining dimention, and the order here is the same as # above example. output_list$dim = 2 output_list$num.args = seq_len concat = mxnet:::mx.varg.symbol.Concat(output_list) #mx.symbol.infer.shape(concat, data = c(seq_len, batch_size))$out.shapes #Tip-4: Now we need to integrate 5 feature to 1 output by sequence. Convolution filter # can handle this situation. fc1_seqs = mx.symbol.Convolution(data = concat, kernel = c(1, 1), stride = c(1, 1), num.filter = 1, name = 'fc1_seqs') reshape_seqs_2 = mx.symbol.reshape(fc1_seqs, shape = c(seq_len, batch_size)) #loss_layer = mx.symbol.broadcast_minus(reshape_seqs_2, label) out_layer = mx.symbol.LinearRegressionOutput(data = reshape_seqs_2, name = 'out_layer') #3. Training model mx.set.seed(0) logger = mx.metric.logger$new() rnn_model = mx.model.FeedForward.create(out_layer, X = X.array, y = Y.array, ctx = mx.cpu(), num.round = 20, array.batch.size = batch_size, learning.rate = 0.0000000005, momentum = 0, wd = 0, array.layout = "colmajor", eval.metric = mx.metric.rmse, epoch.end.callback = mx.callback.log.train.metric(5, logger)) #4. Save and load model #4-1. Save model mx.model.save(rnn_model, "rnn_model", iteration = 0) #4-2. Load model My_model = mx.model.load("rnn_model", iteration = 0) #4-3. Inference predict_Y = predict(rnn_model, X.array, array.layout = "colmajor", array.batch.size = batch_size) RMSE = mean((predict_Y - Y.array)^2) print(RMSE)
/other/mxnet/rnn.R
no_license
krzjoa/learning-R
R
false
false
4,543
r
library(mxnet) #1. Generate example data (equal length data) set.seed(0) data(austres) seqs = as.numeric(t(austres)) random.start = sample(1:(length(seqs)-10), 50, replace = TRUE) seqs.array = sapply(random.start, function(x) {seqs[x+0:10]}) X.array = array(seqs.array[-11,], dim = c(10, 50)) Y.array = array(seqs.array[-1,], dim = c(10, 50)) #2. Define the model architecture #This architecture is builded by simple recurrent unit. #2 inputs: 1 for X; 1 for the last prediction status batch_size = 5 seq_len = 10 num_hidden = 3 simple_recurrent_unit = function (new_data, last_status = NULL, params = NULL, first = TRUE) { if (first) { out = new_data } else { LIST = list(new_data, last_status) LIST$dim = 2 LIST$num.args = 2 concat_LIST = mxnet:::mx.varg.symbol.Concat(LIST) FC_WEIGHT = mx.symbol.FullyConnected(data = concat_LIST, num.hidden = 1, weight = params$highway_weight, bias = params$highway_bias) sigmoid_WEIGHT = mx.symbol.Activation(data = FC_WEIGHT, act.type = 'sigmoid') reshape_WEIGHT = mx.symbol.reshape(sigmoid_WEIGHT, shape = c(1, 1, 1, batch_size)) out = mx.symbol.broadcast_mul(reshape_WEIGHT, new_data) + mx.symbol.broadcast_mul(1 - reshape_WEIGHT, last_status) } return(out) } data = mx.symbol.Variable(name = 'data') label = mx.symbol.Variable(name = 'label') PARAMS = list(highway_weights = mx.symbol.Variable(name = 'highway_weight'), highway_bias = mx.symbol.Variable(name = 'highway_bias')) #Tip-1: The squeeze_axis is in the order of 0, 1, 2, ... but not 1, 2, 3, ... # You need to know the dimention number here is in contrast. # For example, if your data shape is 3-dimention, the squeeze_axis should be # in order of 2, 1, 0; if your data shape is 4-dimention, the squeeze_axis # should be in order of 3, 2, 1, 0; Now our data shape is 2-dimention and # we want to split it by the first dimention. The squeeze_axis is in order of # 1, 0 in this data, so we need to assign 1 in this example. #Tip-2: Please use 'mx.symbol.infer.shape' function to check the output datashape sub_data = mx.symbol.SliceChannel(data = data, num_outputs = seq_len, squeeze_axis = 1) #mx.symbol.infer.shape(sub_data, data = c(seq_len, batch_size))$out.shapes output_list = list() for (i in 1:seq_len) { New_data = mx.symbol.reshape(sub_data[[i]], shape = c(1, 1, 1, batch_size)) if (i == 1) { output_list[[i]] = simple_recurrent_unit(new_data = New_data, params = PARAMS) } else { output_list[[i]] = simple_recurrent_unit(new_data = New_data, last_status = output_list[[i-1]], params = PARAMS, first = FALSE) } #output_list[[i]] = mx.symbol.reshape(output, shape = c(num_hidden, 1, 1, batch_size)) } #Tip-3: The 'dim' meaning the conbining dimention, and the order here is the same as # above example. output_list$dim = 2 output_list$num.args = seq_len concat = mxnet:::mx.varg.symbol.Concat(output_list) #mx.symbol.infer.shape(concat, data = c(seq_len, batch_size))$out.shapes #Tip-4: Now we need to integrate 5 feature to 1 output by sequence. Convolution filter # can handle this situation. fc1_seqs = mx.symbol.Convolution(data = concat, kernel = c(1, 1), stride = c(1, 1), num.filter = 1, name = 'fc1_seqs') reshape_seqs_2 = mx.symbol.reshape(fc1_seqs, shape = c(seq_len, batch_size)) #loss_layer = mx.symbol.broadcast_minus(reshape_seqs_2, label) out_layer = mx.symbol.LinearRegressionOutput(data = reshape_seqs_2, name = 'out_layer') #3. Training model mx.set.seed(0) logger = mx.metric.logger$new() rnn_model = mx.model.FeedForward.create(out_layer, X = X.array, y = Y.array, ctx = mx.cpu(), num.round = 20, array.batch.size = batch_size, learning.rate = 0.0000000005, momentum = 0, wd = 0, array.layout = "colmajor", eval.metric = mx.metric.rmse, epoch.end.callback = mx.callback.log.train.metric(5, logger)) #4. Save and load model #4-1. Save model mx.model.save(rnn_model, "rnn_model", iteration = 0) #4-2. Load model My_model = mx.model.load("rnn_model", iteration = 0) #4-3. Inference predict_Y = predict(rnn_model, X.array, array.layout = "colmajor", array.batch.size = batch_size) RMSE = mean((predict_Y - Y.array)^2) print(RMSE)
# preliminary functions: ## Vectorize Dist: Function that takes a dataframe and returns a vectorized version of a distance matrix applied to that data matrix. ## This function is used for generating vectorized data when we step through the Mantel test. vectorize_dist <- function(df) { tmp <- dist(df) vec <- c(tmp) return(vec)} ## Pull P-Val and Pull F stat return the p-values and f-statstics from the list of output MultiPermanova puts out. pullPval <- function(x){temp <- x$aov.tab$`Pr(>F`[1]; return(temp)} pullFstat <- function(x){temp <- x$aov.tab$`F.Model`[1]; return(temp)} ### Old multipermanova function Generate_Holdout_Maps <- function(data, j, ...){ #hold out a single row of the data (in the jth row) #note - have to remove, as t-SNE doesn't like NAs data_holdout <- data[-j,] #calculate distances FIRST data_dist <- dist(data_holdout) #### Creates Maps (based on several methods) #generate the classical MDS mds1 <- cmdscale(data_dist, k = 2) #generate the t-SNE map and store x,y in map list x <- Rtsne(data_dist, perplexity = perplexity, pca = pca_options, is_distance = TRUE) return(list(mds = mds1, tsne = x$Y)) } MultiPermanova <- function(data, nperms = 5000, perplexity = 10, pca_options = FALSE){ # initialize the size of the data and output lists n <- nrow(data) maplist <- list() cmdlist <- list() #generate maps on holdout data for(j in 1:n){ temp <- Generate_Holdout_Maps(data, j) cmdlist[[j]] <- temp$mds maplist[[j]] <- temp$tsne } # Insert NAs into the holdout indices maplist_new <- list() cmdlist_new <- list() # for(j in 1:length(maplist)){ #create temporary vectors with NAs for each of the XY coordingates tempX <- R.utils::insert(maplist[[j]][,1], j, NA) tempY <- R.utils::insert(maplist[[j]][,2], j, NA) tempcmdX <- R.utils::insert(cmdlist[[j]][,1], j, NA) tempcmdY <- R.utils::insert(cmdlist[[j]][,2], j, NA) maplist_new[[j]] <- tibble(X = tempX, Y = tempY) cmdlist_new[[j]] <- tibble(X = tempcmdX, Y = tempcmdY) } #vectorizes the distances and outputs a list of vectorized distance matrices dist_list <- lapply(maplist_new, vectorize_dist) dist_list_cmd <- lapply(cmdlist_new, vectorize_dist) ## takes the vectorized distance matrices and smashes them into a single data frame - to build correlation matrix dist_mat <- dist_list %>% as_tibble(.name_repair = "minimal") dist_mat_cmd <- dist_list_cmd %>% as_tibble(.name_repair = "minimal") #had to remove the NAs here to get this to run (as it removes when I try to use complete.obs later on) #dist_df_na <- sapply(dist_mat, na.omit) %>% as_tibble(.name_repair = "minimal") #since I'm using pairwise complete obs, I shouldn't need to do this cormat <- cor(dist_mat, use = "pairwise.complete.obs", method = "pearson") cormat %>% dim() cormat_cmd <- cor(dist_mat_cmd, use = "pairwise.complete.obs", method = "pearson") cormat_cmd %>% dim() ##generate distance on correlation matrix cordist <- sqrt(2*(1-cormat)) %>% as.dist() cordist_cmd <- sqrt(2*(1-cormat_cmd)) %>% as.dist() model_list <- list() model_list_cmd <- list() #Step through the permanova method: for(j in 1: nrow(as.matrix(cordist))){ #generate the indicator variable for each feature indicator_df <- rep(0, nrow(maplist_new[[1]])) %>% as.data.frame() indicator_df_cmd <- rep(0, nrow(cmdlist_new[[1]])) %>% as.data.frame() names(indicator_df) <- names(indicator_df_cmd) <- "Indicator" indicator_df$Indicator[j] = 1 indicator_df_cmd$Indicator[j] = 1 #each item in the list is an Adonis test using the indicator for the holdout variable model_list[[j]] <- adonis(cordist ~ Indicator, data = indicator_df, permutations = nperms, parallel = 2) model_list_cmd[[j]] <- adonis(cordist_cmd ~ Indicator, data = indicator_df_cmd, permutations = nperms) #returns the list of ADONIS outputs } return(list(tsnelist = model_list, cmdlist = model_list_cmd, plot_tsne = maplist, plot_mds = cmdlist)) }
/OldOutlierCompFunctions.R
no_license
paulharmongj/tSNEBestPractices
R
false
false
4,164
r
# preliminary functions: ## Vectorize Dist: Function that takes a dataframe and returns a vectorized version of a distance matrix applied to that data matrix. ## This function is used for generating vectorized data when we step through the Mantel test. vectorize_dist <- function(df) { tmp <- dist(df) vec <- c(tmp) return(vec)} ## Pull P-Val and Pull F stat return the p-values and f-statstics from the list of output MultiPermanova puts out. pullPval <- function(x){temp <- x$aov.tab$`Pr(>F`[1]; return(temp)} pullFstat <- function(x){temp <- x$aov.tab$`F.Model`[1]; return(temp)} ### Old multipermanova function Generate_Holdout_Maps <- function(data, j, ...){ #hold out a single row of the data (in the jth row) #note - have to remove, as t-SNE doesn't like NAs data_holdout <- data[-j,] #calculate distances FIRST data_dist <- dist(data_holdout) #### Creates Maps (based on several methods) #generate the classical MDS mds1 <- cmdscale(data_dist, k = 2) #generate the t-SNE map and store x,y in map list x <- Rtsne(data_dist, perplexity = perplexity, pca = pca_options, is_distance = TRUE) return(list(mds = mds1, tsne = x$Y)) } MultiPermanova <- function(data, nperms = 5000, perplexity = 10, pca_options = FALSE){ # initialize the size of the data and output lists n <- nrow(data) maplist <- list() cmdlist <- list() #generate maps on holdout data for(j in 1:n){ temp <- Generate_Holdout_Maps(data, j) cmdlist[[j]] <- temp$mds maplist[[j]] <- temp$tsne } # Insert NAs into the holdout indices maplist_new <- list() cmdlist_new <- list() # for(j in 1:length(maplist)){ #create temporary vectors with NAs for each of the XY coordingates tempX <- R.utils::insert(maplist[[j]][,1], j, NA) tempY <- R.utils::insert(maplist[[j]][,2], j, NA) tempcmdX <- R.utils::insert(cmdlist[[j]][,1], j, NA) tempcmdY <- R.utils::insert(cmdlist[[j]][,2], j, NA) maplist_new[[j]] <- tibble(X = tempX, Y = tempY) cmdlist_new[[j]] <- tibble(X = tempcmdX, Y = tempcmdY) } #vectorizes the distances and outputs a list of vectorized distance matrices dist_list <- lapply(maplist_new, vectorize_dist) dist_list_cmd <- lapply(cmdlist_new, vectorize_dist) ## takes the vectorized distance matrices and smashes them into a single data frame - to build correlation matrix dist_mat <- dist_list %>% as_tibble(.name_repair = "minimal") dist_mat_cmd <- dist_list_cmd %>% as_tibble(.name_repair = "minimal") #had to remove the NAs here to get this to run (as it removes when I try to use complete.obs later on) #dist_df_na <- sapply(dist_mat, na.omit) %>% as_tibble(.name_repair = "minimal") #since I'm using pairwise complete obs, I shouldn't need to do this cormat <- cor(dist_mat, use = "pairwise.complete.obs", method = "pearson") cormat %>% dim() cormat_cmd <- cor(dist_mat_cmd, use = "pairwise.complete.obs", method = "pearson") cormat_cmd %>% dim() ##generate distance on correlation matrix cordist <- sqrt(2*(1-cormat)) %>% as.dist() cordist_cmd <- sqrt(2*(1-cormat_cmd)) %>% as.dist() model_list <- list() model_list_cmd <- list() #Step through the permanova method: for(j in 1: nrow(as.matrix(cordist))){ #generate the indicator variable for each feature indicator_df <- rep(0, nrow(maplist_new[[1]])) %>% as.data.frame() indicator_df_cmd <- rep(0, nrow(cmdlist_new[[1]])) %>% as.data.frame() names(indicator_df) <- names(indicator_df_cmd) <- "Indicator" indicator_df$Indicator[j] = 1 indicator_df_cmd$Indicator[j] = 1 #each item in the list is an Adonis test using the indicator for the holdout variable model_list[[j]] <- adonis(cordist ~ Indicator, data = indicator_df, permutations = nperms, parallel = 2) model_list_cmd[[j]] <- adonis(cordist_cmd ~ Indicator, data = indicator_df_cmd, permutations = nperms) #returns the list of ADONIS outputs } return(list(tsnelist = model_list, cmdlist = model_list_cmd, plot_tsne = maplist, plot_mds = cmdlist)) }
#' Title #' #' @param path #' @param pages Maximum number of pages to retrieve. #' #' @return #' @export #' #' @examples paginate <- function(path, query = NULL, pages = NULL, page_size = 50) { if (is.null(query)) query = list() # query = list() # query$start <- "2020-12-16T05:15:32.998Z" page <- 1 # # TODO: This is deeply inefficient? # results <- list() # while (TRUE) { result <- GET( path, query = c(query, list(page = page, "page-size" = page_size)) ) result <- content(result) records <- length(result) if (records == 0) { log_debug("Page is empty.") break } else { log_debug("Page contains {records} results.") } results <- append(results, result) if (!is.null(pages) && page >= pages) { break } else { page <- page + 1 } } log_debug("API returned {length(results)} results.") results }
/R/paginate.R
no_license
vusmas/clockify
R
false
false
916
r
#' Title #' #' @param path #' @param pages Maximum number of pages to retrieve. #' #' @return #' @export #' #' @examples paginate <- function(path, query = NULL, pages = NULL, page_size = 50) { if (is.null(query)) query = list() # query = list() # query$start <- "2020-12-16T05:15:32.998Z" page <- 1 # # TODO: This is deeply inefficient? # results <- list() # while (TRUE) { result <- GET( path, query = c(query, list(page = page, "page-size" = page_size)) ) result <- content(result) records <- length(result) if (records == 0) { log_debug("Page is empty.") break } else { log_debug("Page contains {records} results.") } results <- append(results, result) if (!is.null(pages) && page >= pages) { break } else { page <- page + 1 } } log_debug("API returned {length(results)} results.") results }
# Write a function that takes a directory of data files and a threshold # for complete cases and calculates the correlation between sulfate and nitrate # for monitor locations where the number of completely observed cases (on all variables) # is greater than the threshold. # The function should return a vector of correlations for the monitors that meet the threshold requirement. # If no monitors meet the threshold requirement, then the function should return a numeric vector of length 0. # A prototype of this function follows corr <- function(directory, threshold = 0) { ## 'directory' is a character vector of length 1 indicating ## the location of the CSV files ## 'threshold' is a numeric vector of length 1 indicating the ## number of completely observed observations (on all ## variables) required to compute the correlation between ## nitrate and sulfate; the default is 0 ## Return a numeric vector of correlations ## NOTE: Do not round the result! ## Utilisation de la library stringr pour retrouver un lpad correct #install.packages("stringr") library(stringr) ## Vector final o? seront stock?s les r?sultats de la fonction corr appliqu? ? chaque jeu de donn?es correct finalvector<-vector() ## Pour chaque capteur for(current_id in 1:332){ ## On cr?e le nom de fichier en s'appuyant sur str_pad (1->001.csv) filename <- paste(str_pad(current_id, width=3, side="left", pad="0"), ".csv", sep="") ## DEBUG #print(filename) ## On charge le fichier en cours dans une dataframe temporaire tempdf<-read.csv(file = paste(directory,"/", filename, sep="")) ## DEBUG #print(str(tempdf)) ## On calcule le nommbre de cas complets via complete.cases ## Le fichier 275 n'a aucun cas complet dans ce cas on affecte 0 ## Ici il faut optimiser car pour chaque fichier on recalcule 2 fois if(is.na(table(complete.cases(tempdf))["TRUE"])){ nbComplete<-0 }else { nbComplete<-table(complete.cases(tempdf))["TRUE"] } ##DEBUG #print(nbComplete) ## Si le dataset est correct le nombre de complete.Cases est sup?rieur au seuil if(nbComplete>threshold){ ## On s?lectionne les lignes compl?te du fichier en cours completeTempDf <- tempdf[complete.cases(tempdf),] ##DEBUG #print(str(completeTempDf)) ## On utilise la fonction corr sur les colonnes sulfate et nitrate et on ajoute le r?sultat au vecteur final finalvector<-c(finalvector, cor(completeTempDf$sulfate, completeTempDf$nitrate)) } ## On passe au fichier suivant } ## On output le vecteur final finalvector } # For this function you will need to use the 'cor' function in R which calculates the correlation between two vectors. # Please read the help page for this function via '?cor' and make sure that you know how to use it. # You can see some example output from this function. # The function that you write should be able to match this output. # Please save your code to a file named corr.R. To run the submit script for this part, # make sure your working directory has the file corr.R in it. directory = "./specdata" result<- corr(directory,400) head(result) str(result)
/R Programming/Programming Assignment 1 Air Pollution/corr.r
no_license
AliHmaou/datasciencecoursera
R
false
false
3,286
r
# Write a function that takes a directory of data files and a threshold # for complete cases and calculates the correlation between sulfate and nitrate # for monitor locations where the number of completely observed cases (on all variables) # is greater than the threshold. # The function should return a vector of correlations for the monitors that meet the threshold requirement. # If no monitors meet the threshold requirement, then the function should return a numeric vector of length 0. # A prototype of this function follows corr <- function(directory, threshold = 0) { ## 'directory' is a character vector of length 1 indicating ## the location of the CSV files ## 'threshold' is a numeric vector of length 1 indicating the ## number of completely observed observations (on all ## variables) required to compute the correlation between ## nitrate and sulfate; the default is 0 ## Return a numeric vector of correlations ## NOTE: Do not round the result! ## Utilisation de la library stringr pour retrouver un lpad correct #install.packages("stringr") library(stringr) ## Vector final o? seront stock?s les r?sultats de la fonction corr appliqu? ? chaque jeu de donn?es correct finalvector<-vector() ## Pour chaque capteur for(current_id in 1:332){ ## On cr?e le nom de fichier en s'appuyant sur str_pad (1->001.csv) filename <- paste(str_pad(current_id, width=3, side="left", pad="0"), ".csv", sep="") ## DEBUG #print(filename) ## On charge le fichier en cours dans une dataframe temporaire tempdf<-read.csv(file = paste(directory,"/", filename, sep="")) ## DEBUG #print(str(tempdf)) ## On calcule le nommbre de cas complets via complete.cases ## Le fichier 275 n'a aucun cas complet dans ce cas on affecte 0 ## Ici il faut optimiser car pour chaque fichier on recalcule 2 fois if(is.na(table(complete.cases(tempdf))["TRUE"])){ nbComplete<-0 }else { nbComplete<-table(complete.cases(tempdf))["TRUE"] } ##DEBUG #print(nbComplete) ## Si le dataset est correct le nombre de complete.Cases est sup?rieur au seuil if(nbComplete>threshold){ ## On s?lectionne les lignes compl?te du fichier en cours completeTempDf <- tempdf[complete.cases(tempdf),] ##DEBUG #print(str(completeTempDf)) ## On utilise la fonction corr sur les colonnes sulfate et nitrate et on ajoute le r?sultat au vecteur final finalvector<-c(finalvector, cor(completeTempDf$sulfate, completeTempDf$nitrate)) } ## On passe au fichier suivant } ## On output le vecteur final finalvector } # For this function you will need to use the 'cor' function in R which calculates the correlation between two vectors. # Please read the help page for this function via '?cor' and make sure that you know how to use it. # You can see some example output from this function. # The function that you write should be able to match this output. # Please save your code to a file named corr.R. To run the submit script for this part, # make sure your working directory has the file corr.R in it. directory = "./specdata" result<- corr(directory,400) head(result) str(result)
#1) Housekeeping rm(list = ls()) library(MARSS) library(lubridate) library(tidyverse) library('tseries') library('dplyr') library(quantmod) # 2) Get data from Quantmod and prepare data frame for estimation getSymbols('GDPC1',src='FRED') getSymbols('PAYEMS',from = "1947-01-01",src='FRED') getSymbols('INDPRO',from = "1947-01-01",src='FRED') getSymbols('RPI',from = "1947-01-01",src='FRED') GDP <- data.frame(date=index(GDPC1), coredata(GDPC1)) Emp <- data.frame(date=index(PAYEMS), coredata(PAYEMS)) Indpr <- data.frame(date=index(INDPRO), coredata(INDPRO)) Inc <- data.frame(date=index(RPI), coredata(RPI)) Emp <- Emp %>% filter(date>=as.Date("1947-01-01")&date<=as.Date("2020-06-01")) Indpr <-Indpr %>% filter(date>=as.Date("1947-01-01")&date<=as.Date("2020-06-01")) Inc <-Inc %>% filter(date>=as.Date("1947-01-01")&date<=as.Date("2020-06-01")) names(Inc) <- c("date","Inc") Inc_aux <- data.frame(seq.Date(as.Date("1947-01-01"), as.Date("1958-12-01") , by = "month")) Inc_aux$RPI <- NA names(Inc_aux) <-c("date","Inc") Inc <- rbind(Inc_aux,Inc) Emp$PAYEMS <- as.numeric(Emp$PAYEMS) Emp <- Emp %>% mutate(rate = PAYEMS/lag(PAYEMS,1)-1) Indpr$INDPRO <- as.numeric(Indpr$INDPRO) Indpr <- Indpr %>% mutate(rate = INDPRO/lag(INDPRO,1)-1) Inc$Inc <- as.numeric(Inc$Inc) Inc <- Inc %>% mutate(rate = Inc/lag(Inc,1)-1) GDP <- GDP %>% mutate(rate =GDPC1/lag(GDPC1,1)-1) GDP <- select(GDP, -c(GDPC1)) months <- lapply(X = GDP$date, FUN = seq.Date, by = "month", length.out = 3) months <- data.frame(date = do.call(what = c, months)) m_GDP <- left_join(x = months, y = GDP , by = "date") # Data frame for estimation df <- cbind(m_GDP,Emp$rate,Indpr$rate,Inc$rate) names(df) <- c("date","S01_GDP","S02_Emp","S03_Indpr","S04_Inc") # 3) Model 1: one quarterly series and two monthly series df_marss <- select(df, -c(S04_Inc)) df_marss <- df_marss %>% gather(key = "serie", value = "value", -date) df_marss <- df_marss %>% spread(key=date,value=value) df_marss$serie <- NULL df_marss <- as.matrix(df_marss) df_marss <- zscore(df_marss) # Matrix Z # Z <- matrix(list("0.33*z1","z2","z3", "0.67*z1",0,0, "z1",0,0, "0.67*z1",0,0, "0.33*z1",0,0, 1/3,0,0, 2/3,0,0, 1,0,0, 2/3,0,0, 1/3,0,0, 0,1,0, 0,0,0, 0,0,1, 0,0,0),3,14) m <- nrow(Z) p <- ncol(Z) # Matrix R R <- matrix(list(0),m,m) # Matrix B B <- matrix (list("b1",1,0,0,0,0,0,0,0,0,0,0,0,0, "b2",0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,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,"b6",1,0,0,0,0,0,0,0, 0,0,0,0,0,"b7",0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,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,"b11",1,0,0, 0,0,0,0,0,0,0,0,0,0,"b12",0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,"b13",1, 0,0,0,0,0,0,0,0,0,0,0,0,"b14",0),14,14) # Matrix Q Q <-matrix (list(1,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,"q6",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,"q11",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,"q13",0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0),14,14) Q[1,1]=1 # Other options for matrix Q # Q <- matrix(list(0),14,14) # Q <- ldiag(list("q1", 0,0,0,0,"q6",0,0,0,0,"q11",0)) # Q <- "diagonal and unequal" # Rest of matrices x0 <- matrix(0,p,1) A <- matrix(0,(length(df)-2),1) U <- matrix(0,p,1) V0 <- 5*diag(1,p) U <- matrix(0,p,1) # Estimation # Define model model.gen_1 =list(Z=Z,A=A,R=R,B=B,U=U,Q=Q,x0=x0,V0=V0,tinitx=1) # Estimation kf_ss_1= MARSS(df_marss, model=model.gen_1,control= list(trace=1,maxit = 300),method="BFGS") #,fun.kf = "MARSSkfss") summary(kf_ss_1) # 4) Model 2: one quarterly series and three monthly series df_marss <- df%>% gather(key = "serie", value = "value", -date) df_marss <- df_marss %>% spread(key=date,value=value) df_marss$serie <- NULL df_marss <- as.matrix(df_marss) #df_marss <- zscore(df_marss,mean.only=TRUE) # Matrix Z # Z <- matrix(list("0.33*z1","z2","z3","z4", "0.67*z1",0,0,0, "z1",0,0,0, "0.67*z1",0,0,0, "0.33*z1",0,0,0, 1/3,0,0,0, 2/3,0,0,0, 1,0,0,0, 2/3,0,0,0, 1/3,0,0,0, 0,1,0,0, 0,0,0,0, 0,0,1,0, 0,0,0,0, 0,0,0,1, 0,0,0,0),4,16) m <- nrow(Z) p <- ncol(Z) # Matrix R R <- matrix(list(0),m,m) # Matrix B B <- matrix (list("b1",1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, "b2",0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,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,"b6",1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,"b7",0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,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,"b11",1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,"b12",0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,"b13",1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,"b14",0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,"b15",1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,"b16",0),16,16) # Matrix Q Q <-matrix (list(1,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,"q6",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,"q11",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,"q13",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,"q15",0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),16,16) #Q[1,1]=1 # Q <- matrix(list(0),14,14) # Q <- ldiag(list("q1", 0,0,0,0,"q6",0,0,0,0,"q11",0)) # Q <- "diagonal and unequal" # Rest of matrices x0 <- matrix(0,p,1) A <- matrix(0,(length(df)-1),1) U <- matrix(0,p,1) V0 <- 5*diag(1,p) U <- matrix(0,p,1) # Estimation # Define model model.gen_2 =list(Z=Z,A=A,R=R,B=B,U=U,Q=Q,x0=x0,V0=V0,tinitx=1) # Estimation kf_ss_2= MARSS(df_marss, model=model.gen_2,control= list(trace=1,maxit = 300),method="BFGS") #,fun.kf = "MARSSkfss") summary(kf_ss_2) # Forecast YT kff <- forecast.marssMLE(kf_ss_2, h=12) plot(kff, include=50) # GDP Forecasat GDP_hat_T <- as.data.frame(kf_ss_2[["ytT"]]) GDP_hat_T <- select(kff[["pred"]], c(.rownames,estimate)) names(GDP_hat_T) <- c("variable","estimate") GDP_hat_T <- GDP_hat_T %>% dplyr::filter(variable == "Y1") GDP_hat_T$date <-(seq.Date(as.Date("1947-01-01"), as.Date("2021-06-01") , by = "month")) GDP_hat_T_Q <- GDP_hat_T%>% filter(month(GDP_hat_T$date) %in% c(3,6,9,12)) GDP_mean <- colMeans(subset(GDP, select=-c(date)), na.rm = TRUE) GDP_hat_T_Q <- GDP_hat_T_Q %>% mutate (annualized_rate = (estimate +GDP_mean+1)^4-1 ) # Forecast and fitted ytt kff_tt <- forecast.marssMLE(kf_ss_2, h=12, type="ytt") kff_fit_tt <- fitted(kf_ss_2, type="ytt")
/SS_MARSS_matrixP.R
no_license
Carherg/Error_example
R
false
false
8,556
r
#1) Housekeeping rm(list = ls()) library(MARSS) library(lubridate) library(tidyverse) library('tseries') library('dplyr') library(quantmod) # 2) Get data from Quantmod and prepare data frame for estimation getSymbols('GDPC1',src='FRED') getSymbols('PAYEMS',from = "1947-01-01",src='FRED') getSymbols('INDPRO',from = "1947-01-01",src='FRED') getSymbols('RPI',from = "1947-01-01",src='FRED') GDP <- data.frame(date=index(GDPC1), coredata(GDPC1)) Emp <- data.frame(date=index(PAYEMS), coredata(PAYEMS)) Indpr <- data.frame(date=index(INDPRO), coredata(INDPRO)) Inc <- data.frame(date=index(RPI), coredata(RPI)) Emp <- Emp %>% filter(date>=as.Date("1947-01-01")&date<=as.Date("2020-06-01")) Indpr <-Indpr %>% filter(date>=as.Date("1947-01-01")&date<=as.Date("2020-06-01")) Inc <-Inc %>% filter(date>=as.Date("1947-01-01")&date<=as.Date("2020-06-01")) names(Inc) <- c("date","Inc") Inc_aux <- data.frame(seq.Date(as.Date("1947-01-01"), as.Date("1958-12-01") , by = "month")) Inc_aux$RPI <- NA names(Inc_aux) <-c("date","Inc") Inc <- rbind(Inc_aux,Inc) Emp$PAYEMS <- as.numeric(Emp$PAYEMS) Emp <- Emp %>% mutate(rate = PAYEMS/lag(PAYEMS,1)-1) Indpr$INDPRO <- as.numeric(Indpr$INDPRO) Indpr <- Indpr %>% mutate(rate = INDPRO/lag(INDPRO,1)-1) Inc$Inc <- as.numeric(Inc$Inc) Inc <- Inc %>% mutate(rate = Inc/lag(Inc,1)-1) GDP <- GDP %>% mutate(rate =GDPC1/lag(GDPC1,1)-1) GDP <- select(GDP, -c(GDPC1)) months <- lapply(X = GDP$date, FUN = seq.Date, by = "month", length.out = 3) months <- data.frame(date = do.call(what = c, months)) m_GDP <- left_join(x = months, y = GDP , by = "date") # Data frame for estimation df <- cbind(m_GDP,Emp$rate,Indpr$rate,Inc$rate) names(df) <- c("date","S01_GDP","S02_Emp","S03_Indpr","S04_Inc") # 3) Model 1: one quarterly series and two monthly series df_marss <- select(df, -c(S04_Inc)) df_marss <- df_marss %>% gather(key = "serie", value = "value", -date) df_marss <- df_marss %>% spread(key=date,value=value) df_marss$serie <- NULL df_marss <- as.matrix(df_marss) df_marss <- zscore(df_marss) # Matrix Z # Z <- matrix(list("0.33*z1","z2","z3", "0.67*z1",0,0, "z1",0,0, "0.67*z1",0,0, "0.33*z1",0,0, 1/3,0,0, 2/3,0,0, 1,0,0, 2/3,0,0, 1/3,0,0, 0,1,0, 0,0,0, 0,0,1, 0,0,0),3,14) m <- nrow(Z) p <- ncol(Z) # Matrix R R <- matrix(list(0),m,m) # Matrix B B <- matrix (list("b1",1,0,0,0,0,0,0,0,0,0,0,0,0, "b2",0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,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,"b6",1,0,0,0,0,0,0,0, 0,0,0,0,0,"b7",0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,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,"b11",1,0,0, 0,0,0,0,0,0,0,0,0,0,"b12",0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,"b13",1, 0,0,0,0,0,0,0,0,0,0,0,0,"b14",0),14,14) # Matrix Q Q <-matrix (list(1,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,"q6",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,"q11",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,"q13",0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0),14,14) Q[1,1]=1 # Other options for matrix Q # Q <- matrix(list(0),14,14) # Q <- ldiag(list("q1", 0,0,0,0,"q6",0,0,0,0,"q11",0)) # Q <- "diagonal and unequal" # Rest of matrices x0 <- matrix(0,p,1) A <- matrix(0,(length(df)-2),1) U <- matrix(0,p,1) V0 <- 5*diag(1,p) U <- matrix(0,p,1) # Estimation # Define model model.gen_1 =list(Z=Z,A=A,R=R,B=B,U=U,Q=Q,x0=x0,V0=V0,tinitx=1) # Estimation kf_ss_1= MARSS(df_marss, model=model.gen_1,control= list(trace=1,maxit = 300),method="BFGS") #,fun.kf = "MARSSkfss") summary(kf_ss_1) # 4) Model 2: one quarterly series and three monthly series df_marss <- df%>% gather(key = "serie", value = "value", -date) df_marss <- df_marss %>% spread(key=date,value=value) df_marss$serie <- NULL df_marss <- as.matrix(df_marss) #df_marss <- zscore(df_marss,mean.only=TRUE) # Matrix Z # Z <- matrix(list("0.33*z1","z2","z3","z4", "0.67*z1",0,0,0, "z1",0,0,0, "0.67*z1",0,0,0, "0.33*z1",0,0,0, 1/3,0,0,0, 2/3,0,0,0, 1,0,0,0, 2/3,0,0,0, 1/3,0,0,0, 0,1,0,0, 0,0,0,0, 0,0,1,0, 0,0,0,0, 0,0,0,1, 0,0,0,0),4,16) m <- nrow(Z) p <- ncol(Z) # Matrix R R <- matrix(list(0),m,m) # Matrix B B <- matrix (list("b1",1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, "b2",0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,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,"b6",1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,"b7",0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,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,"b11",1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,"b12",0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,"b13",1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,"b14",0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,"b15",1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,"b16",0),16,16) # Matrix Q Q <-matrix (list(1,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,"q6",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,"q11",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,"q13",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,"q15",0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),16,16) #Q[1,1]=1 # Q <- matrix(list(0),14,14) # Q <- ldiag(list("q1", 0,0,0,0,"q6",0,0,0,0,"q11",0)) # Q <- "diagonal and unequal" # Rest of matrices x0 <- matrix(0,p,1) A <- matrix(0,(length(df)-1),1) U <- matrix(0,p,1) V0 <- 5*diag(1,p) U <- matrix(0,p,1) # Estimation # Define model model.gen_2 =list(Z=Z,A=A,R=R,B=B,U=U,Q=Q,x0=x0,V0=V0,tinitx=1) # Estimation kf_ss_2= MARSS(df_marss, model=model.gen_2,control= list(trace=1,maxit = 300),method="BFGS") #,fun.kf = "MARSSkfss") summary(kf_ss_2) # Forecast YT kff <- forecast.marssMLE(kf_ss_2, h=12) plot(kff, include=50) # GDP Forecasat GDP_hat_T <- as.data.frame(kf_ss_2[["ytT"]]) GDP_hat_T <- select(kff[["pred"]], c(.rownames,estimate)) names(GDP_hat_T) <- c("variable","estimate") GDP_hat_T <- GDP_hat_T %>% dplyr::filter(variable == "Y1") GDP_hat_T$date <-(seq.Date(as.Date("1947-01-01"), as.Date("2021-06-01") , by = "month")) GDP_hat_T_Q <- GDP_hat_T%>% filter(month(GDP_hat_T$date) %in% c(3,6,9,12)) GDP_mean <- colMeans(subset(GDP, select=-c(date)), na.rm = TRUE) GDP_hat_T_Q <- GDP_hat_T_Q %>% mutate (annualized_rate = (estimate +GDP_mean+1)^4-1 ) # Forecast and fitted ytt kff_tt <- forecast.marssMLE(kf_ss_2, h=12, type="ytt") kff_fit_tt <- fitted(kf_ss_2, type="ytt")
# REQUIRE TEST Monte Carlo poisson --------------------------------------------- test_that('REQUIRE TEST Monte Carlo poisson', { set.seed("123") z <- zpoisson$new() test.poisson <- z$mcunit(minx = 0, plot = FALSE) expect_true(test.poisson) }) # REQUIRE TEST poisson example ------------------------------------------------- test_that('REQUIRE TEST poisson example', { data(sanction) z.out <- zelig(num ~ target + coop, model = "poisson", data = sanction) x.out <- setx(z.out) s.out <- sim(z.out, x = x.out) expect_error(s.out$graph(), NA) }) # REQUIRE TEST poisson get_pvalue ------------------------------------------------- test_that('REQUIRE TEST poisson example', { data(sanction) z.out <- zelig(num ~ target + coop, model = "poisson", data = sanction) expect_error(z.out$get_pvalue(), NA) })
/tests/testthat/test-poisson.R
no_license
mbsabath/Zelig
R
false
false
840
r
# REQUIRE TEST Monte Carlo poisson --------------------------------------------- test_that('REQUIRE TEST Monte Carlo poisson', { set.seed("123") z <- zpoisson$new() test.poisson <- z$mcunit(minx = 0, plot = FALSE) expect_true(test.poisson) }) # REQUIRE TEST poisson example ------------------------------------------------- test_that('REQUIRE TEST poisson example', { data(sanction) z.out <- zelig(num ~ target + coop, model = "poisson", data = sanction) x.out <- setx(z.out) s.out <- sim(z.out, x = x.out) expect_error(s.out$graph(), NA) }) # REQUIRE TEST poisson get_pvalue ------------------------------------------------- test_that('REQUIRE TEST poisson example', { data(sanction) z.out <- zelig(num ~ target + coop, model = "poisson", data = sanction) expect_error(z.out$get_pvalue(), NA) })
dir_exist_create = function(main_dir, sub_dir){ output_dir = paste(main_dir,sub_dir,sep="") if (!dir.exists(output_dir)){ dir.create(output_dir) } return(output_dir) }
/methods/general/dir_exists_create_func.R
permissive
hkfrei/digital-forest-monitoring
R
false
false
186
r
dir_exist_create = function(main_dir, sub_dir){ output_dir = paste(main_dir,sub_dir,sep="") if (!dir.exists(output_dir)){ dir.create(output_dir) } return(output_dir) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/helpers.R \name{plot_ame} \alias{plot_ame} \title{Plot Average Marginal Effect Coefficient Plot} \usage{ plot_ame(mod1, nudge_y = 0.05, nudge_x = 0.1) } \description{ Plot Average Marginal Effect Coefficient Plot }
/man/plot_ame.Rd
no_license
jklevy/tidytemplate
R
false
true
293
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/helpers.R \name{plot_ame} \alias{plot_ame} \title{Plot Average Marginal Effect Coefficient Plot} \usage{ plot_ame(mod1, nudge_y = 0.05, nudge_x = 0.1) } \description{ Plot Average Marginal Effect Coefficient Plot }
createQseaSet=function(sampleTable,BSgenome,chr.select,Regions,window_size=250) { ## Parameter Check facI=sapply(sampleTable, is.factor) sampleTable[,facI] = sapply(sampleTable[,facI, drop=FALSE], as.character) rownames(sampleTable)=sampleTable$sample_name checkSampleTab(sampleTable) #must have: regions or bsgenome if( missing(BSgenome) && (missing(Regions) || class(Regions)!="GRanges" ) ) stop("Must specify a BSgenome library or a GRanges \"Regions\" object.") message("==== Creating qsea set ====") # sort chromosomes parameters=list(window_size=window_size) if(!missing(chr.select)){ chr.select=mixedsort(as.character(chr.select)) message("restricting analysis on ", paste(chr.select, collapse=", ")) } if (!missing(BSgenome)) { parameters[["BSgenome"]] = BSgenome } ## get Genomic Regions if (missing(Regions)){ message("Dividing selected chromosomes of ",BSgenome , " in ", window_size, "nt windows") Regions=makeGenomeWindows(BSgenome, chr.select, window_size) }else{ message("Dividing provided regions in ", window_size, "nt windows") Regions=subdivideRegions(Regions, chr.select,window_size, BSgenome) } chrN=seqlevels(Regions) cyM=matrix(2,nrow(sampleTable), length(chrN), dimnames=list(sampleTable$sample_name,chrN )) sexIdx=match(c("sex", "gender"), names(sampleTable)) sexIdx=head(sexIdx[!is.na(sexIdx)],1) if(length(sexIdx)==0){ sex=rep("unknown", nrow(sampleTable)) if(any(c("X", "Y","chrX", "chrY") %in% chrN)) warning("no column \"sex\" or \"gender\"found in sampleTable, ", "assuming heterozygosity for all selected chromosomes") }else{ sex=sampleTable[,sexIdx] mIdx=sex %in% c("M","m", "male") fIdx=sex %in% c("F","f", "female") yIdx=colnames(cyM) %in% c("Y", "chrY") xIdx=colnames(cyM) %in% c("X", "chrX") if (any(!(mIdx|fIdx))) warning("unknown sex specified sampleTable for sample(s) ", paste(rownames(cyM)[!(mIdx|fIdx)],collapse=", "), "; assuming heterozygosity for all selected chromosomes") cyM[mIdx,yIdx|xIdx]=1 cyM[fIdx,yIdx]=0 } qs=new('qseaSet', sampleTable=sampleTable, regions=Regions, zygosity=cyM, count_matrix=matrix(), cnv=GRanges(), #logFC parameters=parameters, libraries=list(), enrichment=list() ) } addNewSamples<-function(qs, sampleTable, force=FALSE, parallel=FALSE){ #check consistency of sample tables if( ncol(sampleTable) != ncol(getSampleTable(qs)) || ! all.equal(colnames(sampleTable) , colnames(getSampleTable(qs)))) stop("columns of sampleTable must match sample table in") old_samples=getSampleNames(qs) facI=sapply(sampleTable, is.factor) sampleTable[,facI] = sapply(sampleTable[,facI, drop=FALSE], as.character) rownames(sampleTable)=sampleTable$sample_name new=character(0) for (sa in rownames(sampleTable)){ if(sa %in% old_samples){ if(any(sampleTable[sa,]!=getSampleTable(qs,sa), na.rm=TRUE)) stop("sample ",sa, " is already contained in qs, and differs") else message(sa ," already contained in qs") }else new=c(new,sa) } if(length(new)==0) stop("no new samples found in sampleTable") sampleTable=sampleTable[new,] checkSampleTab(sampleTable) message("adding ",length(new), " new samples") w=FALSE if(hasCNV(qs)){ warning("CNVs for new samples can't be added to qsea set") w=TRUE } if(hasEnrichment(qs) ){ warning("Enrichment parameters for new samples can't be added to qsea set") w=TRUE } if (w && !force) stop("use force=TRUE to force adding new samples ", "by first removeing components that can't be added individually ", "for new samples") qs=setSampleTable(qs, rbind(getSampleTable(qs), sampleTable)) qs=setCNV(qs,GRanges()) #remove CNV qs=setEnrichment(qs,list()) #remove Enrichment chrN=mixedsort(levels(seqnames(getRegions(qs)))) cyM=matrix(2,nrow(sampleTable), length(chrN), dimnames=list(sampleTable$sample_name,chrN )) sexIdx=match(c("sex", "gender"), names(sampleTable)) sexIdx=head(sexIdx[!is.na(sexIdx)],1) if(length(sexIdx)==0){ sex=rep("unknown", nrow(sampleTable)) if(any(c("X", "Y","chrX", "chrY") %in% chrN)) warning("no column \"sex\" or \"gender\"found in sampleTable, ", "assuming heterozygosity for all selected chromosomes") }else{ sex=sampleTable[,sexIdx] mIdx=sex %in% c("M","m", "male") fIdx=sex %in% c("F","f", "female") yIdx=colnames(cyM) %in% c("Y", "chrY") xIdx=colnames(cyM) %in% c("X", "chrX") if (any(!(mIdx|fIdx))) warning("unknown sex specified sampleTable for sample(s) ", paste(rownames(cyM)[!(mIdx|fIdx)],collapse=", "), "; assuming heterozygosity for all selected chromosomes") cyM[mIdx,yIdx|xIdx]=1 cyM[fIdx,yIdx]=0 } qs=setZygosity(qs,rbind(getZygosity(qs), cyM)) if(nrow(getCounts(qs))==0) return(qs) #add counts for new samples fragment_length=getParameters(qs, "fragment_length") uniquePos=getParameters(qs, "uniquePos") minMapQual=getParameters(qs, "minMapQual") paired=getParameters(qs, "paired") fname_idx=which(names(sampleTable)=="file_name" )[1] # get the coverage if(parallel) { BPPARAM=bpparam() message("Scanning ",BiocParallel::bpnworkers(BPPARAM) , " files in parallel") }else BPPARAM=SerialParam() coverage=unlist(bplapply(X=sampleTable[,fname_idx],FUN=getCoverage, Regions=getRegions(qs),fragment_length=fragment_length, minMapQual=minMapQual, paired=paired, uniquePos=uniquePos, BPPARAM=BPPARAM ),FALSE, FALSE) libraries=rbind(getLibrary(qs,"file_name"), matrix(unlist(coverage[seq(2,length(coverage),by=2)],FALSE,FALSE), nrow(sampleTable),6, byrow=TRUE, dimnames=list(sampleTable$sample_name, c("total_fragments", "valid_fragments","library_factor", "fragment_length", "fragment_sd", "offset")))) coverage=cbind(getCounts(qs), matrix(unlist(coverage[seq(1,length(coverage),by=2)],FALSE,FALSE), ncol=nrow(sampleTable), byrow=FALSE, dimnames=list(NULL, sampleTable$sample_name))) qs=setCounts(qs,count_matrix=coverage) qs=setLibrary(qs, "file_name", libraries) #addOffset & estimateLibraryFactors hasLibF=any(!is.na(getLibrary(qs, "file_name")[,"library_factor"])) hasOffset=any(!is.na(getOffset(qs))) if(hasLibF){ qs=addLibraryFactors(qs) if(hasOffset) qs=addOffset(qs) } return(qs) } #for each window, calculate the sequence preference from low coverage input seq addSeqPref<-function(qs, seqPref,file_name, fragment_length, paired=FALSE, uniquePos=TRUE, alpha=0.05, pseudocount=5, cut=3){ if(! missing(seqPref) ){ if(class(seqPref)!="numeric") stop("Please provide sequence preference as log2FC") if(length(seqPref) != length(getRegions(qs))) stop("length of provided sequence preference", " does not match number of windows") }else{ if(missing(file_name)) stop("please specify column with file names for ", "sequence preference estimation") if(paired) fragment_length=NULL if(missing(fragment_length)) fragment_length=getFragmentLength(qs)[1] seqPref=findSeqPref(qs=qs, file_name="input", fragment_length=fragment_length, paired=paired, uniquePos=uniquePos, alpha=alpha, pseudocount=pseudocount, cut=cut) qs=setLibrary(qs, "SeqPref",seqPref$libraries) seqPref=seqPref$seqPref } qs=addRegionsFeature(qs, "seqPref",seqPref) if(! all(is.na(getOffset(qs,scale="rpkm") ) )) warning("Consider recalculating offset based ", "on new sequence preference") return(qs) } getFragmentLength<-function(qs){ lib=getLibrary(qs,"file_name") if(is.null( lib)) stop("no fragment length found... either specify parameter ", "\"fragment_length\" or run \"addCoverage()\" first.") r=rank(lib[,"fragment_length"] + lib[,"fragment_sd"]) idx=which.min(abs(r-length(r)/2)) #~which.median fragment_length=lib[idx,"fragment_length"] fragment_sd=lib[idx,"fragment_sd"] message("selecting fragment length (", round(fragment_length,2), ") and sd (", round(fragment_sd,2),") from sample ", getSampleNames(qs,idx), " as typical values") return(c(fragment_length,fragment_sd)) } addPatternDensity<-function(qs, pattern,name, fragment_length, fragment_sd, patternDensity, fixed=TRUE,masks=c("AGAPS","AMB", "RM", "TRF")[1:2]){ if(missing(patternDensity) ){ BSgenome=getGenome(qs) if(is.null(BSgenome)) stop("Pattern density calculation requires BSgenome") if(missing(pattern) ) stop("please provide sequence pattern for density estimation") if(missing(name)) name=pattern if(missing(fragment_length)){ fl=getFragmentLength(qs) fragment_length=fl[1] fragment_sd=fl[2] }else{ if(missing(fragment_sd)) fragment_sd=0 } patternDensity=estimatePatternDensity(Regions=getRegions(qs), pattern=pattern,BSgenome=BSgenome, fragment_length=fragment_length, fragment_sd=fragment_sd, fixed=fixed, masks=masks) } #if(! all(is.na(getOffset(qs,scale="rpkm") ) )) # warning("Consider recalculating offset based on new pattern density") if(missing(name)){ stop("please provide a name for the pattern") } #add density of pattern addRegionsFeature(qs,paste0(name,"_density"), patternDensity ) } addCoverage<-function(qs, fragment_length, uniquePos=TRUE, minMapQual=1, paired=FALSE, parallel=FALSE){ sampleTable=getSampleTable(qs) Regions=getRegions(qs) if(paired) fragment_length=NULL if(missing(fragment_length)) stop("for unpaired reads, please specify fragment length") fname_idx=which(names(sampleTable)=="file_name" )[1] # get the coverage if(parallel) { BPPARAM=bpparam() message("Scanning ",BiocParallel::bpnworkers(BPPARAM) , " files in parallel") }else BPPARAM=SerialParam() coverage=unlist(bplapply(X=sampleTable[,fname_idx],FUN=getCoverage, Regions=Regions,fragment_length=fragment_length, minMapQual=minMapQual, paired=paired, uniquePos=uniquePos, BPPARAM=BPPARAM ),FALSE, FALSE) libraries=matrix(unlist(coverage[seq(2,length(coverage),by=2)],FALSE,FALSE), nrow(sampleTable),6, byrow=TRUE, dimnames=list(sampleTable$sample_name, c("total_fragments", "valid_fragments","library_factor", "fragment_length", "fragment_sd", "offset"))) coverage=matrix(unlist(coverage[seq(1,length(coverage),by=2)],FALSE,FALSE), ncol=nrow(sampleTable), byrow=FALSE, dimnames=list(NULL, sampleTable$sample_name)) param=list(uniquePos=TRUE, minMapQual=minMapQual, paired=paired) qs=addParameters(qs,param) qs=setCounts(qs,count_matrix=coverage) setLibrary(qs, "file_name", libraries) } addLibraryFactors<-function(qs, factors,...){ if(!hasCounts(qs)) stop("No read counts found in qsea set. Run addCoverage first.") if(missing(factors)){ message("deriving TMM library factors for ", length(getSampleNames(qs))," samples" ) factors=estimateLibraryFactors(qs, ...) }else if (!is.numeric(factors) || (length(factors)!=1 && length(factors)!=length(getSampleNames(qs)) ) ){ stop("Number of factors does not mathch number of samples.") } lib=getLibrary(qs, "file_name") lib[, "library_factor"]=factors setLibrary(qs, "file_name", lib) } estimateLibraryFactors<-function(qs,trimA=c(.5,.99), trimM=c(.1,.9), doWeighting=TRUE, ref=1, plot=FALSE, nReg=500000){ if( length(trimM) != 2 || trimM[1]>=trimM[2] || trimM[1]<0 || trimM[2] > 1) stop("invalid trimM parameter for TMM: ", paste(trimM)) if( length(trimA) != 2 || trimA[1]>=trimA[2] || trimA[1]<0 || trimA[2] > 1) stop("invalid trimA parameter for TMM: ", paste(trimA)) n=length(getSampleNames(qs)) if(n==1) return (1) tmm=numeric(n) if (missing(ref)) ref=1 if(is.character(ref)) ref=which(getSampleNames(qs)==ref) if(is.na(ref) | !is.numeric(ref) |ref<1 | ref > n ) stop("invalid reference sample for TMM (",ref,")") others=seq_len(n)[-ref] libsz=getLibSize(qs, normalized=FALSE) normM=list(scaled=c("zygosity","cnv", "preference")) if(ncol(mcols(getRegions(qs)))>=1){ wd=which(!is.na(mcols(getRegions(qs))[,1])) wd=wd[seq(1,length(wd), ceiling(length(wd)/nReg))] }else{ tReg = length(getRegions(qs)) wd=seq(1,tReg, ceiling(tReg/nReg)) } values=getNormalizedValues(qs,methods=normM, windows=wd, samples=getSampleNames(qs) ) values[values<1]=NA if(plot){ row=ceiling(sqrt(n-1)) col=ceiling((n-1)/row) par(mfrow=c(row, col)) cr=colorRampPalette( c("white","skyblue", "blue", "yellow", "orange","red", "darkred")) } for(i in others){ a=log(values[,i])+log(values[,ref])-log(libsz[ref])-log(libsz[i]) m=log(values[,i])-log(values[,ref])+log(libsz[ref])-log(libsz[i]) thA=quantile(a, trimA, na.rm=TRUE) thM=quantile(m, trimM, na.rm=TRUE) sel=which(a>thA[1] & a < thA[2] & m>thM[1] &m<thM[2]) if(doWeighting){ w=1/(1/values[sel,ref]+1/values[sel,i]-1/libsz[ref]-1/libsz[i]) tmm[i]=sum(m[sel]*w)/sum(w) }else{ tmm[i]=mean(m[sel]) } if(plot){ smoothScatter(a,m, pch=20, colramp=cr, ylab="M", xlab="A", main=paste(getSampleNames(qs, c(i,ref)), collapse=" vs ")) abline(h=tmm[i], col="red", lwd=2) rect(thA[1], thM[1], thA[2], thM[2]) } } if(any(is.na(tmm))){ warning("tmm normalization faild") return(rep(1,n)) }else return(exp(tmm-mean(tmm))) } addEnrichmentParameters<-function(qs, enrichmentPattern, signal, windowIdx, min_wd=5,bins=seq(.5,40.5,1)){ if(missing (windowIdx)) stop("please specify the windows for enrichment analysis") if(missing (signal)) stop("please provide a signal matrix for the specified windows") if(missing(enrichmentPattern)) enrichmentPattern=getParameters(qs, "enrichmentPattern") if(is.null(enrichmentPattern)) stop("please specify sequence pattern for enrichment analysis") enrichment=estimateEnrichmentLM(qs,windowIdx=windowIdx, signal=signal, min_wd=min_wd,bins=bins, pattern_name=enrichmentPattern) parameters=fitEnrichmentProfile(enrichment$factors, enrichment$density, enrichment$n, minN=1) addParameters(qs,list(enrichmentPattern=enrichmentPattern)) setEnrichment(qs, c(list(parameters=parameters),enrichment)) } subdivideRegions<-function(Regions, chr.select,window_size, BSgenome){ if(missing(chr.select)) chr.select=mixedsort(seqlevels(Regions)) Regions=Regions[as.vector(seqnames(Regions)) %in% chr.select] #order according to chr.select seqlevels(Regions)=chr.select #merge overlapping windows Regions=reduce(sort(Regions)) ranges=ranges(Regions) #resize (enlarge) to a multiple of window_size pos=apply(FUN=function(x) seq(from=x[1], to=x[2], by=window_size), X=as.data.frame(ranges),MARGIN=1) if(class(pos)=="matrix"){ n=nrow(pos) pos=as.vector(pos) chr=rep(as.character(seqnames(Regions)), each=n) }else { n=sapply(X=pos,FUN=length) pos=unlist(pos) chr=rep(as.character(seqnames(Regions)), times=n) } if(!missing(BSgenome)){ chr_length=seqlengths(get(ls(paste("package:", BSgenome, sep="")))) seqinfo = Seqinfo(names(chr_length),chr_length, NA, BSgenome) }else{ seqinfo=seqinfo(Regions) } if(!missing(chr.select)){ seqinfo=seqinfo[chr.select] } return(GRanges(seqnames=chr, IRanges(start=pos, width=window_size), seqinfo=seqinfo)) } addOffset<-function(qs,enrichmentPattern , maxPatternDensity=0.01,offset){ if(missing(offset)){ if(missing(enrichmentPattern)) enrichmentPattern=getParameters(qs, "enrichmentPattern") if(is.null(enrichmentPattern)) stop("please specify sequence pattern for enrichment analysis") offset=estimateOffset(qs,enrichmentPattern, maxPatternDensity) } lib=getLibrary(qs, "file_name") lib[,"offset"]=offset qs= addParameters(qs,list(enrichmentPattern=enrichmentPattern)) setLibrary(qs, "file_name", lib) } checkSampleTab<-function(sampleTable){ if(missing(sampleTable) || !is.data.frame(sampleTable)) stop("Must specify a sample table (data.frame)") m=match(c("sample_name", "file_name", "group"),names(sampleTable)) if(any(is.na(m))) stop("sample table must contain \"sample_name\", ", "\"file_name\" and \"group\" columns") sname_idx=m[1] fname_idx=m[2] group_idx=m[3] if(length(unique(sampleTable[,sname_idx]))!=nrow(sampleTable)) stop("Sample names must be unique") wigFiles=FALSE bamFiles=FALSE errorMsg="" for(sNr in seq_len(nrow(sampleTable))){ if(file.exists(as.character(sampleTable[sNr,fname_idx]))){ tmp=strsplit(sampleTable[sNr,fname_idx], ".", fixed=TRUE)[[1]] if (tmp[length(tmp)] %in% c("gz","zip","bz2")){ tmp=tmp[-length(tmp)] } ext=tmp[length(tmp)] if(ext %in% c("wig","bw","bigwig")){ wigFiles=TRUE }else if(ext %in% c("bam","BAM","sam", "SAM")){ bamFiles=TRUE }else{ errorMsg=paste(errorMsg,"\nFiletype unknown:", sampleTable[sNr,fname_idx]) } }else{errorMsg=paste(errorMsg,"\nFile not found:", sampleTable[sNr,fname_idx])} } if (errorMsg !=""){ stop("Input file check failed:", errorMsg) } }
/R/qsea.createSet.R
no_license
auberginekenobi/qsea
R
false
false
19,069
r
createQseaSet=function(sampleTable,BSgenome,chr.select,Regions,window_size=250) { ## Parameter Check facI=sapply(sampleTable, is.factor) sampleTable[,facI] = sapply(sampleTable[,facI, drop=FALSE], as.character) rownames(sampleTable)=sampleTable$sample_name checkSampleTab(sampleTable) #must have: regions or bsgenome if( missing(BSgenome) && (missing(Regions) || class(Regions)!="GRanges" ) ) stop("Must specify a BSgenome library or a GRanges \"Regions\" object.") message("==== Creating qsea set ====") # sort chromosomes parameters=list(window_size=window_size) if(!missing(chr.select)){ chr.select=mixedsort(as.character(chr.select)) message("restricting analysis on ", paste(chr.select, collapse=", ")) } if (!missing(BSgenome)) { parameters[["BSgenome"]] = BSgenome } ## get Genomic Regions if (missing(Regions)){ message("Dividing selected chromosomes of ",BSgenome , " in ", window_size, "nt windows") Regions=makeGenomeWindows(BSgenome, chr.select, window_size) }else{ message("Dividing provided regions in ", window_size, "nt windows") Regions=subdivideRegions(Regions, chr.select,window_size, BSgenome) } chrN=seqlevels(Regions) cyM=matrix(2,nrow(sampleTable), length(chrN), dimnames=list(sampleTable$sample_name,chrN )) sexIdx=match(c("sex", "gender"), names(sampleTable)) sexIdx=head(sexIdx[!is.na(sexIdx)],1) if(length(sexIdx)==0){ sex=rep("unknown", nrow(sampleTable)) if(any(c("X", "Y","chrX", "chrY") %in% chrN)) warning("no column \"sex\" or \"gender\"found in sampleTable, ", "assuming heterozygosity for all selected chromosomes") }else{ sex=sampleTable[,sexIdx] mIdx=sex %in% c("M","m", "male") fIdx=sex %in% c("F","f", "female") yIdx=colnames(cyM) %in% c("Y", "chrY") xIdx=colnames(cyM) %in% c("X", "chrX") if (any(!(mIdx|fIdx))) warning("unknown sex specified sampleTable for sample(s) ", paste(rownames(cyM)[!(mIdx|fIdx)],collapse=", "), "; assuming heterozygosity for all selected chromosomes") cyM[mIdx,yIdx|xIdx]=1 cyM[fIdx,yIdx]=0 } qs=new('qseaSet', sampleTable=sampleTable, regions=Regions, zygosity=cyM, count_matrix=matrix(), cnv=GRanges(), #logFC parameters=parameters, libraries=list(), enrichment=list() ) } addNewSamples<-function(qs, sampleTable, force=FALSE, parallel=FALSE){ #check consistency of sample tables if( ncol(sampleTable) != ncol(getSampleTable(qs)) || ! all.equal(colnames(sampleTable) , colnames(getSampleTable(qs)))) stop("columns of sampleTable must match sample table in") old_samples=getSampleNames(qs) facI=sapply(sampleTable, is.factor) sampleTable[,facI] = sapply(sampleTable[,facI, drop=FALSE], as.character) rownames(sampleTable)=sampleTable$sample_name new=character(0) for (sa in rownames(sampleTable)){ if(sa %in% old_samples){ if(any(sampleTable[sa,]!=getSampleTable(qs,sa), na.rm=TRUE)) stop("sample ",sa, " is already contained in qs, and differs") else message(sa ," already contained in qs") }else new=c(new,sa) } if(length(new)==0) stop("no new samples found in sampleTable") sampleTable=sampleTable[new,] checkSampleTab(sampleTable) message("adding ",length(new), " new samples") w=FALSE if(hasCNV(qs)){ warning("CNVs for new samples can't be added to qsea set") w=TRUE } if(hasEnrichment(qs) ){ warning("Enrichment parameters for new samples can't be added to qsea set") w=TRUE } if (w && !force) stop("use force=TRUE to force adding new samples ", "by first removeing components that can't be added individually ", "for new samples") qs=setSampleTable(qs, rbind(getSampleTable(qs), sampleTable)) qs=setCNV(qs,GRanges()) #remove CNV qs=setEnrichment(qs,list()) #remove Enrichment chrN=mixedsort(levels(seqnames(getRegions(qs)))) cyM=matrix(2,nrow(sampleTable), length(chrN), dimnames=list(sampleTable$sample_name,chrN )) sexIdx=match(c("sex", "gender"), names(sampleTable)) sexIdx=head(sexIdx[!is.na(sexIdx)],1) if(length(sexIdx)==0){ sex=rep("unknown", nrow(sampleTable)) if(any(c("X", "Y","chrX", "chrY") %in% chrN)) warning("no column \"sex\" or \"gender\"found in sampleTable, ", "assuming heterozygosity for all selected chromosomes") }else{ sex=sampleTable[,sexIdx] mIdx=sex %in% c("M","m", "male") fIdx=sex %in% c("F","f", "female") yIdx=colnames(cyM) %in% c("Y", "chrY") xIdx=colnames(cyM) %in% c("X", "chrX") if (any(!(mIdx|fIdx))) warning("unknown sex specified sampleTable for sample(s) ", paste(rownames(cyM)[!(mIdx|fIdx)],collapse=", "), "; assuming heterozygosity for all selected chromosomes") cyM[mIdx,yIdx|xIdx]=1 cyM[fIdx,yIdx]=0 } qs=setZygosity(qs,rbind(getZygosity(qs), cyM)) if(nrow(getCounts(qs))==0) return(qs) #add counts for new samples fragment_length=getParameters(qs, "fragment_length") uniquePos=getParameters(qs, "uniquePos") minMapQual=getParameters(qs, "minMapQual") paired=getParameters(qs, "paired") fname_idx=which(names(sampleTable)=="file_name" )[1] # get the coverage if(parallel) { BPPARAM=bpparam() message("Scanning ",BiocParallel::bpnworkers(BPPARAM) , " files in parallel") }else BPPARAM=SerialParam() coverage=unlist(bplapply(X=sampleTable[,fname_idx],FUN=getCoverage, Regions=getRegions(qs),fragment_length=fragment_length, minMapQual=minMapQual, paired=paired, uniquePos=uniquePos, BPPARAM=BPPARAM ),FALSE, FALSE) libraries=rbind(getLibrary(qs,"file_name"), matrix(unlist(coverage[seq(2,length(coverage),by=2)],FALSE,FALSE), nrow(sampleTable),6, byrow=TRUE, dimnames=list(sampleTable$sample_name, c("total_fragments", "valid_fragments","library_factor", "fragment_length", "fragment_sd", "offset")))) coverage=cbind(getCounts(qs), matrix(unlist(coverage[seq(1,length(coverage),by=2)],FALSE,FALSE), ncol=nrow(sampleTable), byrow=FALSE, dimnames=list(NULL, sampleTable$sample_name))) qs=setCounts(qs,count_matrix=coverage) qs=setLibrary(qs, "file_name", libraries) #addOffset & estimateLibraryFactors hasLibF=any(!is.na(getLibrary(qs, "file_name")[,"library_factor"])) hasOffset=any(!is.na(getOffset(qs))) if(hasLibF){ qs=addLibraryFactors(qs) if(hasOffset) qs=addOffset(qs) } return(qs) } #for each window, calculate the sequence preference from low coverage input seq addSeqPref<-function(qs, seqPref,file_name, fragment_length, paired=FALSE, uniquePos=TRUE, alpha=0.05, pseudocount=5, cut=3){ if(! missing(seqPref) ){ if(class(seqPref)!="numeric") stop("Please provide sequence preference as log2FC") if(length(seqPref) != length(getRegions(qs))) stop("length of provided sequence preference", " does not match number of windows") }else{ if(missing(file_name)) stop("please specify column with file names for ", "sequence preference estimation") if(paired) fragment_length=NULL if(missing(fragment_length)) fragment_length=getFragmentLength(qs)[1] seqPref=findSeqPref(qs=qs, file_name="input", fragment_length=fragment_length, paired=paired, uniquePos=uniquePos, alpha=alpha, pseudocount=pseudocount, cut=cut) qs=setLibrary(qs, "SeqPref",seqPref$libraries) seqPref=seqPref$seqPref } qs=addRegionsFeature(qs, "seqPref",seqPref) if(! all(is.na(getOffset(qs,scale="rpkm") ) )) warning("Consider recalculating offset based ", "on new sequence preference") return(qs) } getFragmentLength<-function(qs){ lib=getLibrary(qs,"file_name") if(is.null( lib)) stop("no fragment length found... either specify parameter ", "\"fragment_length\" or run \"addCoverage()\" first.") r=rank(lib[,"fragment_length"] + lib[,"fragment_sd"]) idx=which.min(abs(r-length(r)/2)) #~which.median fragment_length=lib[idx,"fragment_length"] fragment_sd=lib[idx,"fragment_sd"] message("selecting fragment length (", round(fragment_length,2), ") and sd (", round(fragment_sd,2),") from sample ", getSampleNames(qs,idx), " as typical values") return(c(fragment_length,fragment_sd)) } addPatternDensity<-function(qs, pattern,name, fragment_length, fragment_sd, patternDensity, fixed=TRUE,masks=c("AGAPS","AMB", "RM", "TRF")[1:2]){ if(missing(patternDensity) ){ BSgenome=getGenome(qs) if(is.null(BSgenome)) stop("Pattern density calculation requires BSgenome") if(missing(pattern) ) stop("please provide sequence pattern for density estimation") if(missing(name)) name=pattern if(missing(fragment_length)){ fl=getFragmentLength(qs) fragment_length=fl[1] fragment_sd=fl[2] }else{ if(missing(fragment_sd)) fragment_sd=0 } patternDensity=estimatePatternDensity(Regions=getRegions(qs), pattern=pattern,BSgenome=BSgenome, fragment_length=fragment_length, fragment_sd=fragment_sd, fixed=fixed, masks=masks) } #if(! all(is.na(getOffset(qs,scale="rpkm") ) )) # warning("Consider recalculating offset based on new pattern density") if(missing(name)){ stop("please provide a name for the pattern") } #add density of pattern addRegionsFeature(qs,paste0(name,"_density"), patternDensity ) } addCoverage<-function(qs, fragment_length, uniquePos=TRUE, minMapQual=1, paired=FALSE, parallel=FALSE){ sampleTable=getSampleTable(qs) Regions=getRegions(qs) if(paired) fragment_length=NULL if(missing(fragment_length)) stop("for unpaired reads, please specify fragment length") fname_idx=which(names(sampleTable)=="file_name" )[1] # get the coverage if(parallel) { BPPARAM=bpparam() message("Scanning ",BiocParallel::bpnworkers(BPPARAM) , " files in parallel") }else BPPARAM=SerialParam() coverage=unlist(bplapply(X=sampleTable[,fname_idx],FUN=getCoverage, Regions=Regions,fragment_length=fragment_length, minMapQual=minMapQual, paired=paired, uniquePos=uniquePos, BPPARAM=BPPARAM ),FALSE, FALSE) libraries=matrix(unlist(coverage[seq(2,length(coverage),by=2)],FALSE,FALSE), nrow(sampleTable),6, byrow=TRUE, dimnames=list(sampleTable$sample_name, c("total_fragments", "valid_fragments","library_factor", "fragment_length", "fragment_sd", "offset"))) coverage=matrix(unlist(coverage[seq(1,length(coverage),by=2)],FALSE,FALSE), ncol=nrow(sampleTable), byrow=FALSE, dimnames=list(NULL, sampleTable$sample_name)) param=list(uniquePos=TRUE, minMapQual=minMapQual, paired=paired) qs=addParameters(qs,param) qs=setCounts(qs,count_matrix=coverage) setLibrary(qs, "file_name", libraries) } addLibraryFactors<-function(qs, factors,...){ if(!hasCounts(qs)) stop("No read counts found in qsea set. Run addCoverage first.") if(missing(factors)){ message("deriving TMM library factors for ", length(getSampleNames(qs))," samples" ) factors=estimateLibraryFactors(qs, ...) }else if (!is.numeric(factors) || (length(factors)!=1 && length(factors)!=length(getSampleNames(qs)) ) ){ stop("Number of factors does not mathch number of samples.") } lib=getLibrary(qs, "file_name") lib[, "library_factor"]=factors setLibrary(qs, "file_name", lib) } estimateLibraryFactors<-function(qs,trimA=c(.5,.99), trimM=c(.1,.9), doWeighting=TRUE, ref=1, plot=FALSE, nReg=500000){ if( length(trimM) != 2 || trimM[1]>=trimM[2] || trimM[1]<0 || trimM[2] > 1) stop("invalid trimM parameter for TMM: ", paste(trimM)) if( length(trimA) != 2 || trimA[1]>=trimA[2] || trimA[1]<0 || trimA[2] > 1) stop("invalid trimA parameter for TMM: ", paste(trimA)) n=length(getSampleNames(qs)) if(n==1) return (1) tmm=numeric(n) if (missing(ref)) ref=1 if(is.character(ref)) ref=which(getSampleNames(qs)==ref) if(is.na(ref) | !is.numeric(ref) |ref<1 | ref > n ) stop("invalid reference sample for TMM (",ref,")") others=seq_len(n)[-ref] libsz=getLibSize(qs, normalized=FALSE) normM=list(scaled=c("zygosity","cnv", "preference")) if(ncol(mcols(getRegions(qs)))>=1){ wd=which(!is.na(mcols(getRegions(qs))[,1])) wd=wd[seq(1,length(wd), ceiling(length(wd)/nReg))] }else{ tReg = length(getRegions(qs)) wd=seq(1,tReg, ceiling(tReg/nReg)) } values=getNormalizedValues(qs,methods=normM, windows=wd, samples=getSampleNames(qs) ) values[values<1]=NA if(plot){ row=ceiling(sqrt(n-1)) col=ceiling((n-1)/row) par(mfrow=c(row, col)) cr=colorRampPalette( c("white","skyblue", "blue", "yellow", "orange","red", "darkred")) } for(i in others){ a=log(values[,i])+log(values[,ref])-log(libsz[ref])-log(libsz[i]) m=log(values[,i])-log(values[,ref])+log(libsz[ref])-log(libsz[i]) thA=quantile(a, trimA, na.rm=TRUE) thM=quantile(m, trimM, na.rm=TRUE) sel=which(a>thA[1] & a < thA[2] & m>thM[1] &m<thM[2]) if(doWeighting){ w=1/(1/values[sel,ref]+1/values[sel,i]-1/libsz[ref]-1/libsz[i]) tmm[i]=sum(m[sel]*w)/sum(w) }else{ tmm[i]=mean(m[sel]) } if(plot){ smoothScatter(a,m, pch=20, colramp=cr, ylab="M", xlab="A", main=paste(getSampleNames(qs, c(i,ref)), collapse=" vs ")) abline(h=tmm[i], col="red", lwd=2) rect(thA[1], thM[1], thA[2], thM[2]) } } if(any(is.na(tmm))){ warning("tmm normalization faild") return(rep(1,n)) }else return(exp(tmm-mean(tmm))) } addEnrichmentParameters<-function(qs, enrichmentPattern, signal, windowIdx, min_wd=5,bins=seq(.5,40.5,1)){ if(missing (windowIdx)) stop("please specify the windows for enrichment analysis") if(missing (signal)) stop("please provide a signal matrix for the specified windows") if(missing(enrichmentPattern)) enrichmentPattern=getParameters(qs, "enrichmentPattern") if(is.null(enrichmentPattern)) stop("please specify sequence pattern for enrichment analysis") enrichment=estimateEnrichmentLM(qs,windowIdx=windowIdx, signal=signal, min_wd=min_wd,bins=bins, pattern_name=enrichmentPattern) parameters=fitEnrichmentProfile(enrichment$factors, enrichment$density, enrichment$n, minN=1) addParameters(qs,list(enrichmentPattern=enrichmentPattern)) setEnrichment(qs, c(list(parameters=parameters),enrichment)) } subdivideRegions<-function(Regions, chr.select,window_size, BSgenome){ if(missing(chr.select)) chr.select=mixedsort(seqlevels(Regions)) Regions=Regions[as.vector(seqnames(Regions)) %in% chr.select] #order according to chr.select seqlevels(Regions)=chr.select #merge overlapping windows Regions=reduce(sort(Regions)) ranges=ranges(Regions) #resize (enlarge) to a multiple of window_size pos=apply(FUN=function(x) seq(from=x[1], to=x[2], by=window_size), X=as.data.frame(ranges),MARGIN=1) if(class(pos)=="matrix"){ n=nrow(pos) pos=as.vector(pos) chr=rep(as.character(seqnames(Regions)), each=n) }else { n=sapply(X=pos,FUN=length) pos=unlist(pos) chr=rep(as.character(seqnames(Regions)), times=n) } if(!missing(BSgenome)){ chr_length=seqlengths(get(ls(paste("package:", BSgenome, sep="")))) seqinfo = Seqinfo(names(chr_length),chr_length, NA, BSgenome) }else{ seqinfo=seqinfo(Regions) } if(!missing(chr.select)){ seqinfo=seqinfo[chr.select] } return(GRanges(seqnames=chr, IRanges(start=pos, width=window_size), seqinfo=seqinfo)) } addOffset<-function(qs,enrichmentPattern , maxPatternDensity=0.01,offset){ if(missing(offset)){ if(missing(enrichmentPattern)) enrichmentPattern=getParameters(qs, "enrichmentPattern") if(is.null(enrichmentPattern)) stop("please specify sequence pattern for enrichment analysis") offset=estimateOffset(qs,enrichmentPattern, maxPatternDensity) } lib=getLibrary(qs, "file_name") lib[,"offset"]=offset qs= addParameters(qs,list(enrichmentPattern=enrichmentPattern)) setLibrary(qs, "file_name", lib) } checkSampleTab<-function(sampleTable){ if(missing(sampleTable) || !is.data.frame(sampleTable)) stop("Must specify a sample table (data.frame)") m=match(c("sample_name", "file_name", "group"),names(sampleTable)) if(any(is.na(m))) stop("sample table must contain \"sample_name\", ", "\"file_name\" and \"group\" columns") sname_idx=m[1] fname_idx=m[2] group_idx=m[3] if(length(unique(sampleTable[,sname_idx]))!=nrow(sampleTable)) stop("Sample names must be unique") wigFiles=FALSE bamFiles=FALSE errorMsg="" for(sNr in seq_len(nrow(sampleTable))){ if(file.exists(as.character(sampleTable[sNr,fname_idx]))){ tmp=strsplit(sampleTable[sNr,fname_idx], ".", fixed=TRUE)[[1]] if (tmp[length(tmp)] %in% c("gz","zip","bz2")){ tmp=tmp[-length(tmp)] } ext=tmp[length(tmp)] if(ext %in% c("wig","bw","bigwig")){ wigFiles=TRUE }else if(ext %in% c("bam","BAM","sam", "SAM")){ bamFiles=TRUE }else{ errorMsg=paste(errorMsg,"\nFiletype unknown:", sampleTable[sNr,fname_idx]) } }else{errorMsg=paste(errorMsg,"\nFile not found:", sampleTable[sNr,fname_idx])} } if (errorMsg !=""){ stop("Input file check failed:", errorMsg) } }
\name{difsurface.2D} \alias{difsurface.2D} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Function to plot two-dimensional difference surface } \description{ This function plots the surface representing the difference between the expected number correct score surfaces for the theta1, theta2 plane for two separate test forms. } \usage{ difsurface.2D(a1.1, a2.1, a1.2, a2.2, d1, d2, correlation = 0, azimuthal_angle = 0, colatitude_angle = 15, filename = "NA", type = "jpeg") } %- maybe also 'usage' for other objects documented here. \arguments{ \item{a1.1}{ A vector of test 1's item discrimination parameters for theta 1 } \item{a2.1}{ A vector of test 1's item discrimination parameters for theta 2 } \item{a1.2}{ A vector of test 2's item discrimination parameters for theta 1 } \item{a2.2}{ A vector of test 2's item discrimination parameters of theta 2 } \item{d1}{ A vector of test 1's item difficulty parameters } \item{d2}{ A vector of test 2's item difficulty parameters } \item{correlation}{ The correlation between theta 1 and theta 2. If the correlation is not equal to zero, the a1 and a2 will be transformed to maintain the orthogonal representation of the x and y axes. } \item{azimuthal_angle}{ The azimuthal viewing angle (east-west rotation) } \item{colatitude_angle}{ The colatitude viewing angle (north-south rotation) } \item{filename}{ The user specified filename given to save the plot; if the filename is provided, the function will automatically save the plot for the users by the provided filename. } \item{type}{ The format of files in which the user saves the plot. Options include (wmf, emf, png,jpg,jpeg,bmp,tif,tiff,ps,eps, pdf). } } \details{ The x-axis represents theta1, the y-axis represents theta2, and number correct difference score is on the z-axis. This function plots a surface of the difference between expected number correct scores for two test forms. This allows for the investigation of the degree of parallelism between the two test forms. When the difference surface lies at zero, it is evidence that the tests are parallel (Ackerman, 1996). } \references{ Ackerman,T.(1996),Graphical Representation of Multidimensional Item Response Theory Analyses,Applied Psychological Measurement,20(4),311-329. } \author{ Zhan Shu, Terry Ackerman, Matthew Burke } \seealso{\code{\link{difsurface.3D}},\code{\link{surface.2D}} \examples{ a1.1<-c(0.48,1.16,1.48,0.44,0.36,1.78,0.64,1.10,0.76,0.52,0.83,0.88,0.34,0.74, 0.66) a2.1<-c(0.54,0.35,0.44,1.72,0.69,0.47,1.21,1.74,0.89,0.53,0.41,0.98,0.59,0.59,0.70) a1.2<-c(0.58,0.16,0.48,0.84,0.76,0.78,1.64,1.10,1.76,1.52,0.53,0.58,0.54,0.84,0.76) a2.2<-c(1.54,1.35,1.44,1.72,1.69,1.47,0.21,0.74,0.99,0.83,0.71,0.68,0.79,0.69,0.78) d1<-c(-1.11,0.29,1.51,-0.82,-1.89,-0.49,1.35,0.82,-0.21,-0.04,-0.68, 0.22,-0.86,-1.33, 1.21) d2<-c(-1.11,0.29,1.51,-0.82,-1.89,-0.49,1.35,0.82,-0.21,-0.04,-0.68, 0.22,-0.86,-1.33, 1.21) difsurface.2D(a1.1,a2.1,a1.2,a2.2,d1,d2,correlation=0.3) }
/Visualization of Multi-dimensional Item Response Theory Model/man/difsurface.2D.Rd
no_license
zmeers/Visualization-of-Multidimensional-Item-Response-Theory-
R
false
false
3,013
rd
\name{difsurface.2D} \alias{difsurface.2D} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Function to plot two-dimensional difference surface } \description{ This function plots the surface representing the difference between the expected number correct score surfaces for the theta1, theta2 plane for two separate test forms. } \usage{ difsurface.2D(a1.1, a2.1, a1.2, a2.2, d1, d2, correlation = 0, azimuthal_angle = 0, colatitude_angle = 15, filename = "NA", type = "jpeg") } %- maybe also 'usage' for other objects documented here. \arguments{ \item{a1.1}{ A vector of test 1's item discrimination parameters for theta 1 } \item{a2.1}{ A vector of test 1's item discrimination parameters for theta 2 } \item{a1.2}{ A vector of test 2's item discrimination parameters for theta 1 } \item{a2.2}{ A vector of test 2's item discrimination parameters of theta 2 } \item{d1}{ A vector of test 1's item difficulty parameters } \item{d2}{ A vector of test 2's item difficulty parameters } \item{correlation}{ The correlation between theta 1 and theta 2. If the correlation is not equal to zero, the a1 and a2 will be transformed to maintain the orthogonal representation of the x and y axes. } \item{azimuthal_angle}{ The azimuthal viewing angle (east-west rotation) } \item{colatitude_angle}{ The colatitude viewing angle (north-south rotation) } \item{filename}{ The user specified filename given to save the plot; if the filename is provided, the function will automatically save the plot for the users by the provided filename. } \item{type}{ The format of files in which the user saves the plot. Options include (wmf, emf, png,jpg,jpeg,bmp,tif,tiff,ps,eps, pdf). } } \details{ The x-axis represents theta1, the y-axis represents theta2, and number correct difference score is on the z-axis. This function plots a surface of the difference between expected number correct scores for two test forms. This allows for the investigation of the degree of parallelism between the two test forms. When the difference surface lies at zero, it is evidence that the tests are parallel (Ackerman, 1996). } \references{ Ackerman,T.(1996),Graphical Representation of Multidimensional Item Response Theory Analyses,Applied Psychological Measurement,20(4),311-329. } \author{ Zhan Shu, Terry Ackerman, Matthew Burke } \seealso{\code{\link{difsurface.3D}},\code{\link{surface.2D}} \examples{ a1.1<-c(0.48,1.16,1.48,0.44,0.36,1.78,0.64,1.10,0.76,0.52,0.83,0.88,0.34,0.74, 0.66) a2.1<-c(0.54,0.35,0.44,1.72,0.69,0.47,1.21,1.74,0.89,0.53,0.41,0.98,0.59,0.59,0.70) a1.2<-c(0.58,0.16,0.48,0.84,0.76,0.78,1.64,1.10,1.76,1.52,0.53,0.58,0.54,0.84,0.76) a2.2<-c(1.54,1.35,1.44,1.72,1.69,1.47,0.21,0.74,0.99,0.83,0.71,0.68,0.79,0.69,0.78) d1<-c(-1.11,0.29,1.51,-0.82,-1.89,-0.49,1.35,0.82,-0.21,-0.04,-0.68, 0.22,-0.86,-1.33, 1.21) d2<-c(-1.11,0.29,1.51,-0.82,-1.89,-0.49,1.35,0.82,-0.21,-0.04,-0.68, 0.22,-0.86,-1.33, 1.21) difsurface.2D(a1.1,a2.1,a1.2,a2.2,d1,d2,correlation=0.3) }
setwd("~/Projects/immunity/musca/musca-immunity/R/") #code to analyis gene family evolution using Poisson linear models, and also export data subsets for CAFE analysis ##organize data #all.pois has the main dataset, need to add information about differential expression and immune function #first get immune annotations immune.ogs<-unique(mdom.all[,c("ogsid", "hmm", "dmel.imm")]) #need to collapse duplicated ogs immune.ogs<-immune.ogs[order(immune.ogs$ogsid, immune.ogs$hmm, immune.ogs$dmel.imm),] #NAs sort last immune.ogs<-subset(immune.ogs, !duplicated(ogsid)) #fix a few specific cases immune.ogs$dmel.imm[immune.ogs$ogsid=="14740.1"]="recognition" immune.ogs$hmm[immune.ogs$ogsid=="8194"]="DIPT" immune.ogs$hmm<-as.character(immune.ogs$hmm) immune.ogs$hmm[is.na(immune.ogs$hmm)]="none" immune.ogs$dmel.imm[is.na(immune.ogs$dmel.imm)]="none" immune.ogs$dmel.imm[immune.ogs$dmel.imm=="modulation;signaling"] = "signaling" immune.ogs$dmel.imm[immune.ogs$dmel.imm=="effector;recognition"] = "recognition" #add to all.pois all.pois<-merge(all.pois, immune.ogs, by.x="ogs", by.y="ogsid", all.x=T, all.y=F) all.pois$dmel.imm = factor(all.pois$dmel.imm, levels=c("none", "recognition", "signaling", "modulation", "effector")) all.pois$musca = factor(all.pois$musca, levels=c("other_dipt", "musca")) all.pois$hmm = factor(all.pois$hmm) all.pois$hmm = relevel(all.pois$hmm, ref="none") all.pois = subset(all.pois, events > 0) all.pois$immune.narrow = as.factor(all.pois$dmel.imm!="none") all.pois$immune.broad = all.pois$immune.narrow all.pois$immune.broad[all.pois$hmm != "none"] = TRUE #now run models on all.pois #first, look at main results -- recognition, modulation, signaling, and effector differences on musca branch and overall require(multcomp) require(lme4) #result 1 -- musca vs other dipts for immune vs non-immune musca.imm.test.dup<-glmer(count ~ musca*immune.narrow+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root")) musca.imm.test.loss<-glmer(count ~ musca*immune.narrow+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="loss" & nodeclass != "root")) musca.imm.test.tot<-glmer(count ~ musca*immune.narrow+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root")) #note convergence issues in total, use allFit in afex package to examine library(afex) library(optimx) library(nloptr) musca.imm.test.tot.conv<-allFit(musca.imm.test.tot) is.OK<-sapply(musca.imm.test.tot.conv, is, "merMod") musca.imm.test.tot.conv.ok<-musca.imm.test.tot.conv[is.OK] lapply(musca.imm.test.tot.conv.ok, function(x) x@optinfo$conv$lme4$messages) #convergence looks good using bobyqa, look at that result summary(musca.imm.test.tot.conv.ok$bobyqa) summary(musca.imm.test.dup) summary(musca.imm.test.loss) #broadly defined immune genes musca.imm.test.dup.br<-glmer(count ~ musca*immune.broad+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root")) musca.imm.test.loss.br<-glmer(count ~ musca*immune.broad+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="loss" & nodeclass != "root")) musca.imm.test.tot.br<-glmer(count ~ musca*immune.broad+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root")) #total model also has convergence problems with broad immmune definition, use same approach as before musca.imm.test.tot.br.conv<-allFit(musca.imm.test.tot.br) is.OK<-sapply(musca.imm.test.tot.br.conv, is, "merMod") musca.imm.test.tot.br.conv.ok<-musca.imm.test.tot.br.conv[is.OK] lapply(musca.imm.test.tot.br.conv.ok, function(x) x@optinfo$conv$lme4$messages) #convergence looks good using bobyqa, look at that result summary(musca.imm.test.tot.br.conv.ok$bobyqa) #is this driven by something funny going on in Drosophila (streamlined genomes)? Look at different families separately #do this with family-based linear regression and specific contrasts all.pois$family = factor(all.pois$family, levels=c("Muscidae", "Diptera", "Drosophilidae", "Glossinidae", "Culicidae")) fam.imm.test.dup<-glmer(count ~ family*immune.narrow + offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root" & family != "Diptera")), glmerControl(optimizer=c("bobyqa"))) fam.imm.test.loss<-glmer(count ~ family*immune.narrow + offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="loss" & nodeclass != "root" & family != "Diptera")), glmerControl(optimizer=c("bobyqa"))) fam.imm.test.tot<-glmer(count ~ family*immune.narrow + offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root" & family != "Diptera")), glmerControl(optimizer=c("bobyqa"))) #now test by immune class musca.immclass.test<-glmer(count ~ musca*dmel.imm+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root"), glmerControl(optimizer=c("bobyqa"))) #try other optimizers musca.immclass.test.conv<-allFit(musca.immclass.test) is.OK<-sapply(musca.immclass.test.conv, is, "merMod") musca.immclass.test.conv.ok<-musca.immclass.test.conv[is.OK] lapply(musca.immclass.test.conv.ok, function(x) x@optinfo$conv$lme4$messages) #musca.immclass.test.conv.ok$optimx.nlminb muscaVdipt_rec_dup=matrix(c(0,0,1,0,0,0,1,0,0,0)-c(0,0,1,0,0,0,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_rec_dup"))) muscaVdipt_sig_dup=matrix(c(0,0,0,1,0,0,0,1,0,0)-c(0,0,0,1,0,0,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_sig_dup"))) muscaVdipt_mod_dup=matrix(c(0,0,0,0,1,0,0,0,1,0)-c(0,0,0,0,1,0,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_mod_dup"))) muscaVdipt_eff_dup=matrix(c(0,0,0,0,0,1,0,0,0,1)-c(0,0,0,0,0,1,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_eff_dup"))) byclass_cont=rbind(muscaVdipt_rec_dup,muscaVdipt_eff_dup, muscaVdipt_mod_dup, muscaVdipt_sig_dup) colnames(byclass_cont)=names(fixef(musca.immclass.test)) summary(glht(musca.immclass.test.conv.ok$optimx.nlminb, linfct=byclass_cont)) summary(musca.immclass.test.conv.ok$optimx.nlminb) #rec, sig, mod, eff by family - duplication musca.immclass.byfam<-glmer(count ~ family*dmel.imm+offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root" & family != "Diptera"))) #convergence checks musca.immclass.byfam.conv<-allFit(musca.immclass.byfam) is.OK<-sapply(musca.immclass.byfam.conv, is, "merMod") musca.immclass.byfam.conv.ok<-musca.immclass.byfam.conv[is.OK] lapply(musca.immclass.byfam.conv.ok, function(x) x@optinfo$conv$lme4$messages) #still no convergence so try rerunning with optimx.nlimnb which is closest ss <- getME(musca.immclass.byfam.conv$optimx.nlminb,c("theta","fixef")) musca.immclass.byfam.2 <- update(musca.immclass.byfam.conv$optimx.nlminb,start=ss,control=glmerControl(optCtrl=list(method="nlminb"),optimizer="optimx")) byfam.contrasts<-matrix(data=0, nrow=12, ncol=length(fixef(musca.immclass.byfam.2))) rownames(byfam.contrasts)=c("Dros_rec", "Glos_rec", "Cul_rec", "Dros_sig", "Glos_sig", "Cul_sig", "Dros_mod", "Glos_mod", "Cul_mod", "Dros_eff", "Glos_eff", "Cul_eff") for (i in 1:12) { byfam.contrasts[i, i+8] = -1 } colnames(byfam.contrasts)=names(fixef(musca.immclass.byfam.2)) summary(glht(musca.immclass.byfam.2, linfct=byfam.contrasts)) #analysis by HMM-defined gene family musca.immhmm.test<-glmer(count ~ musca*hmm+offset(log(br))+(1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root")) #convergence failed, so let's try again with a different optimizer ss <- getME(musca.immhmm.test,c("theta","fixef")) musca.immhmm.test.2<-update(musca.immhmm.test, start=ss, control=glmerControl(optimizer="bobyqa", optCtrl=list(maxfun=2e5))) #check for singulariy tt <- getME(musca.immhmm.test.2,"theta") ll <- getME(musca.immhmm.test.2,"lower") min(tt[ll==0]) #check gradient calcs derivs1 <- musca.immhmm.test.2@optinfo$derivs sc_grad1 <- with(derivs1,solve(Hessian,gradient)) max(abs(sc_grad1)) dd <- update(musca.immhmm.test.2,devFunOnly=TRUE) pars <- unlist(getME(musca.immhmm.test.2,c("theta","fixef"))) grad2 <- grad(dd,pars) hess2 <- hessian(dd,pars) sc_grad2 <- solve(hess2,grad2) max(pmin(abs(sc_grad2),abs(grad2))) #still not converging...hmmm. #get results anyway...will eventually try running with different optimizers ##NOT RUN## #try with a bunch of optimizers musca.immhmm.test.conv<-allFit(musca.immhmm.test.2) is.OK<-sapply(musca.immhmm.test.conv, is, "merMod") musca.immhmm.test.conv.ok<-musca.immhmm.test.conv[is.OK] lapply(musca.immhmm.test.conv, function(x) x@optinfo$conv$lme4$messages) ##</NOT RUN> fams=c("BGBP", "CEC", "CLIPA", "CLIPB", "CLIPC", "CLIPD", "CTL", "FREP", "GALE", "HPX", "IGSF", "LYS", "MD2L", "NFKB", "NIM", "PGRP", "PPO", "SPRN", "SRCA", "SRCB", "SRCC", "TEP", "TLL", "TPX", "TSF") hmm_conts<-matrix(0, ncol=length(names(fixef(musca.immhmm.test.2))), nrow=length(fams), dimnames=list(fams,names(fixef(musca.immhmm.test.2)))) for (i in 1:length(fams)) { hmm_conts[i,i+27]=1 } summary(glht(musca.immhmm.test.2, linfct=hmm_conts)) #by lineage for a specific gene family for (test in c("TEP", "LYS", "CEC")) { selected_fam=test musca.immhmm.family<-glmer(count ~ family*(hmm==selected_fam)+offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root" & family != "Diptera" & family != "Glossinidae"))) #make tests fams=c("Dros", "Cul") hmm_conts<-matrix(0, ncol=length(names(fixef(musca.immhmm.family))), nrow=length(fams), dimnames=list(fams,names(fixef(musca.immhmm.family)))) for (i in 1:nrow(hmm_conts)) { hmm_conts[i,i+4]=-1 } print(summary(glht(musca.immhmm.family, linfct=hmm_conts))) } #look at per-ogs rate per.ogs.data<-droplevels(subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root")) per.ogs.results<-data.frame(ogs=character(length(unique(per.ogs.data$ogs))), rate=numeric(length(unique(per.ogs.data$ogs))), pval=numeric(length(unique(per.ogs.data$ogs))), stringsAsFactors=F) ogs.list<-as.character(unique(per.ogs.data$ogs)) for (i in 1:length(ogs.list)) { ogs<-ogs.list[i] ogs.data<-per.ogs.data[per.ogs.data$ogs == ogs,] per.ogs.results[i,1]=ogs per.ogs.results[i,c(2,3)]=coef(summary(glm(count ~ musca + offset(log(br)), family=poisson, data=ogs.data)))[2,c(1,4)] } per.ogs.results$qval = p.adjust(per.ogs.results$pval, method="fdr") #add annotations per.ogs.results.annot <- merge(per.ogs.results, unique(all.pois[,c("ogs", "hmm", "dmel.imm", "immune.narrow", "immune.broad")]), by="ogs") #fisher tests fisher.test(table(per.ogs.results.annot$qval < 0.05 & per.ogs.results.annot$rate > 0, per.ogs.results.annot$immune.broad)) table(per.ogs.results.annot$qval < 0.05 & per.ogs.results.annot$rate > 0, per.ogs.results.annot$immune.broad) per.ogs.results.annot[per.ogs.results.annot$qval < 0.05 & per.ogs.results.annot$rate > 0 & per.ogs.results.annot$immune.broad==T,]
/R/duploss_analysis.R
no_license
tsackton/musca-immunity
R
false
false
11,268
r
setwd("~/Projects/immunity/musca/musca-immunity/R/") #code to analyis gene family evolution using Poisson linear models, and also export data subsets for CAFE analysis ##organize data #all.pois has the main dataset, need to add information about differential expression and immune function #first get immune annotations immune.ogs<-unique(mdom.all[,c("ogsid", "hmm", "dmel.imm")]) #need to collapse duplicated ogs immune.ogs<-immune.ogs[order(immune.ogs$ogsid, immune.ogs$hmm, immune.ogs$dmel.imm),] #NAs sort last immune.ogs<-subset(immune.ogs, !duplicated(ogsid)) #fix a few specific cases immune.ogs$dmel.imm[immune.ogs$ogsid=="14740.1"]="recognition" immune.ogs$hmm[immune.ogs$ogsid=="8194"]="DIPT" immune.ogs$hmm<-as.character(immune.ogs$hmm) immune.ogs$hmm[is.na(immune.ogs$hmm)]="none" immune.ogs$dmel.imm[is.na(immune.ogs$dmel.imm)]="none" immune.ogs$dmel.imm[immune.ogs$dmel.imm=="modulation;signaling"] = "signaling" immune.ogs$dmel.imm[immune.ogs$dmel.imm=="effector;recognition"] = "recognition" #add to all.pois all.pois<-merge(all.pois, immune.ogs, by.x="ogs", by.y="ogsid", all.x=T, all.y=F) all.pois$dmel.imm = factor(all.pois$dmel.imm, levels=c("none", "recognition", "signaling", "modulation", "effector")) all.pois$musca = factor(all.pois$musca, levels=c("other_dipt", "musca")) all.pois$hmm = factor(all.pois$hmm) all.pois$hmm = relevel(all.pois$hmm, ref="none") all.pois = subset(all.pois, events > 0) all.pois$immune.narrow = as.factor(all.pois$dmel.imm!="none") all.pois$immune.broad = all.pois$immune.narrow all.pois$immune.broad[all.pois$hmm != "none"] = TRUE #now run models on all.pois #first, look at main results -- recognition, modulation, signaling, and effector differences on musca branch and overall require(multcomp) require(lme4) #result 1 -- musca vs other dipts for immune vs non-immune musca.imm.test.dup<-glmer(count ~ musca*immune.narrow+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root")) musca.imm.test.loss<-glmer(count ~ musca*immune.narrow+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="loss" & nodeclass != "root")) musca.imm.test.tot<-glmer(count ~ musca*immune.narrow+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root")) #note convergence issues in total, use allFit in afex package to examine library(afex) library(optimx) library(nloptr) musca.imm.test.tot.conv<-allFit(musca.imm.test.tot) is.OK<-sapply(musca.imm.test.tot.conv, is, "merMod") musca.imm.test.tot.conv.ok<-musca.imm.test.tot.conv[is.OK] lapply(musca.imm.test.tot.conv.ok, function(x) x@optinfo$conv$lme4$messages) #convergence looks good using bobyqa, look at that result summary(musca.imm.test.tot.conv.ok$bobyqa) summary(musca.imm.test.dup) summary(musca.imm.test.loss) #broadly defined immune genes musca.imm.test.dup.br<-glmer(count ~ musca*immune.broad+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root")) musca.imm.test.loss.br<-glmer(count ~ musca*immune.broad+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="loss" & nodeclass != "root")) musca.imm.test.tot.br<-glmer(count ~ musca*immune.broad+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root")) #total model also has convergence problems with broad immmune definition, use same approach as before musca.imm.test.tot.br.conv<-allFit(musca.imm.test.tot.br) is.OK<-sapply(musca.imm.test.tot.br.conv, is, "merMod") musca.imm.test.tot.br.conv.ok<-musca.imm.test.tot.br.conv[is.OK] lapply(musca.imm.test.tot.br.conv.ok, function(x) x@optinfo$conv$lme4$messages) #convergence looks good using bobyqa, look at that result summary(musca.imm.test.tot.br.conv.ok$bobyqa) #is this driven by something funny going on in Drosophila (streamlined genomes)? Look at different families separately #do this with family-based linear regression and specific contrasts all.pois$family = factor(all.pois$family, levels=c("Muscidae", "Diptera", "Drosophilidae", "Glossinidae", "Culicidae")) fam.imm.test.dup<-glmer(count ~ family*immune.narrow + offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root" & family != "Diptera")), glmerControl(optimizer=c("bobyqa"))) fam.imm.test.loss<-glmer(count ~ family*immune.narrow + offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="loss" & nodeclass != "root" & family != "Diptera")), glmerControl(optimizer=c("bobyqa"))) fam.imm.test.tot<-glmer(count ~ family*immune.narrow + offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root" & family != "Diptera")), glmerControl(optimizer=c("bobyqa"))) #now test by immune class musca.immclass.test<-glmer(count ~ musca*dmel.imm+offset(log(br)) + (1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root"), glmerControl(optimizer=c("bobyqa"))) #try other optimizers musca.immclass.test.conv<-allFit(musca.immclass.test) is.OK<-sapply(musca.immclass.test.conv, is, "merMod") musca.immclass.test.conv.ok<-musca.immclass.test.conv[is.OK] lapply(musca.immclass.test.conv.ok, function(x) x@optinfo$conv$lme4$messages) #musca.immclass.test.conv.ok$optimx.nlminb muscaVdipt_rec_dup=matrix(c(0,0,1,0,0,0,1,0,0,0)-c(0,0,1,0,0,0,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_rec_dup"))) muscaVdipt_sig_dup=matrix(c(0,0,0,1,0,0,0,1,0,0)-c(0,0,0,1,0,0,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_sig_dup"))) muscaVdipt_mod_dup=matrix(c(0,0,0,0,1,0,0,0,1,0)-c(0,0,0,0,1,0,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_mod_dup"))) muscaVdipt_eff_dup=matrix(c(0,0,0,0,0,1,0,0,0,1)-c(0,0,0,0,0,1,0,0,0,0),nrow=1, dimnames=list(c("muscaVdipt_eff_dup"))) byclass_cont=rbind(muscaVdipt_rec_dup,muscaVdipt_eff_dup, muscaVdipt_mod_dup, muscaVdipt_sig_dup) colnames(byclass_cont)=names(fixef(musca.immclass.test)) summary(glht(musca.immclass.test.conv.ok$optimx.nlminb, linfct=byclass_cont)) summary(musca.immclass.test.conv.ok$optimx.nlminb) #rec, sig, mod, eff by family - duplication musca.immclass.byfam<-glmer(count ~ family*dmel.imm+offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root" & family != "Diptera"))) #convergence checks musca.immclass.byfam.conv<-allFit(musca.immclass.byfam) is.OK<-sapply(musca.immclass.byfam.conv, is, "merMod") musca.immclass.byfam.conv.ok<-musca.immclass.byfam.conv[is.OK] lapply(musca.immclass.byfam.conv.ok, function(x) x@optinfo$conv$lme4$messages) #still no convergence so try rerunning with optimx.nlimnb which is closest ss <- getME(musca.immclass.byfam.conv$optimx.nlminb,c("theta","fixef")) musca.immclass.byfam.2 <- update(musca.immclass.byfam.conv$optimx.nlminb,start=ss,control=glmerControl(optCtrl=list(method="nlminb"),optimizer="optimx")) byfam.contrasts<-matrix(data=0, nrow=12, ncol=length(fixef(musca.immclass.byfam.2))) rownames(byfam.contrasts)=c("Dros_rec", "Glos_rec", "Cul_rec", "Dros_sig", "Glos_sig", "Cul_sig", "Dros_mod", "Glos_mod", "Cul_mod", "Dros_eff", "Glos_eff", "Cul_eff") for (i in 1:12) { byfam.contrasts[i, i+8] = -1 } colnames(byfam.contrasts)=names(fixef(musca.immclass.byfam.2)) summary(glht(musca.immclass.byfam.2, linfct=byfam.contrasts)) #analysis by HMM-defined gene family musca.immhmm.test<-glmer(count ~ musca*hmm+offset(log(br))+(1|ogs), family="poisson", data=subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root")) #convergence failed, so let's try again with a different optimizer ss <- getME(musca.immhmm.test,c("theta","fixef")) musca.immhmm.test.2<-update(musca.immhmm.test, start=ss, control=glmerControl(optimizer="bobyqa", optCtrl=list(maxfun=2e5))) #check for singulariy tt <- getME(musca.immhmm.test.2,"theta") ll <- getME(musca.immhmm.test.2,"lower") min(tt[ll==0]) #check gradient calcs derivs1 <- musca.immhmm.test.2@optinfo$derivs sc_grad1 <- with(derivs1,solve(Hessian,gradient)) max(abs(sc_grad1)) dd <- update(musca.immhmm.test.2,devFunOnly=TRUE) pars <- unlist(getME(musca.immhmm.test.2,c("theta","fixef"))) grad2 <- grad(dd,pars) hess2 <- hessian(dd,pars) sc_grad2 <- solve(hess2,grad2) max(pmin(abs(sc_grad2),abs(grad2))) #still not converging...hmmm. #get results anyway...will eventually try running with different optimizers ##NOT RUN## #try with a bunch of optimizers musca.immhmm.test.conv<-allFit(musca.immhmm.test.2) is.OK<-sapply(musca.immhmm.test.conv, is, "merMod") musca.immhmm.test.conv.ok<-musca.immhmm.test.conv[is.OK] lapply(musca.immhmm.test.conv, function(x) x@optinfo$conv$lme4$messages) ##</NOT RUN> fams=c("BGBP", "CEC", "CLIPA", "CLIPB", "CLIPC", "CLIPD", "CTL", "FREP", "GALE", "HPX", "IGSF", "LYS", "MD2L", "NFKB", "NIM", "PGRP", "PPO", "SPRN", "SRCA", "SRCB", "SRCC", "TEP", "TLL", "TPX", "TSF") hmm_conts<-matrix(0, ncol=length(names(fixef(musca.immhmm.test.2))), nrow=length(fams), dimnames=list(fams,names(fixef(musca.immhmm.test.2)))) for (i in 1:length(fams)) { hmm_conts[i,i+27]=1 } summary(glht(musca.immhmm.test.2, linfct=hmm_conts)) #by lineage for a specific gene family for (test in c("TEP", "LYS", "CEC")) { selected_fam=test musca.immhmm.family<-glmer(count ~ family*(hmm==selected_fam)+offset(log(br)) + (1|ogs), family="poisson", data=droplevels(subset(all.pois, subset=="conserved" & type=="dup" & nodeclass != "root" & family != "Diptera" & family != "Glossinidae"))) #make tests fams=c("Dros", "Cul") hmm_conts<-matrix(0, ncol=length(names(fixef(musca.immhmm.family))), nrow=length(fams), dimnames=list(fams,names(fixef(musca.immhmm.family)))) for (i in 1:nrow(hmm_conts)) { hmm_conts[i,i+4]=-1 } print(summary(glht(musca.immhmm.family, linfct=hmm_conts))) } #look at per-ogs rate per.ogs.data<-droplevels(subset(all.pois, subset=="conserved" & type=="total" & nodeclass != "root")) per.ogs.results<-data.frame(ogs=character(length(unique(per.ogs.data$ogs))), rate=numeric(length(unique(per.ogs.data$ogs))), pval=numeric(length(unique(per.ogs.data$ogs))), stringsAsFactors=F) ogs.list<-as.character(unique(per.ogs.data$ogs)) for (i in 1:length(ogs.list)) { ogs<-ogs.list[i] ogs.data<-per.ogs.data[per.ogs.data$ogs == ogs,] per.ogs.results[i,1]=ogs per.ogs.results[i,c(2,3)]=coef(summary(glm(count ~ musca + offset(log(br)), family=poisson, data=ogs.data)))[2,c(1,4)] } per.ogs.results$qval = p.adjust(per.ogs.results$pval, method="fdr") #add annotations per.ogs.results.annot <- merge(per.ogs.results, unique(all.pois[,c("ogs", "hmm", "dmel.imm", "immune.narrow", "immune.broad")]), by="ogs") #fisher tests fisher.test(table(per.ogs.results.annot$qval < 0.05 & per.ogs.results.annot$rate > 0, per.ogs.results.annot$immune.broad)) table(per.ogs.results.annot$qval < 0.05 & per.ogs.results.annot$rate > 0, per.ogs.results.annot$immune.broad) per.ogs.results.annot[per.ogs.results.annot$qval < 0.05 & per.ogs.results.annot$rate > 0 & per.ogs.results.annot$immune.broad==T,]
# library(evd) PLIquantile = function(order,x,y,deltasvector,InputDistributions,type="MOY",samedelta=TRUE,percentage=TRUE,nboot=0,conf=0.95,bootsample=TRUE){ # This function allows the estimation of Density Modification Based Reliability Sensitivity Indices # called PLI (Perturbed-Law based sensitivity Indices) for a quantile # Author: Paul Lemaitre, Bertrand Iooss, Thibault Delage and Roman Sueur # # Refs : P. Lemaitre, E. Sergienko, A. Arnaud, N. Bousquet, F. Gamboa and B. Iooss. # Density modification based reliability sensitivity analysis, # Journal of Statistical Computation and Simulation, 85:1200-1223, 2015. # hal.archives-ouvertes.fr/docs/00/73/79/78/PDF/Article_v68.pdf. # # R. Sueur, B. Iooss and T. Delage. # Sensitivity analysis using perturbed-law based indices for quantiles and application to an industrial case}, # 10th International Conference on Mathematical Methods in Reliability (MMR 2017), Grenoble, France, July 2017. # ################################### ## Description of input parameters ################################### # # order is the order of the quantile to estimate. # x is the matrix of simulation points coordinates (one column per variable). # y is the vector of model outputs. # deltasvector is a vector containing the values of delta for which the indices will be computed # InputDistributions is a list of list. Each list contains, as a list, the name of the distribution to be used and the parameters. # Implemented cases so far: # - for a mean perturbation: Gaussian, Uniform, Triangle, Left Trucated Gaussian, Left Truncated Gumbel # - for a variance perturbation: Gaussian, Uniform # type is a character string in which the user will specify the type of perturbation wanted. # NB: the sense of "deltasvector" varies according to the type of perturbation # type can take the value "MOY",in which case deltasvector is a vector of perturbated means. # type can take the value "VAR",in which case deltasvector is a vector of perturbated variances, therefore needs to be positive integers. # samedelta is a boolean used with the value "MOY" for type. If it is set at TRUE, the mean perturbation will be the same for all the variables. # If not, the mean perturbation will be new_mean = mean+sigma*delta where mean, sigma are parameters defined in InputDistributions and delta is a value of deltasvector. See subsection 4.3.3 of the reference for an exemple of use. # percentage defines the formula used for the PLI. If percentage=FALSE, the initially proposed formula is used (Sueur et al., 2017). # If percentage=TRUE, the PLI is given in percentage of variation of the quantile (even if it is negative). # nboot is the number of bootstrap replicates # conf is the required bootstrap confidence interval # bootsample defines if the sampling uncertainty is taken into account in computing the boostrap confidence intervals of the PLI # # ################################### ## Description of output parameters ################################### # # The output is a matrix where the PLI are stored: # each column corresponds to an input, each line corresponds to a twist of amplitude delta ######################################## ## Creation of local variables ######################################## nmbredevariables=dim(x)[2] # number of variables nmbredepoints=dim(x)[1] # number of points nmbrededeltas=length(deltasvector) # number of perturbations ## some storage vectors and matrices I <- J <- ICIinf <- ICIsup <- JCIinf <- JCIsup <- matrix(0,ncol=nmbredevariables,nrow=nmbrededeltas) colnames(I) <- colnames(J) <- colnames(ICIinf) <- colnames(ICIsup) <- colnames(JCIinf) <- colnames(JCIsup) <- lapply(1:nmbredevariables, function(k) paste("X",k,sep="_", collapse="")) ######################################## ## Definition of useful functions used further on ######################################## ######################################## ## Simpson's method ######################################## simpson_v2 <- function(fun, a, b, n=100) { # numerical integral using Simpson's rule # assume a < b and n is an even positive integer if (a == -Inf & b == Inf) { f <- function(t) (fun((1-t)/t) + fun((t-1)/t))/t^2 s <- simpson_v2(f, 0, 1, n) } else if (a == -Inf & b != Inf) { f <- function(t) fun(b-(1-t)/t)/t^2 s <- simpson_v2(f, 0, 1, n) } else if (a != -Inf & b == Inf) { f <- function(t) fun(a+(1-t)/t)/t^2 s <- simpson_v2(f, 0, 1, n) } else { h <- (b-a)/n x <- seq(a, b, by=h) y <- fun(x) y[is.nan(y)]=0 s <- y[1] + y[n+1] + 2*sum(y[seq(2,n,by=2)]) + 4 *sum(y[seq(3,n-1, by=2)]) s <- s*h/3 } return(s) } transinverse <- function(a,b,c) { # useful to compute bootstrap-based confidence intervals if (a > c) ans <- a / b - 1 else ans <- 1 - b / a return(ans) } ######################################## ## Principal loop of the function ######################################## quantilehat <- quantile(y,order) # quantile estimate ys = sort(y,index.return=T) # ordered output xs = x[ys$ix,] # inputs ordered by increasing output for (i in 1:nmbredevariables){ # loop for each variable ## definition of local variables Loi.Entree=InputDistributions[[i]] lqid=rep(0,length=nmbrededeltas) if (nboot > 0){ lqidb=matrix(0,nrow=nmbrededeltas,ncol=nboot) # pour bootstrap quantilehatb=NULL } if (type=="MOY"){ ############################ ## definition of local variable vdd ############################ if(!samedelta){ # In this case, the mean perturbation will be new_mean = mean+sigma*delta # The mean and the standard deviation sigma of the input distribution must be stored in the third place of the list defining the input distribution. moy=Loi.Entree[[3]][1] sigma=Loi.Entree[[3]][2] vdd=moy+deltasvector*sigma } else { vdd=deltasvector } ########################## ### The next part does, for each kind of input distribution # Solve with respect to lambda the following equation : # (1) Mx'(lambda)/Mx(lambda)-delta=0 {See section 3, proposition 3.2} # One can note that (1) is the derivative with respect to lambda of # (2) log(Mx(lambda))-delta*lambda # Function (2) is concave, therefore its optimisation is theoritically easy. # # => One obtains an unique lambda solution # # Then the density ratio is computed and summed, allowing the estimation of q_i_delta. # lqid is a vector of same length as deltas_vector # sigma2_i_tau_N, the estimator of the variance of the estimator of P_i_delta (see lemma 2.1) is also computed # # Implemented cases: Gaussian, Uniform, Triangle, Left Trucated Gaussian, Left Truncated Gumbel if ( Loi.Entree[[1]] =="norm"||Loi.Entree[[1]] =="lnorm"){ # if the input is a Gaussian,solution of equation (1) is trivial mu=Loi.Entree[[2]][1] sigma=Loi.Entree[[2]][2] phi=function(tau){mu*tau+(sigma^2*tau^2)/2} vlambda=(vdd-mu)/sigma^2 } # end for Gaussian input, mean twisting if ( Loi.Entree[[1]] =="unif"){ # One will not minimise directly log(Mx)-lambda*delta due to numerical problems emerging when considering # exponential of large numbers (if b is large, problems can be expected) # Instead, one note that the optimal lambda for an Uniform(a,b) and a given mean delta is the same that for # an Uniform(0,b-a) and a given mean (delta-a). # Function phit corresponding to the log of the Mgf of an U(0,b-a) is implemented; # the function expm1 is used to avoid numerical troubles when tau is small. # Function gt allowing to minimise phit(tau)-(delta-a)*tau is also implemented. a=Loi.Entree[[2]][1] b=Loi.Entree[[2]][2] mu=(a+b)/2 Mx=function(tau){ if (tau==0){ 1 } else {(exp(tau*b)-exp(tau*a) )/ ( tau * (b-a))} } phi=function(tau){ if(tau==0){0} else { log(Mx(tau))} } phit=function(tau){ if (tau==0){0} else {log(expm1(tau*(b-a)) / (tau*(b-a)))} } gt=function(tau,delta){ phit(tau) -(delta-a)*tau } vlambda=c(); for (l in 1:nmbrededeltas){ tm=nlm(gt,0,vdd[l])$estimate vlambda[l]=tm } } # end for Uniform input, mean twisting if ( Loi.Entree[[1]] =="triangle"){ # One will not minimise directly log(Mx)-lambda*delta due to numerical problems emerging when considering # exponential of large numbers (if b is large, problems can be expected) # Instead, one note that the optimal lambda for an Triangular(a,b,c) and a given mean delta is the same that for # an Uniform(0,b-a,c-a) and a given mean (delta-a). # Function phit corresponding to the log of the Mgf of an Tri(0,b-a,c-a) is implemented; # One can note that phit=log(Mx)+lambda*a # Function gt allowing to minimise phit(tau)-(delta-a)*tau is also implemented.. a=Loi.Entree[[2]][1] b=Loi.Entree[[2]][2] c=Loi.Entree[[2]][3] # reminder: c is between a and b mu=(a+b+c)/3 Mx=function(tau){ if (tau !=0){ dessus=(b-c)*exp(a*tau)-(b-a)*exp(c*tau)+(c-a)*exp(b*tau) dessous=(b-c)*(b-a)*(c-a)*tau^2 return ( 2*dessus/dessous) } else { return (1) } } phi=function(tau){return (log (Mx(tau)))} phit=function(tau){ if(tau!=0){ dessus=(a-b)*expm1((c-a)*tau)+(c-a)*expm1((b-a)*tau) dessous=(b-c)*(b-a)*(c-a)*tau^2 return( log (2*dessus/dessous) ) } else { return (0)} } gt=function(tau,delta){ phit(tau)-(delta-a)*tau } vlambda=c(); for (l in 1:nmbrededeltas){ tm=nlm(gt,0,vdd[l])$estimate vlambda[l]=tm } } # End for Triangle input, mean twisting if ( Loi.Entree[[1]] =="tnorm"){ # The case implemented is the left truncated Gaussian # Details : First, the constants defining the distribution (mu, sigma, min) are extracted. # Then, the function g is defined as log(Mx(tau))-delta*tau. # The function phi has an explicit expression in this case. mu=Loi.Entree[[2]][1] sigma=Loi.Entree[[2]][2] min=Loi.Entree[[2]][3] phi=function(tau){ mpls2=mu+tau*sigma^2 Fa=pnorm(min,mu,sigma) Fia=pnorm(min,mpls2,sigma) lMx=mu*tau+1/2*sigma^2*tau^2 - (1-Fa) + (1-Fia) return(lMx) } g=function(tau,delta){ if (tau == 0 ){ return(0) } else { return(phi(tau) -delta*tau)} } vlambda=c(); for (l in 1:nmbrededeltas){ tm=nlm(g,0,vdd[l])$estimate vlambda[l]=tm } } # End for left truncated Gaussian, mean twisting if ( Loi.Entree[[1]] =="tgumbel"){ # The case implemented is the left truncated Gumbel # Details : First, the constants defining the distribution (mu, beta, min) are extracted. # Then, the function g is defined as log(Mx(tau))-delta*tau. # The function Mx is estimated as described in annex C, the unknonw integrals are estimated with Simpson's method # One should be warned that the MGF is not defined if tau> 1/beta # The function Mx prime is also defined as in annex C. # Then a dichotomy is performed to find the root of equation (1) mu=Loi.Entree[[2]][1] beta=Loi.Entree[[2]][2] min=Loi.Entree[[2]][3] vraie_mean=mu-beta*digamma(1) estimateurdeMYT=function(tau){ if(tau>1/beta){ print("Warning, the MGF of the truncated gumbel distribution is not defined")} if (tau!=0){ fctaint=function(y){evd::dgumbel(y,mu,beta)*exp(tau*y)} partie_tronquee=simpson_v2(fctaint,-Inf,min,2000) MGFgumbel=exp(mu*tau)*gamma(1-beta*tau) res=(MGFgumbel-partie_tronquee) / (1-evd::pgumbel(min,mu,beta)) return(res) } else { return (1)} } estimateurdeMYTprime=function(tau){ fctaint=function(y){y*evd::dgumbel(y,mu,beta)*exp(tau*y)} partie_tronquee=simpson_v2(fctaint,-Inf,min,2000) MGFprimegumbel=exp(mu*tau)*gamma(1-beta*tau)*(mu-beta*digamma(1-beta*tau)) Mxp=(MGFprimegumbel-partie_tronquee)/(1-evd::pgumbel(min,mu,beta)) return(Mxp) } phi=function(tau){ return(log(estimateurdeMYT(tau))) } g=function(tau,delta){ Mx=estimateurdeMYT(tau) Mxp=estimateurdeMYTprime(tau) return(Mxp/Mx-delta) } vlambda=c() vmax_search=1/beta -10^-8 #Maximal theoritical value of lambda, with some safety precision=10^-8 for (l in 1:nmbrededeltas){ d=vdd[l] t=vmax_search a=g(t,d) while(a>0){t=t-5*10^-4 a=g(t,d) } t1=t;t2=t+5*10^-4 #g(t1) is negative; g(t2) positive while(abs(g(t,d))>precision){ t=(t1+t2)/2 if ( g(t,d)<0 ){t1=t} else {t2=t} } vlambda[l]=t } } # End for left trucated Gumbel, mean twisting ############################################################### ############# Computation of q_i_delta for the mean twisting ############################################################### pti=rep(0,nmbrededeltas) for (K in 1:nmbrededeltas){ if(vdd[K]!=mu){ res=NULL pti[K]=phi(vlambda[K]) for (j in 1:nmbredepoints){ res[j]=exp(vlambda[K]*xs[j,i]-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum_res while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqid[K] = ys$x[kid] } else lqid[K] = quantilehat } ############################################################### ########## BOOTSTRAP ############### ############################################################### if (nboot >0){ for (b in 1:nboot){ ib <- sample(1:length(y),replace=TRUE) xb <- x[ib,] yb <- y[ib] quantilehatb <- c(quantilehatb, quantile(yb,order)) # quantile estimate ysb = sort(yb,index.return=T) # ordered output xsb = xb[ysb$ix,] # inputs ordered by increasing output for (K in 1:nmbrededeltas){ if(vdd[K]!=mu){ res=NULL for (j in 1:nmbredepoints){ res[j]=exp(vlambda[K]*xsb[j,i]-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum_res while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqidb[K,b] = ysb$x[kid] } else lqidb[K,b] = quantilehatb[b] } } # end of bootstrap loop } } # endif type="MOY" ###################################################################################### if (type=="VAR"){ ### The next part does, for each kind of input distribution # Solve with respect to lambda the following set of equations : # int (y.f_lambda(y)dy) = int( yf(y)dy) # (3) int (y^2.f_lambda(y)dy)= V_f + int( yf(y)dy) ^2 # One must note that lambda is of size 2. # # Implemented cases : Gaussian, Uniform if ( Loi.Entree[[1]] =="norm"||Loi.Entree[[1]] =="lnorm"){ # if the input is a Gaussian,solution of equation (3) is given by analytical devlopment mu=Loi.Entree[[2]][1] sigma=Loi.Entree[[2]][2] phi1=function(l){ t1=exp(-mu^2/(2*sigma^2)) t2=exp((mu+sigma^2*l[1])^2/(2*sigma^2*(1-2*sigma^2*l[2]))) t3=1/sqrt(1-2*sigma^2*l[2]) return(log(t1*t2*t3)) } lambda1=mu*(1/deltasvector-1/sigma^2) lambda2=-1/2*(1/deltasvector-1/sigma^2) # nota bene : lambda1 and lambda2 are vectors of size nmbrededeltas } # End for Gaussian input, variance twisting if ( Loi.Entree[[1]] =="unif"){ # Details : First, the constants defining the distribution (a, b) are extracted. # Then, the function phi1 is defined, the unknonw integrals are estimated with Simpson's method # The Hessian of the Lagrange function is then defined (See annex B) # Then, for each perturbed variance, the Lagrange function and its gradient are defined and minimised. a=Loi.Entree[[2]][1] b=Loi.Entree[[2]][2] mu=(a+b)/2 lambda1=c() lambda2=c() phi1=function(l){ # l is a vector of size 2, resp lambda1, lambda2 fctaint=function(y){dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) return(log(cste)) } hess=function(l){ # the Hessian of the Lagrange function epl=exp(phi1(l)) fctaint=function(y){y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r1=cste/epl fctaint=function(y){y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r2=cste/epl fctaint=function(y){y*y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r3=cste/epl fctaint=function(y){y*y*y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r4=cste/epl h11=r2-(r1*r1) h21=r3-(r1*r2) h22=r4-(r2*r2) return(matrix(c(h11,h21,h21,h22),ncol=2,nrow=2)) } # The lagrange function and its gradient must be redefined for each delta (i.e. for each fixed variance) for (w in 1:nmbrededeltas){ gr=function(l){ # the gradient of the lagrange function epl=exp(phi1(l)) fctaint=function(y){y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) resultat1=cste/epl-mu fctaint=function(y){y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) resultat2=cste/epl-(deltasvector[w]+mu^2) return(c(resultat1,resultat2)) } lagrangefun=function(l){ res=phi1(l)-l[1]*mu-l[2]*(deltasvector[w]+mu^2) attr(res, "gradient")=gr(l) attr(res, "hessian")=hess(l) return(res) } v=nlm(lagrangefun,c(0,-1))$estimate lambda1[w]=v[1] lambda2[w]=v[2] } } # End for Uniform input, variance twisting ############################################################### ############# Computation of q_i_delta for the variance twisting ############################################################### pti=rep(0,nmbrededeltas) for (K in 1:nmbrededeltas){ if(deltasvector[K]!=0){ res=0 pti[K]=phi1(c(lambda1[K],lambda2[K])) for (j in 1:nmbredepoints){ res[j]=exp(lambda1[K]*xs[j,i]+lambda2[K]*xs[j,i]^2-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum(res) while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqid[K] = ys$x[kid] } else lqid[K] = quantilehat } ############################################################### ########## BOOTSTRAP ############### ############################################################### if (nboot >0){ for (b in 1:nboot){ ib <- sample(1:length(y),replace=TRUE) xb <- x[ib,] yb <- y[ib] quantilehatb <- c(quantilehatb, quantile(yb,order)) # quantile estimate ysb = sort(yb,index.return=T) # ordered output xsb = xb[ysb$ix,] # inputs ordered by increasing output for (K in 1:nmbrededeltas){ if(deltasvector[K]!=0){ res=0 for (j in 1:nmbredepoints){ res[j]=exp(lambda1[K]*xsb[j,i]+lambda2[K]*xsb[j,i]^2-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum(res) while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqidb[K,b] = ysb$x[kid] } else lqidb[K,b] = quantilehatb[b] } } # end of bootstrap loop } } # endif TYPE="VAR" ######################################## ## Plugging estimator of the S_i_delta indices ######################################## for (j in 1:length(lqid)){ J[j,i]=lqid[j] if (percentage==FALSE) I[j,i]=transinverse(lqid[j],quantilehat,quantilehat) else I[j,i]=lqid[j]/quantilehat-1 if (nboot > 0){ # ICI = PLI bootstrap including or excluding sampling uncertainty # JCI = quantile bootstrap qinf <- quantile(lqidb[j,],(1-conf)/2) qsup <- quantile(lqidb[j,],(1+conf)/2) JCIinf[j,i]=qinf JCIsup[j,i]=qsup qb <- mean(quantilehatb) if (percentage==FALSE){ if (bootsample){ ICIinf[j,i]=transinverse(qinf,qb,qb) ICIsup[j,i]=transinverse(qsup,qb,quantilehat) } else{ ICIinf[j,i]=quantile(transinverse(lqidb[j,],quantilehatb,quantilehatb),(1-conf)/2) ICIsup[j,i]=quantile(transinverse(lqidb[j,],quantilehatb,quantilehatb),(1+conf)/2) } } else { if (bootsample){ ICIinf[j,i]=qinf/qb-1 ICIsup[j,i]=qsup/qb-1 } else{ ICIinf[j,i]=quantile((lqidb[j,]/quantilehatb-1),(1-conf)/2) ICIsup[j,i]=quantile((lqidb[j,]/quantilehatb-1),(1+conf)/2) } } } } } # End for each input res <- list(PLI = I, PLICIinf = ICIinf, PLICIsup = ICIsup, quantile = J, quantileCIinf = JCIinf, quantileCIsup = JCIsup) return(res) }
/R/PLIquantile.r
no_license
cran/sensitivity
R
false
false
23,729
r
# library(evd) PLIquantile = function(order,x,y,deltasvector,InputDistributions,type="MOY",samedelta=TRUE,percentage=TRUE,nboot=0,conf=0.95,bootsample=TRUE){ # This function allows the estimation of Density Modification Based Reliability Sensitivity Indices # called PLI (Perturbed-Law based sensitivity Indices) for a quantile # Author: Paul Lemaitre, Bertrand Iooss, Thibault Delage and Roman Sueur # # Refs : P. Lemaitre, E. Sergienko, A. Arnaud, N. Bousquet, F. Gamboa and B. Iooss. # Density modification based reliability sensitivity analysis, # Journal of Statistical Computation and Simulation, 85:1200-1223, 2015. # hal.archives-ouvertes.fr/docs/00/73/79/78/PDF/Article_v68.pdf. # # R. Sueur, B. Iooss and T. Delage. # Sensitivity analysis using perturbed-law based indices for quantiles and application to an industrial case}, # 10th International Conference on Mathematical Methods in Reliability (MMR 2017), Grenoble, France, July 2017. # ################################### ## Description of input parameters ################################### # # order is the order of the quantile to estimate. # x is the matrix of simulation points coordinates (one column per variable). # y is the vector of model outputs. # deltasvector is a vector containing the values of delta for which the indices will be computed # InputDistributions is a list of list. Each list contains, as a list, the name of the distribution to be used and the parameters. # Implemented cases so far: # - for a mean perturbation: Gaussian, Uniform, Triangle, Left Trucated Gaussian, Left Truncated Gumbel # - for a variance perturbation: Gaussian, Uniform # type is a character string in which the user will specify the type of perturbation wanted. # NB: the sense of "deltasvector" varies according to the type of perturbation # type can take the value "MOY",in which case deltasvector is a vector of perturbated means. # type can take the value "VAR",in which case deltasvector is a vector of perturbated variances, therefore needs to be positive integers. # samedelta is a boolean used with the value "MOY" for type. If it is set at TRUE, the mean perturbation will be the same for all the variables. # If not, the mean perturbation will be new_mean = mean+sigma*delta where mean, sigma are parameters defined in InputDistributions and delta is a value of deltasvector. See subsection 4.3.3 of the reference for an exemple of use. # percentage defines the formula used for the PLI. If percentage=FALSE, the initially proposed formula is used (Sueur et al., 2017). # If percentage=TRUE, the PLI is given in percentage of variation of the quantile (even if it is negative). # nboot is the number of bootstrap replicates # conf is the required bootstrap confidence interval # bootsample defines if the sampling uncertainty is taken into account in computing the boostrap confidence intervals of the PLI # # ################################### ## Description of output parameters ################################### # # The output is a matrix where the PLI are stored: # each column corresponds to an input, each line corresponds to a twist of amplitude delta ######################################## ## Creation of local variables ######################################## nmbredevariables=dim(x)[2] # number of variables nmbredepoints=dim(x)[1] # number of points nmbrededeltas=length(deltasvector) # number of perturbations ## some storage vectors and matrices I <- J <- ICIinf <- ICIsup <- JCIinf <- JCIsup <- matrix(0,ncol=nmbredevariables,nrow=nmbrededeltas) colnames(I) <- colnames(J) <- colnames(ICIinf) <- colnames(ICIsup) <- colnames(JCIinf) <- colnames(JCIsup) <- lapply(1:nmbredevariables, function(k) paste("X",k,sep="_", collapse="")) ######################################## ## Definition of useful functions used further on ######################################## ######################################## ## Simpson's method ######################################## simpson_v2 <- function(fun, a, b, n=100) { # numerical integral using Simpson's rule # assume a < b and n is an even positive integer if (a == -Inf & b == Inf) { f <- function(t) (fun((1-t)/t) + fun((t-1)/t))/t^2 s <- simpson_v2(f, 0, 1, n) } else if (a == -Inf & b != Inf) { f <- function(t) fun(b-(1-t)/t)/t^2 s <- simpson_v2(f, 0, 1, n) } else if (a != -Inf & b == Inf) { f <- function(t) fun(a+(1-t)/t)/t^2 s <- simpson_v2(f, 0, 1, n) } else { h <- (b-a)/n x <- seq(a, b, by=h) y <- fun(x) y[is.nan(y)]=0 s <- y[1] + y[n+1] + 2*sum(y[seq(2,n,by=2)]) + 4 *sum(y[seq(3,n-1, by=2)]) s <- s*h/3 } return(s) } transinverse <- function(a,b,c) { # useful to compute bootstrap-based confidence intervals if (a > c) ans <- a / b - 1 else ans <- 1 - b / a return(ans) } ######################################## ## Principal loop of the function ######################################## quantilehat <- quantile(y,order) # quantile estimate ys = sort(y,index.return=T) # ordered output xs = x[ys$ix,] # inputs ordered by increasing output for (i in 1:nmbredevariables){ # loop for each variable ## definition of local variables Loi.Entree=InputDistributions[[i]] lqid=rep(0,length=nmbrededeltas) if (nboot > 0){ lqidb=matrix(0,nrow=nmbrededeltas,ncol=nboot) # pour bootstrap quantilehatb=NULL } if (type=="MOY"){ ############################ ## definition of local variable vdd ############################ if(!samedelta){ # In this case, the mean perturbation will be new_mean = mean+sigma*delta # The mean and the standard deviation sigma of the input distribution must be stored in the third place of the list defining the input distribution. moy=Loi.Entree[[3]][1] sigma=Loi.Entree[[3]][2] vdd=moy+deltasvector*sigma } else { vdd=deltasvector } ########################## ### The next part does, for each kind of input distribution # Solve with respect to lambda the following equation : # (1) Mx'(lambda)/Mx(lambda)-delta=0 {See section 3, proposition 3.2} # One can note that (1) is the derivative with respect to lambda of # (2) log(Mx(lambda))-delta*lambda # Function (2) is concave, therefore its optimisation is theoritically easy. # # => One obtains an unique lambda solution # # Then the density ratio is computed and summed, allowing the estimation of q_i_delta. # lqid is a vector of same length as deltas_vector # sigma2_i_tau_N, the estimator of the variance of the estimator of P_i_delta (see lemma 2.1) is also computed # # Implemented cases: Gaussian, Uniform, Triangle, Left Trucated Gaussian, Left Truncated Gumbel if ( Loi.Entree[[1]] =="norm"||Loi.Entree[[1]] =="lnorm"){ # if the input is a Gaussian,solution of equation (1) is trivial mu=Loi.Entree[[2]][1] sigma=Loi.Entree[[2]][2] phi=function(tau){mu*tau+(sigma^2*tau^2)/2} vlambda=(vdd-mu)/sigma^2 } # end for Gaussian input, mean twisting if ( Loi.Entree[[1]] =="unif"){ # One will not minimise directly log(Mx)-lambda*delta due to numerical problems emerging when considering # exponential of large numbers (if b is large, problems can be expected) # Instead, one note that the optimal lambda for an Uniform(a,b) and a given mean delta is the same that for # an Uniform(0,b-a) and a given mean (delta-a). # Function phit corresponding to the log of the Mgf of an U(0,b-a) is implemented; # the function expm1 is used to avoid numerical troubles when tau is small. # Function gt allowing to minimise phit(tau)-(delta-a)*tau is also implemented. a=Loi.Entree[[2]][1] b=Loi.Entree[[2]][2] mu=(a+b)/2 Mx=function(tau){ if (tau==0){ 1 } else {(exp(tau*b)-exp(tau*a) )/ ( tau * (b-a))} } phi=function(tau){ if(tau==0){0} else { log(Mx(tau))} } phit=function(tau){ if (tau==0){0} else {log(expm1(tau*(b-a)) / (tau*(b-a)))} } gt=function(tau,delta){ phit(tau) -(delta-a)*tau } vlambda=c(); for (l in 1:nmbrededeltas){ tm=nlm(gt,0,vdd[l])$estimate vlambda[l]=tm } } # end for Uniform input, mean twisting if ( Loi.Entree[[1]] =="triangle"){ # One will not minimise directly log(Mx)-lambda*delta due to numerical problems emerging when considering # exponential of large numbers (if b is large, problems can be expected) # Instead, one note that the optimal lambda for an Triangular(a,b,c) and a given mean delta is the same that for # an Uniform(0,b-a,c-a) and a given mean (delta-a). # Function phit corresponding to the log of the Mgf of an Tri(0,b-a,c-a) is implemented; # One can note that phit=log(Mx)+lambda*a # Function gt allowing to minimise phit(tau)-(delta-a)*tau is also implemented.. a=Loi.Entree[[2]][1] b=Loi.Entree[[2]][2] c=Loi.Entree[[2]][3] # reminder: c is between a and b mu=(a+b+c)/3 Mx=function(tau){ if (tau !=0){ dessus=(b-c)*exp(a*tau)-(b-a)*exp(c*tau)+(c-a)*exp(b*tau) dessous=(b-c)*(b-a)*(c-a)*tau^2 return ( 2*dessus/dessous) } else { return (1) } } phi=function(tau){return (log (Mx(tau)))} phit=function(tau){ if(tau!=0){ dessus=(a-b)*expm1((c-a)*tau)+(c-a)*expm1((b-a)*tau) dessous=(b-c)*(b-a)*(c-a)*tau^2 return( log (2*dessus/dessous) ) } else { return (0)} } gt=function(tau,delta){ phit(tau)-(delta-a)*tau } vlambda=c(); for (l in 1:nmbrededeltas){ tm=nlm(gt,0,vdd[l])$estimate vlambda[l]=tm } } # End for Triangle input, mean twisting if ( Loi.Entree[[1]] =="tnorm"){ # The case implemented is the left truncated Gaussian # Details : First, the constants defining the distribution (mu, sigma, min) are extracted. # Then, the function g is defined as log(Mx(tau))-delta*tau. # The function phi has an explicit expression in this case. mu=Loi.Entree[[2]][1] sigma=Loi.Entree[[2]][2] min=Loi.Entree[[2]][3] phi=function(tau){ mpls2=mu+tau*sigma^2 Fa=pnorm(min,mu,sigma) Fia=pnorm(min,mpls2,sigma) lMx=mu*tau+1/2*sigma^2*tau^2 - (1-Fa) + (1-Fia) return(lMx) } g=function(tau,delta){ if (tau == 0 ){ return(0) } else { return(phi(tau) -delta*tau)} } vlambda=c(); for (l in 1:nmbrededeltas){ tm=nlm(g,0,vdd[l])$estimate vlambda[l]=tm } } # End for left truncated Gaussian, mean twisting if ( Loi.Entree[[1]] =="tgumbel"){ # The case implemented is the left truncated Gumbel # Details : First, the constants defining the distribution (mu, beta, min) are extracted. # Then, the function g is defined as log(Mx(tau))-delta*tau. # The function Mx is estimated as described in annex C, the unknonw integrals are estimated with Simpson's method # One should be warned that the MGF is not defined if tau> 1/beta # The function Mx prime is also defined as in annex C. # Then a dichotomy is performed to find the root of equation (1) mu=Loi.Entree[[2]][1] beta=Loi.Entree[[2]][2] min=Loi.Entree[[2]][3] vraie_mean=mu-beta*digamma(1) estimateurdeMYT=function(tau){ if(tau>1/beta){ print("Warning, the MGF of the truncated gumbel distribution is not defined")} if (tau!=0){ fctaint=function(y){evd::dgumbel(y,mu,beta)*exp(tau*y)} partie_tronquee=simpson_v2(fctaint,-Inf,min,2000) MGFgumbel=exp(mu*tau)*gamma(1-beta*tau) res=(MGFgumbel-partie_tronquee) / (1-evd::pgumbel(min,mu,beta)) return(res) } else { return (1)} } estimateurdeMYTprime=function(tau){ fctaint=function(y){y*evd::dgumbel(y,mu,beta)*exp(tau*y)} partie_tronquee=simpson_v2(fctaint,-Inf,min,2000) MGFprimegumbel=exp(mu*tau)*gamma(1-beta*tau)*(mu-beta*digamma(1-beta*tau)) Mxp=(MGFprimegumbel-partie_tronquee)/(1-evd::pgumbel(min,mu,beta)) return(Mxp) } phi=function(tau){ return(log(estimateurdeMYT(tau))) } g=function(tau,delta){ Mx=estimateurdeMYT(tau) Mxp=estimateurdeMYTprime(tau) return(Mxp/Mx-delta) } vlambda=c() vmax_search=1/beta -10^-8 #Maximal theoritical value of lambda, with some safety precision=10^-8 for (l in 1:nmbrededeltas){ d=vdd[l] t=vmax_search a=g(t,d) while(a>0){t=t-5*10^-4 a=g(t,d) } t1=t;t2=t+5*10^-4 #g(t1) is negative; g(t2) positive while(abs(g(t,d))>precision){ t=(t1+t2)/2 if ( g(t,d)<0 ){t1=t} else {t2=t} } vlambda[l]=t } } # End for left trucated Gumbel, mean twisting ############################################################### ############# Computation of q_i_delta for the mean twisting ############################################################### pti=rep(0,nmbrededeltas) for (K in 1:nmbrededeltas){ if(vdd[K]!=mu){ res=NULL pti[K]=phi(vlambda[K]) for (j in 1:nmbredepoints){ res[j]=exp(vlambda[K]*xs[j,i]-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum_res while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqid[K] = ys$x[kid] } else lqid[K] = quantilehat } ############################################################### ########## BOOTSTRAP ############### ############################################################### if (nboot >0){ for (b in 1:nboot){ ib <- sample(1:length(y),replace=TRUE) xb <- x[ib,] yb <- y[ib] quantilehatb <- c(quantilehatb, quantile(yb,order)) # quantile estimate ysb = sort(yb,index.return=T) # ordered output xsb = xb[ysb$ix,] # inputs ordered by increasing output for (K in 1:nmbrededeltas){ if(vdd[K]!=mu){ res=NULL for (j in 1:nmbredepoints){ res[j]=exp(vlambda[K]*xsb[j,i]-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum_res while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqidb[K,b] = ysb$x[kid] } else lqidb[K,b] = quantilehatb[b] } } # end of bootstrap loop } } # endif type="MOY" ###################################################################################### if (type=="VAR"){ ### The next part does, for each kind of input distribution # Solve with respect to lambda the following set of equations : # int (y.f_lambda(y)dy) = int( yf(y)dy) # (3) int (y^2.f_lambda(y)dy)= V_f + int( yf(y)dy) ^2 # One must note that lambda is of size 2. # # Implemented cases : Gaussian, Uniform if ( Loi.Entree[[1]] =="norm"||Loi.Entree[[1]] =="lnorm"){ # if the input is a Gaussian,solution of equation (3) is given by analytical devlopment mu=Loi.Entree[[2]][1] sigma=Loi.Entree[[2]][2] phi1=function(l){ t1=exp(-mu^2/(2*sigma^2)) t2=exp((mu+sigma^2*l[1])^2/(2*sigma^2*(1-2*sigma^2*l[2]))) t3=1/sqrt(1-2*sigma^2*l[2]) return(log(t1*t2*t3)) } lambda1=mu*(1/deltasvector-1/sigma^2) lambda2=-1/2*(1/deltasvector-1/sigma^2) # nota bene : lambda1 and lambda2 are vectors of size nmbrededeltas } # End for Gaussian input, variance twisting if ( Loi.Entree[[1]] =="unif"){ # Details : First, the constants defining the distribution (a, b) are extracted. # Then, the function phi1 is defined, the unknonw integrals are estimated with Simpson's method # The Hessian of the Lagrange function is then defined (See annex B) # Then, for each perturbed variance, the Lagrange function and its gradient are defined and minimised. a=Loi.Entree[[2]][1] b=Loi.Entree[[2]][2] mu=(a+b)/2 lambda1=c() lambda2=c() phi1=function(l){ # l is a vector of size 2, resp lambda1, lambda2 fctaint=function(y){dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) return(log(cste)) } hess=function(l){ # the Hessian of the Lagrange function epl=exp(phi1(l)) fctaint=function(y){y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r1=cste/epl fctaint=function(y){y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r2=cste/epl fctaint=function(y){y*y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r3=cste/epl fctaint=function(y){y*y*y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) r4=cste/epl h11=r2-(r1*r1) h21=r3-(r1*r2) h22=r4-(r2*r2) return(matrix(c(h11,h21,h21,h22),ncol=2,nrow=2)) } # The lagrange function and its gradient must be redefined for each delta (i.e. for each fixed variance) for (w in 1:nmbrededeltas){ gr=function(l){ # the gradient of the lagrange function epl=exp(phi1(l)) fctaint=function(y){y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) resultat1=cste/epl-mu fctaint=function(y){y*y*dunif(y,a,b)*exp(l[1]*y+l[2]*y*y)} cste=simpson_v2(fctaint,a,b,2000) resultat2=cste/epl-(deltasvector[w]+mu^2) return(c(resultat1,resultat2)) } lagrangefun=function(l){ res=phi1(l)-l[1]*mu-l[2]*(deltasvector[w]+mu^2) attr(res, "gradient")=gr(l) attr(res, "hessian")=hess(l) return(res) } v=nlm(lagrangefun,c(0,-1))$estimate lambda1[w]=v[1] lambda2[w]=v[2] } } # End for Uniform input, variance twisting ############################################################### ############# Computation of q_i_delta for the variance twisting ############################################################### pti=rep(0,nmbrededeltas) for (K in 1:nmbrededeltas){ if(deltasvector[K]!=0){ res=0 pti[K]=phi1(c(lambda1[K],lambda2[K])) for (j in 1:nmbredepoints){ res[j]=exp(lambda1[K]*xs[j,i]+lambda2[K]*xs[j,i]^2-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum(res) while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqid[K] = ys$x[kid] } else lqid[K] = quantilehat } ############################################################### ########## BOOTSTRAP ############### ############################################################### if (nboot >0){ for (b in 1:nboot){ ib <- sample(1:length(y),replace=TRUE) xb <- x[ib,] yb <- y[ib] quantilehatb <- c(quantilehatb, quantile(yb,order)) # quantile estimate ysb = sort(yb,index.return=T) # ordered output xsb = xb[ysb$ix,] # inputs ordered by increasing output for (K in 1:nmbrededeltas){ if(deltasvector[K]!=0){ res=0 for (j in 1:nmbredepoints){ res[j]=exp(lambda1[K]*xsb[j,i]+lambda2[K]*xsb[j,i]^2-pti[K]) } sum_res = sum(res) kid = 1 res1 = res[1] res2 = res1/sum(res) while (res2 < order){ kid = kid + 1 res1 = res1 + res[kid] res2 = res1/sum_res } lqidb[K,b] = ysb$x[kid] } else lqidb[K,b] = quantilehatb[b] } } # end of bootstrap loop } } # endif TYPE="VAR" ######################################## ## Plugging estimator of the S_i_delta indices ######################################## for (j in 1:length(lqid)){ J[j,i]=lqid[j] if (percentage==FALSE) I[j,i]=transinverse(lqid[j],quantilehat,quantilehat) else I[j,i]=lqid[j]/quantilehat-1 if (nboot > 0){ # ICI = PLI bootstrap including or excluding sampling uncertainty # JCI = quantile bootstrap qinf <- quantile(lqidb[j,],(1-conf)/2) qsup <- quantile(lqidb[j,],(1+conf)/2) JCIinf[j,i]=qinf JCIsup[j,i]=qsup qb <- mean(quantilehatb) if (percentage==FALSE){ if (bootsample){ ICIinf[j,i]=transinverse(qinf,qb,qb) ICIsup[j,i]=transinverse(qsup,qb,quantilehat) } else{ ICIinf[j,i]=quantile(transinverse(lqidb[j,],quantilehatb,quantilehatb),(1-conf)/2) ICIsup[j,i]=quantile(transinverse(lqidb[j,],quantilehatb,quantilehatb),(1+conf)/2) } } else { if (bootsample){ ICIinf[j,i]=qinf/qb-1 ICIsup[j,i]=qsup/qb-1 } else{ ICIinf[j,i]=quantile((lqidb[j,]/quantilehatb-1),(1-conf)/2) ICIsup[j,i]=quantile((lqidb[j,]/quantilehatb-1),(1+conf)/2) } } } } } # End for each input res <- list(PLI = I, PLICIinf = ICIinf, PLICIsup = ICIsup, quantile = J, quantileCIinf = JCIinf, quantileCIsup = JCIsup) return(res) }
get_staff_user_id() => retorna id is_staff_member() => if yes return true
/funcoes_publicas.rd
no_license
EdsonACortese/Perfex-Hook-List
R
false
false
76
rd
get_staff_user_id() => retorna id is_staff_member() => if yes return true
library(adiv) ### Name: speciesdiv ### Title: Indices of Species Diversity ### Aliases: speciesdiv ### Keywords: models ### ** Examples data(batcomm) ab <- batcomm$ab speciesdiv(ab)
/data/genthat_extracted_code/adiv/examples/speciesdiv.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
189
r
library(adiv) ### Name: speciesdiv ### Title: Indices of Species Diversity ### Aliases: speciesdiv ### Keywords: models ### ** Examples data(batcomm) ab <- batcomm$ab speciesdiv(ab)
#' @name update_det #' #' @title Update by determined specimens #' #' @description #' Reference specimens can be integrated in slot **layers** within a #' [vegtable-class] object. #' Updated entries in the specimens can be updated in slot **samples** by using #' this function. #' Alternatively expert opinions can be inserted and applied in case of #' disagreement with the original records. #' #' @param x A [vegtable-class] object to be updated. #' @param specimens A character vector indicating the names of tables included #' in slot **layers** with updates to be applied. #' Note that they will be applied in the same order of the vector in the #' case of multiple updates. #' @param ... Further arguments (not yet in use). #' #' @rdname update_det #' #' @exportMethod update_det #' setGeneric( "update_det", function(x, specimens, ...) { standardGeneric("update_det") } ) #' @rdname update_det #' #' @aliases update_det,vegtable-method #' setMethod( "update_det", signature(x = "vegtable", specimens = "character"), function(x, specimens, ...) { if (any(!specimens %in% names(x@layers))) { stop(paste( "Some values in 'specimens' are not included", "as layer in 'x'." )) } for (i in specimens) { if (!"TaxonUsageID" %in% colnames(x@layers[[i]])) { stop(paste0( "At \"", i, "\", column 'TaxonUsageID' is ", "mandatory in list of specimens." )) } specimens_tab <- x@layers[[i]][x@layers[[i]][, i] %in% x@samples[, i], ] if (any(!specimens_tab$TaxonUsageID %in% x@species@taxonNames$TaxonUsageID)) { stop(paste0( "At \"", i, "\", some taxon usage names ", "are not included in slot 'species'." )) } x@samples$TaxonUsageID <- replace_idx( x@samples$TaxonUsageID, x@samples[, i], specimens_tab[, i], specimens_tab$TaxonUsageID ) } # In the case that taxa2samples was applied before if ("TaxonConceptID" %in% colnames(x@samples)) { warning("You may like to repeat 'taxa2samples()' on 'x'.") } return(x) } )
/R/update_det.R
no_license
kamapu/vegtable
R
false
false
2,157
r
#' @name update_det #' #' @title Update by determined specimens #' #' @description #' Reference specimens can be integrated in slot **layers** within a #' [vegtable-class] object. #' Updated entries in the specimens can be updated in slot **samples** by using #' this function. #' Alternatively expert opinions can be inserted and applied in case of #' disagreement with the original records. #' #' @param x A [vegtable-class] object to be updated. #' @param specimens A character vector indicating the names of tables included #' in slot **layers** with updates to be applied. #' Note that they will be applied in the same order of the vector in the #' case of multiple updates. #' @param ... Further arguments (not yet in use). #' #' @rdname update_det #' #' @exportMethod update_det #' setGeneric( "update_det", function(x, specimens, ...) { standardGeneric("update_det") } ) #' @rdname update_det #' #' @aliases update_det,vegtable-method #' setMethod( "update_det", signature(x = "vegtable", specimens = "character"), function(x, specimens, ...) { if (any(!specimens %in% names(x@layers))) { stop(paste( "Some values in 'specimens' are not included", "as layer in 'x'." )) } for (i in specimens) { if (!"TaxonUsageID" %in% colnames(x@layers[[i]])) { stop(paste0( "At \"", i, "\", column 'TaxonUsageID' is ", "mandatory in list of specimens." )) } specimens_tab <- x@layers[[i]][x@layers[[i]][, i] %in% x@samples[, i], ] if (any(!specimens_tab$TaxonUsageID %in% x@species@taxonNames$TaxonUsageID)) { stop(paste0( "At \"", i, "\", some taxon usage names ", "are not included in slot 'species'." )) } x@samples$TaxonUsageID <- replace_idx( x@samples$TaxonUsageID, x@samples[, i], specimens_tab[, i], specimens_tab$TaxonUsageID ) } # In the case that taxa2samples was applied before if ("TaxonConceptID" %in% colnames(x@samples)) { warning("You may like to repeat 'taxa2samples()' on 'x'.") } return(x) } )
library(h2o) ### Name: h2o.deeplearning ### Title: Build a Deep Neural Network model using CPUs ### Aliases: h2o.deeplearning ### ** Examples ## No test: library(h2o) h2o.init() iris_hf <- as.h2o(iris) iris_dl <- h2o.deeplearning(x = 1:4, y = 5, training_frame = iris_hf, seed=123456) # now make a prediction predictions <- h2o.predict(iris_dl, iris_hf) ## End(No test)
/data/genthat_extracted_code/h2o/examples/h2o.deeplearning.Rd.R
no_license
surayaaramli/typeRrh
R
false
false
379
r
library(h2o) ### Name: h2o.deeplearning ### Title: Build a Deep Neural Network model using CPUs ### Aliases: h2o.deeplearning ### ** Examples ## No test: library(h2o) h2o.init() iris_hf <- as.h2o(iris) iris_dl <- h2o.deeplearning(x = 1:4, y = 5, training_frame = iris_hf, seed=123456) # now make a prediction predictions <- h2o.predict(iris_dl, iris_hf) ## End(No test)
# Vulnerability modeling - parallel # Imports ---- source("vulnerability_modeling_tools.R") source("vulnerability_plotting_tools.R") # Options ---- Sys.setenv(LOCAL_CPPFLAGS = '-march=corei7 -mtune=corei7') options(mc.cores = parallel::detectCores()) rstan_options(auto_write = TRUE) # Main ---- args = commandArgs(trailingOnly=TRUE) # test if there is at least one argument: if not, return an error if (length(args)==0) { args = c("H37Rv", "test", "example_H37Rv_data.txt") } desired_strain = args[1] label = args[2] DATA_PATH = args[3] desired_gene_path = "" DEBUG = TRUE if(length(args) > 3){ DEBUG = TRUE desired_gene_path = args[4] } stancode.filepath = "single_guide_cov_betalogistic.stan" message(sprintf("Reading %s data...", desired_strain)) XFULL = read.table(DATA_PATH, sep=",", stringsAsFactors = FALSE, header=T) ii_bad = is.na(XFULL$ESS) XFULL$ESS[ii_bad] = "N/A" data = XFULL unique_genes = unique(data$ORF) dir.create(file.path("data", desired_strain, label), showWarnings = FALSE) gene = unique_genes[1] message("Creating model...") vb_model = stan_model(stancode.filepath, save_dso = TRUE) message("Running Stan on all genes...") mclapply(unique_genes, run_model, mc.cores=40, data=data, strain=desired_strain, folder=label)
/gene_vul_analysis_parallel.R
no_license
bigfacebig/vulnerability_2021
R
false
false
1,348
r
# Vulnerability modeling - parallel # Imports ---- source("vulnerability_modeling_tools.R") source("vulnerability_plotting_tools.R") # Options ---- Sys.setenv(LOCAL_CPPFLAGS = '-march=corei7 -mtune=corei7') options(mc.cores = parallel::detectCores()) rstan_options(auto_write = TRUE) # Main ---- args = commandArgs(trailingOnly=TRUE) # test if there is at least one argument: if not, return an error if (length(args)==0) { args = c("H37Rv", "test", "example_H37Rv_data.txt") } desired_strain = args[1] label = args[2] DATA_PATH = args[3] desired_gene_path = "" DEBUG = TRUE if(length(args) > 3){ DEBUG = TRUE desired_gene_path = args[4] } stancode.filepath = "single_guide_cov_betalogistic.stan" message(sprintf("Reading %s data...", desired_strain)) XFULL = read.table(DATA_PATH, sep=",", stringsAsFactors = FALSE, header=T) ii_bad = is.na(XFULL$ESS) XFULL$ESS[ii_bad] = "N/A" data = XFULL unique_genes = unique(data$ORF) dir.create(file.path("data", desired_strain, label), showWarnings = FALSE) gene = unique_genes[1] message("Creating model...") vb_model = stan_model(stancode.filepath, save_dso = TRUE) message("Running Stan on all genes...") mclapply(unique_genes, run_model, mc.cores=40, data=data, strain=desired_strain, folder=label)
## ----setup, include=FALSE--------------------------------------------- library(canprot) oldopt <- options(width = 72) ## ----HTML, include=FALSE---------------------------------------------- ZC <- "<i>Z</i><sub>C</sub>" nH2O <- "<i>n</i><sub>H<sub>2</sub>O</sub>" H2O <- "H<sub>2</sub>O" O2 <- "O<sub>2</sub>" ## ----AG--------------------------------------------------------------- AG <- data.frame(Ala = 1, Gly = 1) ## ----AG_metrics------------------------------------------------------- ZCAA(AG) H2OAA(AG) ## ----AG_reaction, message = FALSE------------------------------------- CHNOSZ::basis("QEC") CHNOSZ::subcrt("alanylglycine", 1)$reaction ## ----LYSC_CHICK------------------------------------------------------- AA <- CHNOSZ::pinfo(CHNOSZ::pinfo("LYSC_CHICK")) CHNOSZ::protein.length(AA) AA ## ----LYSC_metrics----------------------------------------------------- ZCAA(AA) H2OAA(AA) ## ----LYSC_reaction, message = FALSE----------------------------------- CHNOSZ::subcrt("LYSC_CHICK", 1)$reaction ## ----protcomp--------------------------------------------------------- (pc <- protcomp("P24298")) ZCAA(pc$aa) ## ----protcomp_archaea------------------------------------------------- aa_file <- system.file("extdata/aa/archaea/JSP+19_aa.csv.xz", package = "canprot") pc <- protcomp("D4GP79", aa_file = aa_file) ZCAA(pc$aa) ## ----GRAVY_pI--------------------------------------------------------- proteins <- c("LYSC_CHICK", "RNAS1_BOVIN", "AMYA_PYRFU") AA <- CHNOSZ::pinfo(CHNOSZ::pinfo(proteins)) pI(AA) GRAVY(AA) ## ----pdat_3D_datasets------------------------------------------------- pdat_3D() ## ----pdat_3D---------------------------------------------------------- pdat <- pdat_3D("DKM+20") str(pdat) ## ----get_comptab------------------------------------------------------ (get_comptab(pdat)) ## ----get_comptabs, message = FALSE, results = "hide"------------------ datasets <- pdat_3D() pdats <- lapply(datasets, pdat_3D) comptabs <- lapply(pdats, get_comptab) ## ----diffplot, fig.width=5, fig.height=5, fig.align = "center"-------- diffplot(comptabs) title("3D cell culture vs monolayers") ## ----vignettes, echo = FALSE------------------------------------------ functions <- grep("pdat_", ls("package:canprot"), value = TRUE) vignettes <- gsub("pdat_", "", functions) vignettes ## ----reset, include=FALSE----------------------------------------------------- options(oldopt)
/inst/doc/canprot.R
no_license
cran/canprot
R
false
false
2,413
r
## ----setup, include=FALSE--------------------------------------------- library(canprot) oldopt <- options(width = 72) ## ----HTML, include=FALSE---------------------------------------------- ZC <- "<i>Z</i><sub>C</sub>" nH2O <- "<i>n</i><sub>H<sub>2</sub>O</sub>" H2O <- "H<sub>2</sub>O" O2 <- "O<sub>2</sub>" ## ----AG--------------------------------------------------------------- AG <- data.frame(Ala = 1, Gly = 1) ## ----AG_metrics------------------------------------------------------- ZCAA(AG) H2OAA(AG) ## ----AG_reaction, message = FALSE------------------------------------- CHNOSZ::basis("QEC") CHNOSZ::subcrt("alanylglycine", 1)$reaction ## ----LYSC_CHICK------------------------------------------------------- AA <- CHNOSZ::pinfo(CHNOSZ::pinfo("LYSC_CHICK")) CHNOSZ::protein.length(AA) AA ## ----LYSC_metrics----------------------------------------------------- ZCAA(AA) H2OAA(AA) ## ----LYSC_reaction, message = FALSE----------------------------------- CHNOSZ::subcrt("LYSC_CHICK", 1)$reaction ## ----protcomp--------------------------------------------------------- (pc <- protcomp("P24298")) ZCAA(pc$aa) ## ----protcomp_archaea------------------------------------------------- aa_file <- system.file("extdata/aa/archaea/JSP+19_aa.csv.xz", package = "canprot") pc <- protcomp("D4GP79", aa_file = aa_file) ZCAA(pc$aa) ## ----GRAVY_pI--------------------------------------------------------- proteins <- c("LYSC_CHICK", "RNAS1_BOVIN", "AMYA_PYRFU") AA <- CHNOSZ::pinfo(CHNOSZ::pinfo(proteins)) pI(AA) GRAVY(AA) ## ----pdat_3D_datasets------------------------------------------------- pdat_3D() ## ----pdat_3D---------------------------------------------------------- pdat <- pdat_3D("DKM+20") str(pdat) ## ----get_comptab------------------------------------------------------ (get_comptab(pdat)) ## ----get_comptabs, message = FALSE, results = "hide"------------------ datasets <- pdat_3D() pdats <- lapply(datasets, pdat_3D) comptabs <- lapply(pdats, get_comptab) ## ----diffplot, fig.width=5, fig.height=5, fig.align = "center"-------- diffplot(comptabs) title("3D cell culture vs monolayers") ## ----vignettes, echo = FALSE------------------------------------------ functions <- grep("pdat_", ls("package:canprot"), value = TRUE) vignettes <- gsub("pdat_", "", functions) vignettes ## ----reset, include=FALSE----------------------------------------------------- options(oldopt)
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data_clean_up.R \name{clean_gacc} \alias{clean_gacc} \title{Clean up missing gaccs} \usage{ clean_gacc(inc_data, inc_info) } \arguments{ \item{inc_data}{Data frame containing daily incident assignments} \item{inc_info}{Data frame containing information on all the incidents of a season} } \value{ Vector of new agent home gaccs } \description{ Agents with missing home gaccs have their home gacc assigned to the gacc of the first fire of the season they are assigned to. }
/man/clean_gacc.Rd
permissive
jakedilliott/covidfireMASS
R
false
true
552
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data_clean_up.R \name{clean_gacc} \alias{clean_gacc} \title{Clean up missing gaccs} \usage{ clean_gacc(inc_data, inc_info) } \arguments{ \item{inc_data}{Data frame containing daily incident assignments} \item{inc_info}{Data frame containing information on all the incidents of a season} } \value{ Vector of new agent home gaccs } \description{ Agents with missing home gaccs have their home gacc assigned to the gacc of the first fire of the season they are assigned to. }
\name{combineFeatures} \alias{combineFeatures} \title{ Combines features in an \code{MSnSet} object } \description{ This function combines the features in an \code{"\linkS4class{MSnSet}"} instance applying a summarisation function (see \code{fun} argument) to sets of features as defined by a factor (see \code{fcol} argument). Note that the feature names are automatically updated based on the \code{groupBy} parameter. The coefficient of variations are automatically computed and collated to the featureData slot. See \code{cv} and \code{cv.norm} arguments for details. If NA values are present, a message will be shown. Details on how missing value impact on the data aggregation are provided below. } \usage{ combineFeatures(object, groupBy, method = c("mean", "median", "weighted.mean", "sum", "medpolish", "robust", "iPQF", "NTR"), fcol, redundancy.handler = c("unique", "multiple"), cv = TRUE, cv.norm = "sum", verbose = isMSnbaseVerbose(), fun, ...) } \arguments{ \item{object}{ An instance of class \code{"\linkS4class{MSnSet}"} whose features will be summerised. } \item{groupBy}{ A \code{factor}, \code{character}, \code{numeric} or a \code{list} of the above defining how to summerise the features. The list must be of length \code{nrow(object)}. Each element of the list is a vector describing the feature mapping. If the list can be named, its names must match \code{fetureNames(object)}. See \code{redundancy.handler} for details about the latter. } \item{fun}{Deprecated; use \code{method} instead. } \item{method}{ The summerising function. Currently, mean, median, weighted mean, sum, median polish, robust summarisation (using \code{MASS::rlm}), iPQF (see \code{\link{iPQF}} for details) and NTR (see \code{\link[MSnbase]{NTR}} for details) are implemented, but user-defined functions can also be supplied. Note that the robust menthods assumes that the data are already log-transformed. } \item{fcol}{Feature meta-data label (fData column name) defining how to summerise the features. It must be present in \code{fvarLabels(object)} and, if present, will be used to defined \code{groupBy} as \code{fData(object)[, fcol]}. Note that \code{fcol} is ignored if \code{groupBy} is present. } \item{redundancy.handler}{ If \code{groupBy} is a \code{list}, one of \code{"unique"} (default) or \code{"multiple"} (ignored otherwise) defining how to handle peptides that can be associated to multiple higher-level features (proteins) upon combination. Using \code{"unique"} will only consider uniquely matching features (features matching multiple proteins will be discarded). \code{"multiple"} will allow matching to multiple proteins and each feature will be repeatedly tallied for each possible matching protein. } \item{cv}{ A \code{logical} defining if feature coefficients of variation should be computed and stored as feature meta-data. Default is \code{TRUE}. } \item{cv.norm}{ A \code{character} defining how to normalise the feature intensitites prior to CV calculation. Default is \code{sum}. Use \code{none} to keep intensities as is. See \code{\link{featureCV}} for more details. } \item{verbose}{ A \code{logical} indicating whether verbose output is to be printed out. } \item{\dots}{ Additional arguments for the \code{fun} function. } } \value{ A new \code{"\linkS4class{MSnSet}"} instance is returned with \code{ncol} (i.e. number of samples) is unchanged, but \code{nrow} (i.e. the number od features) is now equals to the number of levels in \code{groupBy}. The feature metadata (\code{featureData} slot) is updated accordingly and only the first occurrence of a feature in the original feature meta-data is kept. } \details{ Missing values have different effect based on the aggregation method employed, as detailed below. See also examples below. \enumerate{ \item When using either \code{"sum"}, \code{"mean"}, \code{"weighted.mean"} or \code{"median"}, any missing value will be propagated at the higher level. If \code{na.rm = TRUE} is used, then the missing value will be ignored. \item Missing values will result in an error when using \code{"medpolish"}, unless \code{na.rm = TRUE} is used. \item When using robust summarisation (\code{"robust"}), individual missing values are excluded prior to fitting the linear model by robust regression. To remove all values in the feature containing the missing values, use \code{filterNA}. \item The \code{"iPQF"} method will fail with an error if missing value are present, which will have to be handled explicitly. See below. } More generally, missing values often need dedicated handling such as filtering (see \code{\link{filterNA}}) or imputation (see \code{\link{impute}}). } \author{ Laurent Gatto <lg390@cam.ac.uk> with contributions from Martina Fischer for iPQF and Ludger Goeminne, Adriaan Sticker and Lieven Clement for robust. } \references{ iPQF: a new peptide-to-protein summarization method using peptide spectra characteristics to improve protein quantification. Fischer M, Renard BY. Bioinformatics. 2016 Apr 1;32(7):1040-7. doi:10.1093/bioinformatics/btv675. Epub 2015 Nov 20. PubMed PMID:26589272. } \seealso{ \code{\link{featureCV}} to calculate coefficient of variation, \code{\link{nFeatures}} to document the number of features per group in the feature data, and the \code{\link{aggvar}} to explore variability within protein groups. \code{\link[MSnbase]{iPQF}} for iPQF summarisation. \code{\link[MSnbase]{NTR}} for normalisation to reference summarisation. } \examples{ data(msnset) msnset <- msnset[11:15, ] exprs(msnset) ## arbitrary grouping into two groups grp <- as.factor(c(1, 1, 2, 2, 2)) msnset.comb <- combineFeatures(msnset, grp, "sum") dim(msnset.comb) exprs(msnset.comb) fvarLabels(msnset.comb) ## grouping with a list grpl <- list(c("A", "B"), "A", "A", "C", c("C", "B")) ## optional naming names(grpl) <- featureNames(msnset) exprs(combineFeatures(msnset, grpl, method = "sum", redundancy.handler = "unique")) exprs(combineFeatures(msnset, grpl, method = "sum", redundancy.handler = "multiple")) ## missing data exprs(msnset)[4, 4] <- exprs(msnset)[2, 2] <- NA exprs(msnset) ## NAs propagate in the 115 and 117 channels exprs(combineFeatures(msnset, grp, "sum")) ## NAs are removed before summing exprs(combineFeatures(msnset, grp, "sum", na.rm = TRUE)) ## using iPQF data(msnset2) anyNA(msnset2) res <- combineFeatures(msnset2, groupBy = fData(msnset2)$accession, redundancy.handler = "unique", method = "iPQF", low.support.filter = FALSE, ratio.calc = "sum", method.combine = FALSE) head(exprs(res)) ## using robust summarisation data(msnset) ## reset data msnset <- log(msnset, 2) ## log2 transform ## Feature X46, in the ENO protein has one missig value which(is.na(msnset), arr.ind = dim(msnset)) exprs(msnset["X46", ]) ## Only the missing value in X46 and iTRAQ4.116 will be ignored res <- combineFeatures(msnset, fcol = "ProteinAccession", method = "robust") tail(exprs(res)) msnset2 <- filterNA(msnset) ## remove features with missing value(s) res2 <- combineFeatures(msnset2, fcol = "ProteinAccession", method = "robust") ## Here, the values for ENO are different because the whole feature ## X46 that contained the missing value was removed prior to fitting. tail(exprs(res2)) }
/man/combineFeatures.Rd
no_license
mjhelf/MSnbase
R
false
false
7,612
rd
\name{combineFeatures} \alias{combineFeatures} \title{ Combines features in an \code{MSnSet} object } \description{ This function combines the features in an \code{"\linkS4class{MSnSet}"} instance applying a summarisation function (see \code{fun} argument) to sets of features as defined by a factor (see \code{fcol} argument). Note that the feature names are automatically updated based on the \code{groupBy} parameter. The coefficient of variations are automatically computed and collated to the featureData slot. See \code{cv} and \code{cv.norm} arguments for details. If NA values are present, a message will be shown. Details on how missing value impact on the data aggregation are provided below. } \usage{ combineFeatures(object, groupBy, method = c("mean", "median", "weighted.mean", "sum", "medpolish", "robust", "iPQF", "NTR"), fcol, redundancy.handler = c("unique", "multiple"), cv = TRUE, cv.norm = "sum", verbose = isMSnbaseVerbose(), fun, ...) } \arguments{ \item{object}{ An instance of class \code{"\linkS4class{MSnSet}"} whose features will be summerised. } \item{groupBy}{ A \code{factor}, \code{character}, \code{numeric} or a \code{list} of the above defining how to summerise the features. The list must be of length \code{nrow(object)}. Each element of the list is a vector describing the feature mapping. If the list can be named, its names must match \code{fetureNames(object)}. See \code{redundancy.handler} for details about the latter. } \item{fun}{Deprecated; use \code{method} instead. } \item{method}{ The summerising function. Currently, mean, median, weighted mean, sum, median polish, robust summarisation (using \code{MASS::rlm}), iPQF (see \code{\link{iPQF}} for details) and NTR (see \code{\link[MSnbase]{NTR}} for details) are implemented, but user-defined functions can also be supplied. Note that the robust menthods assumes that the data are already log-transformed. } \item{fcol}{Feature meta-data label (fData column name) defining how to summerise the features. It must be present in \code{fvarLabels(object)} and, if present, will be used to defined \code{groupBy} as \code{fData(object)[, fcol]}. Note that \code{fcol} is ignored if \code{groupBy} is present. } \item{redundancy.handler}{ If \code{groupBy} is a \code{list}, one of \code{"unique"} (default) or \code{"multiple"} (ignored otherwise) defining how to handle peptides that can be associated to multiple higher-level features (proteins) upon combination. Using \code{"unique"} will only consider uniquely matching features (features matching multiple proteins will be discarded). \code{"multiple"} will allow matching to multiple proteins and each feature will be repeatedly tallied for each possible matching protein. } \item{cv}{ A \code{logical} defining if feature coefficients of variation should be computed and stored as feature meta-data. Default is \code{TRUE}. } \item{cv.norm}{ A \code{character} defining how to normalise the feature intensitites prior to CV calculation. Default is \code{sum}. Use \code{none} to keep intensities as is. See \code{\link{featureCV}} for more details. } \item{verbose}{ A \code{logical} indicating whether verbose output is to be printed out. } \item{\dots}{ Additional arguments for the \code{fun} function. } } \value{ A new \code{"\linkS4class{MSnSet}"} instance is returned with \code{ncol} (i.e. number of samples) is unchanged, but \code{nrow} (i.e. the number od features) is now equals to the number of levels in \code{groupBy}. The feature metadata (\code{featureData} slot) is updated accordingly and only the first occurrence of a feature in the original feature meta-data is kept. } \details{ Missing values have different effect based on the aggregation method employed, as detailed below. See also examples below. \enumerate{ \item When using either \code{"sum"}, \code{"mean"}, \code{"weighted.mean"} or \code{"median"}, any missing value will be propagated at the higher level. If \code{na.rm = TRUE} is used, then the missing value will be ignored. \item Missing values will result in an error when using \code{"medpolish"}, unless \code{na.rm = TRUE} is used. \item When using robust summarisation (\code{"robust"}), individual missing values are excluded prior to fitting the linear model by robust regression. To remove all values in the feature containing the missing values, use \code{filterNA}. \item The \code{"iPQF"} method will fail with an error if missing value are present, which will have to be handled explicitly. See below. } More generally, missing values often need dedicated handling such as filtering (see \code{\link{filterNA}}) or imputation (see \code{\link{impute}}). } \author{ Laurent Gatto <lg390@cam.ac.uk> with contributions from Martina Fischer for iPQF and Ludger Goeminne, Adriaan Sticker and Lieven Clement for robust. } \references{ iPQF: a new peptide-to-protein summarization method using peptide spectra characteristics to improve protein quantification. Fischer M, Renard BY. Bioinformatics. 2016 Apr 1;32(7):1040-7. doi:10.1093/bioinformatics/btv675. Epub 2015 Nov 20. PubMed PMID:26589272. } \seealso{ \code{\link{featureCV}} to calculate coefficient of variation, \code{\link{nFeatures}} to document the number of features per group in the feature data, and the \code{\link{aggvar}} to explore variability within protein groups. \code{\link[MSnbase]{iPQF}} for iPQF summarisation. \code{\link[MSnbase]{NTR}} for normalisation to reference summarisation. } \examples{ data(msnset) msnset <- msnset[11:15, ] exprs(msnset) ## arbitrary grouping into two groups grp <- as.factor(c(1, 1, 2, 2, 2)) msnset.comb <- combineFeatures(msnset, grp, "sum") dim(msnset.comb) exprs(msnset.comb) fvarLabels(msnset.comb) ## grouping with a list grpl <- list(c("A", "B"), "A", "A", "C", c("C", "B")) ## optional naming names(grpl) <- featureNames(msnset) exprs(combineFeatures(msnset, grpl, method = "sum", redundancy.handler = "unique")) exprs(combineFeatures(msnset, grpl, method = "sum", redundancy.handler = "multiple")) ## missing data exprs(msnset)[4, 4] <- exprs(msnset)[2, 2] <- NA exprs(msnset) ## NAs propagate in the 115 and 117 channels exprs(combineFeatures(msnset, grp, "sum")) ## NAs are removed before summing exprs(combineFeatures(msnset, grp, "sum", na.rm = TRUE)) ## using iPQF data(msnset2) anyNA(msnset2) res <- combineFeatures(msnset2, groupBy = fData(msnset2)$accession, redundancy.handler = "unique", method = "iPQF", low.support.filter = FALSE, ratio.calc = "sum", method.combine = FALSE) head(exprs(res)) ## using robust summarisation data(msnset) ## reset data msnset <- log(msnset, 2) ## log2 transform ## Feature X46, in the ENO protein has one missig value which(is.na(msnset), arr.ind = dim(msnset)) exprs(msnset["X46", ]) ## Only the missing value in X46 and iTRAQ4.116 will be ignored res <- combineFeatures(msnset, fcol = "ProteinAccession", method = "robust") tail(exprs(res)) msnset2 <- filterNA(msnset) ## remove features with missing value(s) res2 <- combineFeatures(msnset2, fcol = "ProteinAccession", method = "robust") ## Here, the values for ENO are different because the whole feature ## X46 that contained the missing value was removed prior to fitting. tail(exprs(res2)) }
## Quiz 4 - Statistical Inferencing ### Question 1 # A pharmaceutical company is interested in testing a potential blood pressure lowering medication. Their first examination # considers only subjects that received the medication at baseline then two weeks later. The data are as follows (SBP in mmHg) #Subject Baseline Week 2 #1 140 132 #2 138 135 #3 150 151 #4 148 146 # 135 130 # Consider testing the hypothesis that there was a mean reduction in blood pressure? Give the P-value for the associated two # sided T test. # asnwer 0.087 base <- (c(140,138,150,148,135)) final <- c(132,135,151,146,130) t.test(base,final,alternative="two.sided",paired=TRUE) ### Question 2 # A sample of 9 men yielded a sample average brain volume of 1,100cc and a standard deviation of 30cc. What is the complete set # of values of ??actual mean that a test of H0:??=??0 would fail to reject the null hypothesis in a two sided 5% Students t-test? # answer 1077 to 1123 meanS <- 1100 sdS <- 30 n <- 9 ul <- meanS + qt(0.975,n-1) * sdS/sqrt(n) ll <- meanS - qt(0.975,n-1) * sdS/sqrt(n) ul ll ### Question 3 # Researchers conducted a blind taste test of Coke versus Pepsi. Each of four people was asked which of two blinded drinks # given in random order that they preferred. The data was such that 3 of the 4 people chose Coke. Assuming that this sample is # representative, report a P-value for a test of the hypothesis that Coke is preferred to Pepsi using a one sided exact test. # http://www.instantr.com/2012/11/06/performing-a-binomial-test/ # answer 0.31 binom.test(3,4,0.5,alternative="greater") ### Question 4 # Infection rates at a hospital above 1 infection per 100 person days at risk are believed to be too high and are used as a # benchmark. A hospital that had previously been above the benchmark recently had 10 infections over the last 1,787 person days # at risk. About what is the one sided P-value for the relevant test of whether the hospital is *below* the standard? lambdaH0 <- 1/100 lambdaHA <- 10/1787 days <- 1787 infects <- 10 ppois(infects,lambdaH0*days,lower.tail=TRUE) # ANSWER = 0.03 ### Question 5 # Suppose that 18 obese subjects were randomized, 9 each, to a new diet pill and a placebo. Subjects??? body mass indices (BMIs) # were measured at a baseline and again after having received the treatment or placebo for four weeks. The average difference # from follow-up to the baseline (followup - baseline) was ???3 kg/m2 for the treated group and 1 kg/m2 for the placebo group. # The corresponding standard deviations of the differences was 1.5 kg/m2 for the treatment group and 1.8 kg/m2 for the placebo # group. Does the change in BMI appear to differ between the treated and placebo groups? Assuming normality of the underlying # data and a common population variance, give a pvalue for a two sided t test. md <- -3 - 1 n1 <- n2 <- 9 var1 <- 1.5*sqrt(n1) var2 <- 1.8*sqrt(n2) sp <- sqrt(((n1-1)*var1 + (n2-1)*var2)/(n1 + n2-2)) semd <- sp * sqrt(1/n1 + 1/n2) md + c(-1,1) * qt(0.95,n1 + n2 - 2) * semd # T interval: -5.324521 -2.675479 # P Value for independent group T test (two-sided) mean.diff <- md df <- n1 + n2 - 2 sd1 <- 1.5 sd2 <- 1.8 pooled.var = (sd1^2 * n1 + sd2^2 * n2) / df se.diff = sqrt(pooled.var/n1 + pooled.var/n2) t.obt = mean.diff / se.diff t.obt p.value = 2*pt(t.obt,df=df) # two-tailed p.value #ANSWER = Less than 0.01 ### Question 6 # Brain volumes for 9 men yielded a 90% confidence interval of 1,077 cc to 1,123 cc. Would you reject in a two sided 5% # hypothesis test of H0:??=1,078? # ANSWER = Not Reject ### Question 7 # Researchers would like to conduct a study of 100 healthy adults to detect a four year mean brain volume loss of .01 mm3. # Assume that the standard deviation of four year volume loss in this population is .04 mm3. About what would be the power of # the study for a 5% one sided test versus a null hypothesis of no volume loss? power.t.test(n=100,delta=0.01,sd=0.04,alternative="one.sided",type="one.sample",sig.level=0.05)$power #ANSWER = 0.8 ### Question 8 # Researchers would like to conduct a study of n healthy adults to detect a four year mean brain volume loss of .01 mm3. # Assume that the standard deviation of four year volume loss in this population is .04 mm3. About what would be the value of # n needded for 90% power of type one error rate of 5% one sided test versus a null hypothesis of no volume loss? power.t.test(power=0.9,delta=0.01,sd=0.04,alternative="one.sided",type="one.sample",sig.level=0.05)$n # ANSWER = 140 ### Question 9 # As you increase the type one error rate, ??, what happens to power? # ANSWER = You will get larger power
/quiz4.R
no_license
henrybowers/StatisticalInference
R
false
false
4,687
r
## Quiz 4 - Statistical Inferencing ### Question 1 # A pharmaceutical company is interested in testing a potential blood pressure lowering medication. Their first examination # considers only subjects that received the medication at baseline then two weeks later. The data are as follows (SBP in mmHg) #Subject Baseline Week 2 #1 140 132 #2 138 135 #3 150 151 #4 148 146 # 135 130 # Consider testing the hypothesis that there was a mean reduction in blood pressure? Give the P-value for the associated two # sided T test. # asnwer 0.087 base <- (c(140,138,150,148,135)) final <- c(132,135,151,146,130) t.test(base,final,alternative="two.sided",paired=TRUE) ### Question 2 # A sample of 9 men yielded a sample average brain volume of 1,100cc and a standard deviation of 30cc. What is the complete set # of values of ??actual mean that a test of H0:??=??0 would fail to reject the null hypothesis in a two sided 5% Students t-test? # answer 1077 to 1123 meanS <- 1100 sdS <- 30 n <- 9 ul <- meanS + qt(0.975,n-1) * sdS/sqrt(n) ll <- meanS - qt(0.975,n-1) * sdS/sqrt(n) ul ll ### Question 3 # Researchers conducted a blind taste test of Coke versus Pepsi. Each of four people was asked which of two blinded drinks # given in random order that they preferred. The data was such that 3 of the 4 people chose Coke. Assuming that this sample is # representative, report a P-value for a test of the hypothesis that Coke is preferred to Pepsi using a one sided exact test. # http://www.instantr.com/2012/11/06/performing-a-binomial-test/ # answer 0.31 binom.test(3,4,0.5,alternative="greater") ### Question 4 # Infection rates at a hospital above 1 infection per 100 person days at risk are believed to be too high and are used as a # benchmark. A hospital that had previously been above the benchmark recently had 10 infections over the last 1,787 person days # at risk. About what is the one sided P-value for the relevant test of whether the hospital is *below* the standard? lambdaH0 <- 1/100 lambdaHA <- 10/1787 days <- 1787 infects <- 10 ppois(infects,lambdaH0*days,lower.tail=TRUE) # ANSWER = 0.03 ### Question 5 # Suppose that 18 obese subjects were randomized, 9 each, to a new diet pill and a placebo. Subjects??? body mass indices (BMIs) # were measured at a baseline and again after having received the treatment or placebo for four weeks. The average difference # from follow-up to the baseline (followup - baseline) was ???3 kg/m2 for the treated group and 1 kg/m2 for the placebo group. # The corresponding standard deviations of the differences was 1.5 kg/m2 for the treatment group and 1.8 kg/m2 for the placebo # group. Does the change in BMI appear to differ between the treated and placebo groups? Assuming normality of the underlying # data and a common population variance, give a pvalue for a two sided t test. md <- -3 - 1 n1 <- n2 <- 9 var1 <- 1.5*sqrt(n1) var2 <- 1.8*sqrt(n2) sp <- sqrt(((n1-1)*var1 + (n2-1)*var2)/(n1 + n2-2)) semd <- sp * sqrt(1/n1 + 1/n2) md + c(-1,1) * qt(0.95,n1 + n2 - 2) * semd # T interval: -5.324521 -2.675479 # P Value for independent group T test (two-sided) mean.diff <- md df <- n1 + n2 - 2 sd1 <- 1.5 sd2 <- 1.8 pooled.var = (sd1^2 * n1 + sd2^2 * n2) / df se.diff = sqrt(pooled.var/n1 + pooled.var/n2) t.obt = mean.diff / se.diff t.obt p.value = 2*pt(t.obt,df=df) # two-tailed p.value #ANSWER = Less than 0.01 ### Question 6 # Brain volumes for 9 men yielded a 90% confidence interval of 1,077 cc to 1,123 cc. Would you reject in a two sided 5% # hypothesis test of H0:??=1,078? # ANSWER = Not Reject ### Question 7 # Researchers would like to conduct a study of 100 healthy adults to detect a four year mean brain volume loss of .01 mm3. # Assume that the standard deviation of four year volume loss in this population is .04 mm3. About what would be the power of # the study for a 5% one sided test versus a null hypothesis of no volume loss? power.t.test(n=100,delta=0.01,sd=0.04,alternative="one.sided",type="one.sample",sig.level=0.05)$power #ANSWER = 0.8 ### Question 8 # Researchers would like to conduct a study of n healthy adults to detect a four year mean brain volume loss of .01 mm3. # Assume that the standard deviation of four year volume loss in this population is .04 mm3. About what would be the value of # n needded for 90% power of type one error rate of 5% one sided test versus a null hypothesis of no volume loss? power.t.test(power=0.9,delta=0.01,sd=0.04,alternative="one.sided",type="one.sample",sig.level=0.05)$n # ANSWER = 140 ### Question 9 # As you increase the type one error rate, ??, what happens to power? # ANSWER = You will get larger power
training_data_raw <- read.csv("train.csv") test_data <- read.csv("test.csv") library("caret") library("e1071") # might need to create binary target variables training_data_raw$target_ONE <- ifelse(training_data_raw$target == "Class_1", 1, 0) training_data_raw$target_TWO <- ifelse(training_data_raw$target == "Class_2", 1, 0) training_data_raw$target_THREE <- ifelse(training_data_raw$target == "Class_3", 1, 0) training_data_raw$target_FOUR <- ifelse(training_data_raw$target == "Class_4", 1, 0) training_data_raw$target_FIVE <- ifelse(training_data_raw$target == "Class_5", 1, 0) training_data_raw$target_SIX <- ifelse(training_data_raw$target == "Class_6", 1, 0) training_data_raw$target_SEVEN <- ifelse(training_data_raw$target == "Class_7", 1, 0) training_data_raw$target_EIGHT <- ifelse(training_data_raw$target == "Class_8", 1, 0) training_data_raw$target_NINE <- ifelse(training_data_raw$target == "Class_9", 1, 0) # create new training data set with equally distributed number of rows and all thats left is for the hold out sample for cv set.seed(1188) classOne <- training_data_raw[training_data_raw$target_ONE == 1,] classTwo <- training_data_raw[training_data_raw$target_TWO == 1,] classThree <- training_data_raw[training_data_raw$target_THREE == 1,] classFour <- training_data_raw[training_data_raw$target_FOUR == 1,] classFive <- training_data_raw[training_data_raw$target_FIVE == 1,] classSix <- training_data_raw[training_data_raw$target_SIX == 1,] classSeven <- training_data_raw[training_data_raw$target_SEVEN == 1,] classEight <- training_data_raw[training_data_raw$target_EIGHT == 1,] classNine <- training_data_raw[training_data_raw$target_NINE == 1,] # subsample trainingOne <- classOne[sample(1:nrow(classOne), 1500, replace=FALSE),] valOne <- classOne[-sample(1:nrow(classOne), 1500, replace=FALSE),] trainingTwo <- classTwo[sample(1:nrow(classTwo), 1500, replace=FALSE),] valTwo <- classTwo[-sample(1:nrow(classTwo), 1500, replace=FALSE),] trainingThree <- classThree[sample(1:nrow(classThree), 1500, replace=FALSE),] valThree <- classThree[-sample(1:nrow(classThree), 1500, replace=FALSE),] trainingFour <- classFour[sample(1:nrow(classFour), 1500, replace=FALSE),] valFour <- classFour[-sample(1:nrow(classFour), 1500, replace=FALSE),] trainingFive <- classFive[sample(1:nrow(classFive), 1500, replace=FALSE),] valFive <- classFive[-sample(1:nrow(classFive), 1500, replace=FALSE),] trainingSix <- classSix[sample(1:nrow(classSix), 1500, replace=FALSE),] valSix <- classSix[-sample(1:nrow(classSix), 1500, replace=FALSE),] trainingSeven <- classSeven[sample(1:nrow(classSeven), 1500, replace=FALSE),] valSeven <- classSeven[-sample(1:nrow(classSeven), 1500, replace=FALSE),] trainingEight <- classEight[sample(1:nrow(classEight), 1500, replace=FALSE),] valEight <- classEight[-sample(1:nrow(classEight), 1500, replace=FALSE),] trainingNine <- classNine[sample(1:nrow(classNine), 1500, replace=FALSE),] valNine <- classNine[-sample(1:nrow(classNine), 1500, replace=FALSE),] ################################################################################# # merging ################################################################################# training_data <- NULL training_data <- rbind(training_data,trainingOne,trainingTwo,trainingThree,trainingFour,trainingFive,trainingSix,trainingSeven,trainingEight,trainingNine) # shuffle the deck training_data <- training_data[sample(nrow(training_data)),] holdout_sample <- NULL holdout_sample <- rbind(holdout_sample,valOne,valTwo,valThree,valFour,valFive,valSix,valSeven,valEight,valNine) targets <- training_data[,96:104] targets_cv <- holdout_sample[,96:104] predictions <- NULL models <- NULL cost <- NULL ## Grid search # building one multiclass model with multiple hidden layers gammas <- c(0.003, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1) for (k in 1:9) { for (i in 1:length(gammas)){ print(k) print(i) mySVM <- svm(as.matrix(training_data[,2:94]), as.factor(targets[,k]) , kernel = "radial", scale = TRUE, probability = TRUE, gamma = gammas[i]) # save model # models <- rbind(models, c(k, lambdas[i], neurons[j], nnetFit)) # make predictions on holdout sample pred_holdout <- predict(mySVM, holdout_sample[,2:94], probability = TRUE) pred_holdout <- attr(pred_holdout, "probabilities") # calculate and save cost cost <- rbind(cost, c(k, i, sum((targets_cv-pred_holdout)^2))) #pred <- predict(mySVM, test_data[,2:94], probability = TRUE) #pred <- attr(pred, "probabilities") #pred <- pred[,2] #predictions <- cbind(predictions, pred) } } # add id column predictions <- cbind(test_data$id,predictions) # convert matrix to data.frame in order to add names predictions <- as.data.frame(predictions) names(predictions) <- c("id","Class_1","Class_2","Class_3","Class_4","Class_5","Class_6","Class_7","Class_8","Class_9") # convert id to interger for submission reasons predictions$id <- as.integer(predictions$id) write.csv(predictions, file = "./resultsMulticlassSVM_oneVsAll.csv", row.names = FALSE)
/[2015] Otto Group Product Classification Challenge/scripts/2015_05_04_SVM_OneVsAll.R
no_license
r-haase/Kaggle
R
false
false
5,276
r
training_data_raw <- read.csv("train.csv") test_data <- read.csv("test.csv") library("caret") library("e1071") # might need to create binary target variables training_data_raw$target_ONE <- ifelse(training_data_raw$target == "Class_1", 1, 0) training_data_raw$target_TWO <- ifelse(training_data_raw$target == "Class_2", 1, 0) training_data_raw$target_THREE <- ifelse(training_data_raw$target == "Class_3", 1, 0) training_data_raw$target_FOUR <- ifelse(training_data_raw$target == "Class_4", 1, 0) training_data_raw$target_FIVE <- ifelse(training_data_raw$target == "Class_5", 1, 0) training_data_raw$target_SIX <- ifelse(training_data_raw$target == "Class_6", 1, 0) training_data_raw$target_SEVEN <- ifelse(training_data_raw$target == "Class_7", 1, 0) training_data_raw$target_EIGHT <- ifelse(training_data_raw$target == "Class_8", 1, 0) training_data_raw$target_NINE <- ifelse(training_data_raw$target == "Class_9", 1, 0) # create new training data set with equally distributed number of rows and all thats left is for the hold out sample for cv set.seed(1188) classOne <- training_data_raw[training_data_raw$target_ONE == 1,] classTwo <- training_data_raw[training_data_raw$target_TWO == 1,] classThree <- training_data_raw[training_data_raw$target_THREE == 1,] classFour <- training_data_raw[training_data_raw$target_FOUR == 1,] classFive <- training_data_raw[training_data_raw$target_FIVE == 1,] classSix <- training_data_raw[training_data_raw$target_SIX == 1,] classSeven <- training_data_raw[training_data_raw$target_SEVEN == 1,] classEight <- training_data_raw[training_data_raw$target_EIGHT == 1,] classNine <- training_data_raw[training_data_raw$target_NINE == 1,] # subsample trainingOne <- classOne[sample(1:nrow(classOne), 1500, replace=FALSE),] valOne <- classOne[-sample(1:nrow(classOne), 1500, replace=FALSE),] trainingTwo <- classTwo[sample(1:nrow(classTwo), 1500, replace=FALSE),] valTwo <- classTwo[-sample(1:nrow(classTwo), 1500, replace=FALSE),] trainingThree <- classThree[sample(1:nrow(classThree), 1500, replace=FALSE),] valThree <- classThree[-sample(1:nrow(classThree), 1500, replace=FALSE),] trainingFour <- classFour[sample(1:nrow(classFour), 1500, replace=FALSE),] valFour <- classFour[-sample(1:nrow(classFour), 1500, replace=FALSE),] trainingFive <- classFive[sample(1:nrow(classFive), 1500, replace=FALSE),] valFive <- classFive[-sample(1:nrow(classFive), 1500, replace=FALSE),] trainingSix <- classSix[sample(1:nrow(classSix), 1500, replace=FALSE),] valSix <- classSix[-sample(1:nrow(classSix), 1500, replace=FALSE),] trainingSeven <- classSeven[sample(1:nrow(classSeven), 1500, replace=FALSE),] valSeven <- classSeven[-sample(1:nrow(classSeven), 1500, replace=FALSE),] trainingEight <- classEight[sample(1:nrow(classEight), 1500, replace=FALSE),] valEight <- classEight[-sample(1:nrow(classEight), 1500, replace=FALSE),] trainingNine <- classNine[sample(1:nrow(classNine), 1500, replace=FALSE),] valNine <- classNine[-sample(1:nrow(classNine), 1500, replace=FALSE),] ################################################################################# # merging ################################################################################# training_data <- NULL training_data <- rbind(training_data,trainingOne,trainingTwo,trainingThree,trainingFour,trainingFive,trainingSix,trainingSeven,trainingEight,trainingNine) # shuffle the deck training_data <- training_data[sample(nrow(training_data)),] holdout_sample <- NULL holdout_sample <- rbind(holdout_sample,valOne,valTwo,valThree,valFour,valFive,valSix,valSeven,valEight,valNine) targets <- training_data[,96:104] targets_cv <- holdout_sample[,96:104] predictions <- NULL models <- NULL cost <- NULL ## Grid search # building one multiclass model with multiple hidden layers gammas <- c(0.003, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1) for (k in 1:9) { for (i in 1:length(gammas)){ print(k) print(i) mySVM <- svm(as.matrix(training_data[,2:94]), as.factor(targets[,k]) , kernel = "radial", scale = TRUE, probability = TRUE, gamma = gammas[i]) # save model # models <- rbind(models, c(k, lambdas[i], neurons[j], nnetFit)) # make predictions on holdout sample pred_holdout <- predict(mySVM, holdout_sample[,2:94], probability = TRUE) pred_holdout <- attr(pred_holdout, "probabilities") # calculate and save cost cost <- rbind(cost, c(k, i, sum((targets_cv-pred_holdout)^2))) #pred <- predict(mySVM, test_data[,2:94], probability = TRUE) #pred <- attr(pred, "probabilities") #pred <- pred[,2] #predictions <- cbind(predictions, pred) } } # add id column predictions <- cbind(test_data$id,predictions) # convert matrix to data.frame in order to add names predictions <- as.data.frame(predictions) names(predictions) <- c("id","Class_1","Class_2","Class_3","Class_4","Class_5","Class_6","Class_7","Class_8","Class_9") # convert id to interger for submission reasons predictions$id <- as.integer(predictions$id) write.csv(predictions, file = "./resultsMulticlassSVM_oneVsAll.csv", row.names = FALSE)
library(shinydashboard) library(curl) library(zoo) library(tseries) library(PerformanceAnalytics) library(quantmod) library(dygraphs) library(forecast) ##HEADER header<- dashboardHeader(title = "820651-WebApp") ##SIDEBAR sidebar<-dashboardSidebar( sidebarMenu( menuItem("Descriptive Statistics", tabName="Stats", icon=icon("bar-chart-o")), menuItem("Forecasting", tabName="Forecasting", icon=icon("list-alt")), menuItem("Multivariate", tabName="Multivariate", icon=icon("list")) ) ) ##MENU TAB1 tab1<-tabItem( tabName="Stats", fluidRow( box( title="Plots", status="primary", solidHeader=TRUE, collapsible=TRUE, # plotOutput("plot"), # dygraphOutput("plot2") conditionalPanel('input.radio<=4', plotOutput("plot")), conditionalPanel('input.radio==5', dygraphOutput("plot2")) ##There has to be a better solution ), box( title = "Controls", solidHeader = TRUE, collapsible=TRUE, width=4, dateRangeInput( "dates", label = h3("Date range"), start='2009-01-01', end= '2019-01-01', max=Sys.Date() ), # sliderInput # ( # inputId="num", # label="Choose a number", # value=40,min=1,max=100 # ), textInput ( inputId="title", label="Insert a Title", value="Default Title" ), textInput ( inputId="stocks", label="Insert the stock(s) you want to plot", value="AMZN" ), radioButtons( "radio", h3("Plot type"), choices = list("Histogram" = 1, "Line Plot" = 2, "QQ Plot" = 3, "Box Plot" = 4),selected = 1), #"DyGraph [ONLY FOR TS]" = 5 radioButtons( "radio2", h3("Compression"), choices = list("Monthly" = "m", "Weekly" = "w", "Daily" = "d"),selected = "m"), radioButtons( "radio3", h3("Value to plot"), choices = list("Open" = "Open", "High" = "High", "Low" = "Low", "Close" = "Close"),selected = "High"), actionButton(inputId="clicks", label="UpdatePlot") ) ), fluidRow( box(title=h3("Summary"),verbatimTextOutput(outputId = "stats")) ), fluidRow( box( title=h3("Quantile,Kurtosis & Skewness"), verbatimTextOutput(outputId="quantile"), verbatimTextOutput(outputId = "kurtosis"), verbatimTextOutput(outputId="skewness")) ) ) ##MENU TAB2 tab2<- tabItem(tabName="Forecasting", fluidRow( box(title="Controls Forecast", solidHeader=TRUE, collapsible=TRUE, dateRangeInput( "datesForecasting", label = h3("Date range Forecasting"), start='2009-01-01', end= '2019-01-01', max=Sys.Date() ), #Percentages sliderInput("sliderForecasting", label = h3("Slider Range"), min = 0, max = 100, value = c(70, 90)), textInput ( inputId="stocksForecasting", label="Insert the stock(s) you want to plot", value="AMZN" ), radioButtons( inputId="arimaRadio", label=h3("Method:"), #ML=>Missing Values #CSS=>Conditional sum-of-squares choices=list("ML"="ML","CSS"="CSS", "CSS-ML"="CSS-ML") ), actionButton(inputId="clicksForecast", label="Update") ), box(title="Statistics", solidHeader = TRUE, collapsible = TRUE), verbatimTextOutput(outputId = "statsForecast") ), fluidRow( box(title="PlotsForecasting", status="primary", width=12, solidHeader=TRUE, collapsible=TRUE, plotOutput("Decomposition"), plotOutput("Forecast")) ) ) tab3<- tabItem(tabName="Multivariate", fluidRow( box( title="Plots", status="primary", solidHeader=TRUE, collpasible=TRUE, # plotOutput("plot"), # dygraphOutput("plot2") conditionalPanel('input.radioMulti==1', dygraphOutput("dygraphPlot")), conditionalPanel('input.radioMulti==2', plotOutput("correlationMatrix")) ), box( title="Controls", solidHeader = TRUE, collapsible=TRUE, width=4, dateRangeInput( "datesMulti", label = h3("Date range"), start='2009-01-01', end= '2019-01-01', max=Sys.Date() ), textInput ( inputId="stocksMulti1", label="Insert the stock you want to plot", value="AMZN" ), textInput ( inputId="stocksMulti2", label="Insert the stock you want to plot", value="GOOG" ), textInput ( inputId="stocksMulti3", label="Insert the stock you want to plot", value="FB" ), textInput ( inputId="stocksMulti4", label="Insert the stock you want to plot", value="ATVI" ), radioButtons( "radioMulti", h3("Plot type"), choices = list("DyGraph" = 1, "CorrelationMatrix [ATLEAST 2 STOCKS]" = 2) ,selected = 1), actionButton(inputId="clicksMultivariate", label="Update") ) ) ) ##BODY == TAB1+TAB2+TAB3 body<- dashboardBody( # Boxes need to be put in a row (or column) tabItems( tab1, tab2, tab3 ) ) ##UI == EVERYTHING TOGETHER ui <- dashboardPage( skin="purple", header, sidebar, body )
/Project/ui.R
no_license
LeoFraq/bisf
R
false
false
8,132
r
library(shinydashboard) library(curl) library(zoo) library(tseries) library(PerformanceAnalytics) library(quantmod) library(dygraphs) library(forecast) ##HEADER header<- dashboardHeader(title = "820651-WebApp") ##SIDEBAR sidebar<-dashboardSidebar( sidebarMenu( menuItem("Descriptive Statistics", tabName="Stats", icon=icon("bar-chart-o")), menuItem("Forecasting", tabName="Forecasting", icon=icon("list-alt")), menuItem("Multivariate", tabName="Multivariate", icon=icon("list")) ) ) ##MENU TAB1 tab1<-tabItem( tabName="Stats", fluidRow( box( title="Plots", status="primary", solidHeader=TRUE, collapsible=TRUE, # plotOutput("plot"), # dygraphOutput("plot2") conditionalPanel('input.radio<=4', plotOutput("plot")), conditionalPanel('input.radio==5', dygraphOutput("plot2")) ##There has to be a better solution ), box( title = "Controls", solidHeader = TRUE, collapsible=TRUE, width=4, dateRangeInput( "dates", label = h3("Date range"), start='2009-01-01', end= '2019-01-01', max=Sys.Date() ), # sliderInput # ( # inputId="num", # label="Choose a number", # value=40,min=1,max=100 # ), textInput ( inputId="title", label="Insert a Title", value="Default Title" ), textInput ( inputId="stocks", label="Insert the stock(s) you want to plot", value="AMZN" ), radioButtons( "radio", h3("Plot type"), choices = list("Histogram" = 1, "Line Plot" = 2, "QQ Plot" = 3, "Box Plot" = 4),selected = 1), #"DyGraph [ONLY FOR TS]" = 5 radioButtons( "radio2", h3("Compression"), choices = list("Monthly" = "m", "Weekly" = "w", "Daily" = "d"),selected = "m"), radioButtons( "radio3", h3("Value to plot"), choices = list("Open" = "Open", "High" = "High", "Low" = "Low", "Close" = "Close"),selected = "High"), actionButton(inputId="clicks", label="UpdatePlot") ) ), fluidRow( box(title=h3("Summary"),verbatimTextOutput(outputId = "stats")) ), fluidRow( box( title=h3("Quantile,Kurtosis & Skewness"), verbatimTextOutput(outputId="quantile"), verbatimTextOutput(outputId = "kurtosis"), verbatimTextOutput(outputId="skewness")) ) ) ##MENU TAB2 tab2<- tabItem(tabName="Forecasting", fluidRow( box(title="Controls Forecast", solidHeader=TRUE, collapsible=TRUE, dateRangeInput( "datesForecasting", label = h3("Date range Forecasting"), start='2009-01-01', end= '2019-01-01', max=Sys.Date() ), #Percentages sliderInput("sliderForecasting", label = h3("Slider Range"), min = 0, max = 100, value = c(70, 90)), textInput ( inputId="stocksForecasting", label="Insert the stock(s) you want to plot", value="AMZN" ), radioButtons( inputId="arimaRadio", label=h3("Method:"), #ML=>Missing Values #CSS=>Conditional sum-of-squares choices=list("ML"="ML","CSS"="CSS", "CSS-ML"="CSS-ML") ), actionButton(inputId="clicksForecast", label="Update") ), box(title="Statistics", solidHeader = TRUE, collapsible = TRUE), verbatimTextOutput(outputId = "statsForecast") ), fluidRow( box(title="PlotsForecasting", status="primary", width=12, solidHeader=TRUE, collapsible=TRUE, plotOutput("Decomposition"), plotOutput("Forecast")) ) ) tab3<- tabItem(tabName="Multivariate", fluidRow( box( title="Plots", status="primary", solidHeader=TRUE, collpasible=TRUE, # plotOutput("plot"), # dygraphOutput("plot2") conditionalPanel('input.radioMulti==1', dygraphOutput("dygraphPlot")), conditionalPanel('input.radioMulti==2', plotOutput("correlationMatrix")) ), box( title="Controls", solidHeader = TRUE, collapsible=TRUE, width=4, dateRangeInput( "datesMulti", label = h3("Date range"), start='2009-01-01', end= '2019-01-01', max=Sys.Date() ), textInput ( inputId="stocksMulti1", label="Insert the stock you want to plot", value="AMZN" ), textInput ( inputId="stocksMulti2", label="Insert the stock you want to plot", value="GOOG" ), textInput ( inputId="stocksMulti3", label="Insert the stock you want to plot", value="FB" ), textInput ( inputId="stocksMulti4", label="Insert the stock you want to plot", value="ATVI" ), radioButtons( "radioMulti", h3("Plot type"), choices = list("DyGraph" = 1, "CorrelationMatrix [ATLEAST 2 STOCKS]" = 2) ,selected = 1), actionButton(inputId="clicksMultivariate", label="Update") ) ) ) ##BODY == TAB1+TAB2+TAB3 body<- dashboardBody( # Boxes need to be put in a row (or column) tabItems( tab1, tab2, tab3 ) ) ##UI == EVERYTHING TOGETHER ui <- dashboardPage( skin="purple", header, sidebar, body )
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mc_from_coclust.r \name{mcell_mc_from_coclust_louv_sub} \alias{mcell_mc_from_coclust_louv_sub} \title{build a metacell cover from a big co-clust using louvain clustering and metacell coverage within clusters} \usage{ mcell_mc_from_coclust_louv_sub( mc_id, coc_id, mat_id, max_clust_size, max_mc_size, min_mc_size, T_weight = 1 ) } \arguments{ \item{mc_id}{Id of new metacell object} \item{coc_id}{cocluster object to use} \item{mat_id}{mat object to use when building the mc object} \item{max_clust_size}{maximum clust size. Bigger chunks will be clustered} \item{max_mc_size}{maximum mc size (bigger clusters will be dissected)} } \description{ build a metacell cover from a big co-clust using louvain clustering and metacell coverage within clusters }
/man/mcell_mc_from_coclust_louv_sub.Rd
permissive
tanaylab/metacell
R
false
true
850
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/mc_from_coclust.r \name{mcell_mc_from_coclust_louv_sub} \alias{mcell_mc_from_coclust_louv_sub} \title{build a metacell cover from a big co-clust using louvain clustering and metacell coverage within clusters} \usage{ mcell_mc_from_coclust_louv_sub( mc_id, coc_id, mat_id, max_clust_size, max_mc_size, min_mc_size, T_weight = 1 ) } \arguments{ \item{mc_id}{Id of new metacell object} \item{coc_id}{cocluster object to use} \item{mat_id}{mat object to use when building the mc object} \item{max_clust_size}{maximum clust size. Bigger chunks will be clustered} \item{max_mc_size}{maximum mc size (bigger clusters will be dissected)} } \description{ build a metacell cover from a big co-clust using louvain clustering and metacell coverage within clusters }
library(dplyr) library(plyr) #The order of the steps are different than the task #reading files (includes also step 4) features<- read.table("features.txt") #import features activity_labels<-read.table("activity_labels.txt",col.names = c("label","activity_name")) #import activity_labels test_X<- read.table("test/X_test.txt",col.names = as.vector(features[[2]])) #import test_X_test add column names test_y<- read.table("test/y_test.txt",col.names= "label") #import test_y_test subject_test <- read.table("test/subject_test.txt",col.names="subject_label") # import subjet train train_X<- read.table("train/X_train.txt",col.names = as.vector(features[[2]])) #import train_X_test add column names train_y<- read.table("train/y_train.txt",col.names= "label") #import train_y_test subject_train <- read.table("train/subject_train.txt",col.names="subject_label") # import subjet train #(step 3) Change label to activity name in test_y and train_Y test_y_activity<- join(test_y,activity_labels)[-1] #test_y with activity names in stead of labels train_y_activity<- join(train_y,activity_labels)[-1] #train_y with activity names in stead of labels #(step 1) merge test and train sets merged_test <- cbind(test_y_activity,subject_test,test_X) merged_train <- cbind(train_y_activity,subject_train,train_X) merged_ALL <- rbind(merged_test,merged_train) #(step 2) Extracts only the measurements on the mean and standard deviation for each measurement mean_std<-(grepl("activity_name",colnames(merged_test))| grepl("subject_label",colnames(merged_test))| grepl("mean",colnames(merged_test))| grepl("std",colnames(merged_test))) merged_ALL<-merged_ALL[,mean_std==TRUE] #(step 5)a second, independent tidy data set with the average of each variable for each activity and each subject. tidy <- aggregate(. ~subject_label + activity_name, merged_ALL, mean) tidySet <- tidy[order(tidy$subject_label, tidy$activity_name),] #export to txt file write.table(tidySet, "tidySet.txt", row.name=FALSE)
/run_analysis.R
no_license
Isabelgium/Getting_and_Cleaning_Data_Course_Project
R
false
false
2,082
r
library(dplyr) library(plyr) #The order of the steps are different than the task #reading files (includes also step 4) features<- read.table("features.txt") #import features activity_labels<-read.table("activity_labels.txt",col.names = c("label","activity_name")) #import activity_labels test_X<- read.table("test/X_test.txt",col.names = as.vector(features[[2]])) #import test_X_test add column names test_y<- read.table("test/y_test.txt",col.names= "label") #import test_y_test subject_test <- read.table("test/subject_test.txt",col.names="subject_label") # import subjet train train_X<- read.table("train/X_train.txt",col.names = as.vector(features[[2]])) #import train_X_test add column names train_y<- read.table("train/y_train.txt",col.names= "label") #import train_y_test subject_train <- read.table("train/subject_train.txt",col.names="subject_label") # import subjet train #(step 3) Change label to activity name in test_y and train_Y test_y_activity<- join(test_y,activity_labels)[-1] #test_y with activity names in stead of labels train_y_activity<- join(train_y,activity_labels)[-1] #train_y with activity names in stead of labels #(step 1) merge test and train sets merged_test <- cbind(test_y_activity,subject_test,test_X) merged_train <- cbind(train_y_activity,subject_train,train_X) merged_ALL <- rbind(merged_test,merged_train) #(step 2) Extracts only the measurements on the mean and standard deviation for each measurement mean_std<-(grepl("activity_name",colnames(merged_test))| grepl("subject_label",colnames(merged_test))| grepl("mean",colnames(merged_test))| grepl("std",colnames(merged_test))) merged_ALL<-merged_ALL[,mean_std==TRUE] #(step 5)a second, independent tidy data set with the average of each variable for each activity and each subject. tidy <- aggregate(. ~subject_label + activity_name, merged_ALL, mean) tidySet <- tidy[order(tidy$subject_label, tidy$activity_name),] #export to txt file write.table(tidySet, "tidySet.txt", row.name=FALSE)
# Module UI #' @title mod_left_ui and mod_left_server #' @description A shiny Module. #' #' @param id shiny id #' @param input internal #' @param output internal #' @param session internal #' #' @rdname mod_left #' #' @keywords internal #' @export #' @importFrom shiny NS tagList #' @import magrittr mod_left_ui <- function(id){ ns <- NS(id) tagList( tags$div( class = "rounded", h2("Build your own hex sticker"), tags$details( tags$summary("Manage Package name"), tags$div( class = "innerrounded rounded", fluidRow( col_12( textInput( ns("package"), "Package name", value = "hexmake" ) ), col_6( numericInput( ns("p_x"), "x position for package name", value = 1, step = 0.1 ) ), col_6( numericInput( ns("p_y"), "y position for package name", value = 1.4, step = 0.1 ) ), col_6( tags$label( `for` = "p_color", "Font color for package name" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("p_color"), value = "#FFFFFF", name = "p_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("p_color") ) ) ), col_6( selectInput( ns("p_family"), "Font family for package name", selected = sysfonts::font_families()[1], choices = sysfonts::font_families() ) ), col_6( numericInput( ns("p_size"), "Font size for package name", value = 8, step = 0.1 ) ) ) ) ), tags$details( tags$summary("Manage image"), tags$div( class = "innerrounded rounded", fluidRow( col_6( fileInput(ns("file"), "Upload a file") ), col_6( HTML("&nbsp;") ) ), fluidRow( col_6( numericInput( ns("s_x"), "x position for image", value = 1, step = 0.1 ) ), col_6( numericInput( ns("s_y"), "y position for image", value = 0.7, step = 0.1 ) ), col_6( numericInput( ns("s_width"), "Width for image", value = 0.4, step = 0.1 ) ), col_6( numericInput( ns("s_height"), "Height for image", value = 1, step = 0.1 ) ) ) ) ), tags$details( tags$summary("Manage Hexagon"), tags$div( class = "innerrounded rounded", fluidRow( col_6( numericInput( ns("h_size"), "Size for hexagon border", value = 1.2, step = 0.1 ) ), col_6( tags$label( `for` = "p_color", "Color to fill hexagon" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("h_fill"), value = "#1881C2", name = "p_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("h_fill") ) ) ), col_6( tags$label( `for` = "h_color", "Color for hexagon border" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("h_color"), value = "#87B13F", name = "p_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("h_color") ) ) ) ) ) ), tags$details( tags$summary("Manage Spotlight"), tags$div( class = "innerrounded rounded", fluidRow( col_6( checkboxInput( ns("spotlight"), "Add spotlight", value = FALSE ) ), col_6( numericInput( ns("l_x"), "x position for spotlight", value = 1, step = 0.1 ) ), col_6( numericInput( ns("l_y"), "y position for spotlight", value = 0.5, step = 0.1 ) ), col_6( numericInput( ns("l_width"), "width for spotlight", value = 3, step = 0.1 ) ), col_6( numericInput( ns("l_height"), "height for spotlight", value = 3, step = 0.1 ) ), col_6( numericInput( ns("l_alpha"), "maximum alpha for spotlight", value = 0.4, step = 0.1 ) ) ) ) ), tags$details( tags$summary("Manage URL"), tags$div( class = "innerrounded rounded", fluidRow( col_6( textInput( ns("url"), "url at lower border", value = "" ) ), col_6( numericInput( ns("u_x"), "x position for url", value = 1, step = 0.1 ) ), col_6( numericInput( ns("u_y"), "y position for url", value = 0.08, step = 0.1 ) ), col_6( tags$label( `for` = "u_color", "Color for url" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("u_color"), value = "#000000", name = "u_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("u_color") ) ) ), col_6( selectInput( ns("u_family"), "Font family for url", selected = sysfonts::font_families()[1], choices = sysfonts::font_families() ) ), col_6( numericInput( ns("u_size"), "Text size for url", value = 1.5, step = 0.1 ) ), col_6( numericInput( ns("u_angle"), "Angle for url", value = 30, step = 1 ) ) ) ) ), tags$details( tags$summary("Rendering mode"), tags$div( class = "innerrounded rounded", align = "center", fluidRow( tags$div( align = "center", col_4( checkboxInput( ns("live"), "Live preview", value = TRUE ) ) ), tags$div( align = "right", col_4( actionButton( ns("render"), "Manual render", icon = icon("arrow-right"), `disabled` = "disable" ) ) ) ) ) ), tags$details( tags$summary("Download the hex"), tags$div( class = "innerrounded rounded", align = "center", fluidRow( col_12( downloadButton( ns("dl"), "Download the Hex" ) ) ) ) ), tags$details( tags$summary("About"), tags$div( class = "innerrounded rounded", align = "center", mod_about_ui(ns("about_ui_1")) ) ) ) ) } # Module Server #' @rdname mod_left #' @export #' @keywords internal mod_left_server <- function(input, output, session, img){ ns <- session$ns lapply( c( "package", "p_x", "p_y", "p_color", "p_family", "p_size", "s_x", "s_y", "s_width", "s_height", "h_size", "h_fill", "h_color", "spotlight", "l_x", "l_y", "l_width", "l_height", "l_alpha", "url", "u_x", "u_y", "u_color", "u_family", "u_size", "u_angle" ), function(x){ observeEvent( input[[x]] , { img[[x]] <- input[[x]] if (input$live) trigger("render") }) } ) observeEvent( input$file , { img$subplot <- input$file$datapath if (input$live) trigger("render") }) observeEvent( input$render , { trigger("render") }) output$dl <- downloadHandler( filename = function() { paste('hex-', img$package, '.png', sep='') }, content = function(con) { img$render(con) } ) observeEvent( input$live , { if (input$live){ golem::invoke_js("disable", sprintf("#%s", ns("render"))) } else { golem::invoke_js("reable", sprintf("#%s", ns("render"))) } }) callModule(mod_about_server, "about_ui_1") }
/R/mod_left.R
permissive
fxcebx/hexmake
R
false
false
11,208
r
# Module UI #' @title mod_left_ui and mod_left_server #' @description A shiny Module. #' #' @param id shiny id #' @param input internal #' @param output internal #' @param session internal #' #' @rdname mod_left #' #' @keywords internal #' @export #' @importFrom shiny NS tagList #' @import magrittr mod_left_ui <- function(id){ ns <- NS(id) tagList( tags$div( class = "rounded", h2("Build your own hex sticker"), tags$details( tags$summary("Manage Package name"), tags$div( class = "innerrounded rounded", fluidRow( col_12( textInput( ns("package"), "Package name", value = "hexmake" ) ), col_6( numericInput( ns("p_x"), "x position for package name", value = 1, step = 0.1 ) ), col_6( numericInput( ns("p_y"), "y position for package name", value = 1.4, step = 0.1 ) ), col_6( tags$label( `for` = "p_color", "Font color for package name" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("p_color"), value = "#FFFFFF", name = "p_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("p_color") ) ) ), col_6( selectInput( ns("p_family"), "Font family for package name", selected = sysfonts::font_families()[1], choices = sysfonts::font_families() ) ), col_6( numericInput( ns("p_size"), "Font size for package name", value = 8, step = 0.1 ) ) ) ) ), tags$details( tags$summary("Manage image"), tags$div( class = "innerrounded rounded", fluidRow( col_6( fileInput(ns("file"), "Upload a file") ), col_6( HTML("&nbsp;") ) ), fluidRow( col_6( numericInput( ns("s_x"), "x position for image", value = 1, step = 0.1 ) ), col_6( numericInput( ns("s_y"), "y position for image", value = 0.7, step = 0.1 ) ), col_6( numericInput( ns("s_width"), "Width for image", value = 0.4, step = 0.1 ) ), col_6( numericInput( ns("s_height"), "Height for image", value = 1, step = 0.1 ) ) ) ) ), tags$details( tags$summary("Manage Hexagon"), tags$div( class = "innerrounded rounded", fluidRow( col_6( numericInput( ns("h_size"), "Size for hexagon border", value = 1.2, step = 0.1 ) ), col_6( tags$label( `for` = "p_color", "Color to fill hexagon" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("h_fill"), value = "#1881C2", name = "p_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("h_fill") ) ) ), col_6( tags$label( `for` = "h_color", "Color for hexagon border" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("h_color"), value = "#87B13F", name = "p_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("h_color") ) ) ) ) ) ), tags$details( tags$summary("Manage Spotlight"), tags$div( class = "innerrounded rounded", fluidRow( col_6( checkboxInput( ns("spotlight"), "Add spotlight", value = FALSE ) ), col_6( numericInput( ns("l_x"), "x position for spotlight", value = 1, step = 0.1 ) ), col_6( numericInput( ns("l_y"), "y position for spotlight", value = 0.5, step = 0.1 ) ), col_6( numericInput( ns("l_width"), "width for spotlight", value = 3, step = 0.1 ) ), col_6( numericInput( ns("l_height"), "height for spotlight", value = 3, step = 0.1 ) ), col_6( numericInput( ns("l_alpha"), "maximum alpha for spotlight", value = 0.4, step = 0.1 ) ) ) ) ), tags$details( tags$summary("Manage URL"), tags$div( class = "innerrounded rounded", fluidRow( col_6( textInput( ns("url"), "url at lower border", value = "" ) ), col_6( numericInput( ns("u_x"), "x position for url", value = 1, step = 0.1 ) ), col_6( numericInput( ns("u_y"), "y position for url", value = 0.08, step = 0.1 ) ), col_6( tags$label( `for` = "u_color", "Color for url" ), tags$br(), tags$input( tags$br(), type = "color", id = ns("u_color"), value = "#000000", name = "u_color" ) %>% tagAppendAttributes( onInput = sprintf( "Shiny.setInputValue('%s', event.target.value)", ns("u_color") ) ) ), col_6( selectInput( ns("u_family"), "Font family for url", selected = sysfonts::font_families()[1], choices = sysfonts::font_families() ) ), col_6( numericInput( ns("u_size"), "Text size for url", value = 1.5, step = 0.1 ) ), col_6( numericInput( ns("u_angle"), "Angle for url", value = 30, step = 1 ) ) ) ) ), tags$details( tags$summary("Rendering mode"), tags$div( class = "innerrounded rounded", align = "center", fluidRow( tags$div( align = "center", col_4( checkboxInput( ns("live"), "Live preview", value = TRUE ) ) ), tags$div( align = "right", col_4( actionButton( ns("render"), "Manual render", icon = icon("arrow-right"), `disabled` = "disable" ) ) ) ) ) ), tags$details( tags$summary("Download the hex"), tags$div( class = "innerrounded rounded", align = "center", fluidRow( col_12( downloadButton( ns("dl"), "Download the Hex" ) ) ) ) ), tags$details( tags$summary("About"), tags$div( class = "innerrounded rounded", align = "center", mod_about_ui(ns("about_ui_1")) ) ) ) ) } # Module Server #' @rdname mod_left #' @export #' @keywords internal mod_left_server <- function(input, output, session, img){ ns <- session$ns lapply( c( "package", "p_x", "p_y", "p_color", "p_family", "p_size", "s_x", "s_y", "s_width", "s_height", "h_size", "h_fill", "h_color", "spotlight", "l_x", "l_y", "l_width", "l_height", "l_alpha", "url", "u_x", "u_y", "u_color", "u_family", "u_size", "u_angle" ), function(x){ observeEvent( input[[x]] , { img[[x]] <- input[[x]] if (input$live) trigger("render") }) } ) observeEvent( input$file , { img$subplot <- input$file$datapath if (input$live) trigger("render") }) observeEvent( input$render , { trigger("render") }) output$dl <- downloadHandler( filename = function() { paste('hex-', img$package, '.png', sep='') }, content = function(con) { img$render(con) } ) observeEvent( input$live , { if (input$live){ golem::invoke_js("disable", sprintf("#%s", ns("render"))) } else { golem::invoke_js("reable", sprintf("#%s", ns("render"))) } }) callModule(mod_about_server, "about_ui_1") }
setwd('C:/Users/paart/Desktop') #data data and assigning data matrix discover = read.csv('replc_top1000_nonnull_2.csv', row.names = 1) discover = read.csv('top 86.csv', row.names = 1) tdiscover = as.data.frame(t(discover)) tdisc=as.data.frame(tdiscover[,14:ncol(tdiscover)]) #convert to numeric tdisc[] <- lapply(tdisc, function(x) { as.double(as.character(x))}) #Plotting PCA library(ggfortify) tdiscover = as.data.frame(t(discover)) colnames(tdiscover)[1]="separator" #choose required column number for having colour codes autoplot(prcomp(tdisc, center=TRUE, scale. = TRUE), data = tdiscover, colour = "separator") autoplot(prcomp(tdisc, center=FALSE, scale. = FALSE), data = tdiscover, colour = "separator")
/PCA_Analysis.R
no_license
PaarthParekh/HIV_Smokers
R
false
false
734
r
setwd('C:/Users/paart/Desktop') #data data and assigning data matrix discover = read.csv('replc_top1000_nonnull_2.csv', row.names = 1) discover = read.csv('top 86.csv', row.names = 1) tdiscover = as.data.frame(t(discover)) tdisc=as.data.frame(tdiscover[,14:ncol(tdiscover)]) #convert to numeric tdisc[] <- lapply(tdisc, function(x) { as.double(as.character(x))}) #Plotting PCA library(ggfortify) tdiscover = as.data.frame(t(discover)) colnames(tdiscover)[1]="separator" #choose required column number for having colour codes autoplot(prcomp(tdisc, center=TRUE, scale. = TRUE), data = tdiscover, colour = "separator") autoplot(prcomp(tdisc, center=FALSE, scale. = FALSE), data = tdiscover, colour = "separator")
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/STATSVD.R \name{vector_sum_square} \alias{vector_sum_square} \title{Calculate the Square of l2 norm of a vector.} \usage{ vector_sum_square(x) } \arguments{ \item{x}{Input vector.} } \value{ Square of l2 norm of a vector. } \description{ Calculate the Square of l2 norm of a vector. }
/man/vector_sum_square.Rd
no_license
Rungang/STATSVD
R
false
true
363
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/STATSVD.R \name{vector_sum_square} \alias{vector_sum_square} \title{Calculate the Square of l2 norm of a vector.} \usage{ vector_sum_square(x) } \arguments{ \item{x}{Input vector.} } \value{ Square of l2 norm of a vector. } \description{ Calculate the Square of l2 norm of a vector. }
# ====================== Step 3: Data Preparation ====================== # 3a. Analyze Attributes: Check properties of data # 3b. Complete Data Perform missing value analysis and Impute if needed # 3c. Correct Data: Check for any invalid data points # 3d. Create Derived Attributes - Feature Extraction # 3e. Convert - Converting data to proper formats # 3a. Analyze Attributes: Check properties of data dim(bike) str(bike) head(bike, 10) # 3a -> Inference: #i. The dataset has 10,886 observations (n=10886) and 12 columns of type int, num and factor. #ii. Season, Holiday, Working day and weather are categorical variables. #ii. temp, atemp, humidity, windspeed, casual, registered and count are continuous numerical variables. # 3b. Complete Data Perform missing value analysis and Impute if needed table(is.na(bike)) # 3b -> Inference: There are no null values in the dataset. If it had, then either the rows/columns had to be # dropped or the null values be imputed based on the % of null values # 3c. Correct Data: Check for any invalid data points # From above observations data doesnot seem to have any invalid datatypes to be handled. # Let's check for the outliers in EDA step # 3d. Create Derived Attributes - Feature Extraction # Lets extract 'date','month','weekday' and 'year' from 'datetime' column as we will be needing it for analysis bike$date=as.factor(day(bike$datetime)) bike$year = as.factor(year(bike$datetime)) bike$month = as.factor(month(bike$datetime)) bike$hour = as.factor(hour(bike$datetime)) bike$wkday = as.factor(wday(bike$datetime)) bike_test$date=as.factor(day(bike_test$datetime)) bike_test$year = as.factor(year(bike_test$datetime)) bike_test$month = as.factor(month(bike_test$datetime)) bike_test$hour = as.factor(hour(bike_test$datetime)) bike_test$wkday = as.factor(wday(bike_test$datetime)) # Drop datetime as we have extracted all the above needed information from it bike = bike[-c(1)] bike_test = bike_test[-c(1)] head(bike, 5) head(bike_test, 5) # 3d -> Inference: There are no null values in the dataset. If it had, then either the rows/columns had to be #dropped or the null values be imputed based on the % of null values. # 3e. Convert - Converting data to proper formats # We can clearly see that "season", "holiday", "workingday" and"weather" are categories rather than continous variable. # Let's convert them to categories names = c("season", "holiday", "workingday", "weather") bike[,names] = lapply(bike[,names], factor) bike_test[,names] = lapply(bike_test[,names], factor) str(bike) str(bike_test) # ====================== Step 3: Data Preparation ends here ======================
/code/Data_Preparation.r
no_license
chiraghbhansali/DPA_Bike_share_demand
R
false
false
2,902
r
# ====================== Step 3: Data Preparation ====================== # 3a. Analyze Attributes: Check properties of data # 3b. Complete Data Perform missing value analysis and Impute if needed # 3c. Correct Data: Check for any invalid data points # 3d. Create Derived Attributes - Feature Extraction # 3e. Convert - Converting data to proper formats # 3a. Analyze Attributes: Check properties of data dim(bike) str(bike) head(bike, 10) # 3a -> Inference: #i. The dataset has 10,886 observations (n=10886) and 12 columns of type int, num and factor. #ii. Season, Holiday, Working day and weather are categorical variables. #ii. temp, atemp, humidity, windspeed, casual, registered and count are continuous numerical variables. # 3b. Complete Data Perform missing value analysis and Impute if needed table(is.na(bike)) # 3b -> Inference: There are no null values in the dataset. If it had, then either the rows/columns had to be # dropped or the null values be imputed based on the % of null values # 3c. Correct Data: Check for any invalid data points # From above observations data doesnot seem to have any invalid datatypes to be handled. # Let's check for the outliers in EDA step # 3d. Create Derived Attributes - Feature Extraction # Lets extract 'date','month','weekday' and 'year' from 'datetime' column as we will be needing it for analysis bike$date=as.factor(day(bike$datetime)) bike$year = as.factor(year(bike$datetime)) bike$month = as.factor(month(bike$datetime)) bike$hour = as.factor(hour(bike$datetime)) bike$wkday = as.factor(wday(bike$datetime)) bike_test$date=as.factor(day(bike_test$datetime)) bike_test$year = as.factor(year(bike_test$datetime)) bike_test$month = as.factor(month(bike_test$datetime)) bike_test$hour = as.factor(hour(bike_test$datetime)) bike_test$wkday = as.factor(wday(bike_test$datetime)) # Drop datetime as we have extracted all the above needed information from it bike = bike[-c(1)] bike_test = bike_test[-c(1)] head(bike, 5) head(bike_test, 5) # 3d -> Inference: There are no null values in the dataset. If it had, then either the rows/columns had to be #dropped or the null values be imputed based on the % of null values. # 3e. Convert - Converting data to proper formats # We can clearly see that "season", "holiday", "workingday" and"weather" are categories rather than continous variable. # Let's convert them to categories names = c("season", "holiday", "workingday", "weather") bike[,names] = lapply(bike[,names], factor) bike_test[,names] = lapply(bike_test[,names], factor) str(bike) str(bike_test) # ====================== Step 3: Data Preparation ends here ======================
library(streamR) library(twitteR) library(ROAuth) library(jsonlite) library(devtools) loadAuth <- function() { if(file.exists("F:/Projects/streamingtwitterapp/my_oauth.Rdata")) { #oauth_file<-file.path("F:/Projects/streamingtwitterapp", "my_oauth.Rdata") load("F:/Projects/streamingtwitterapp/my_oauth.Rdata") } else { cat("my_oauth doesnt exist... creating") install_github("streamR", "pablobarbera", subdir = "streamR") requestURL <- "https://api.twitter.com/oauth/request_token" accessURL <- "https://api.twitter.com/oauth/access_token" authURL <- "https://api.twitter.com/oauth/authorize" consumerKey <- "ax4TCkpNczz2gGZCQPzlTieZ1" consumerSecret <- "t6anJn4xZHfkNGubGDqh5CrWUJW9pXT9rqNvTd1Rao0twux6pg" my_oauth <- OAuthFactory$new(consumerKey = consumerKey, consumerSecret = consumerSecret, requestURL = requestURL, accessURL = accessURL, authURL = authURL) my_oauth$handshake(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl"))+ save(my_oauth, file = "my_oauth.Rdata") load("F:/Projects/streamingtwitterapp/my_oauth.Rdata") } } # clean text function clean.text <- function(some_txt) { some_txt = gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", some_txt) some_txt = gsub("@\\w+", "", some_txt) some_txt = gsub("[[:punct:]]", "", some_txt) some_txt = gsub("[[:digit:]]", "", some_txt) some_txt = gsub("http\\w+", "", some_txt) some_txt = gsub("[ \t]{2,}", "", some_txt) some_txt = gsub("^\\s+|\\s+$", "", some_txt) # Remove non-english characters some_txt = gsub("[^\x20-\x7E]", "", some_txt) # define "tolower error handling" function try.tolower = function(x) { y = NA try_error = tryCatch(tolower(x), error=function(e) e) if (!inherits(try_error, "error")) y = tolower(x) return(y) } some_txt = sapply(some_txt, try.tolower) some_txt = some_txt[some_txt != ""] names(some_txt) = NULL return(some_txt) } #readFile <- function() { # if(file.exists("F:/Projects/streamingtwitterapp/tweets.json")) # tweets <<- parseTweets("F:/Projects/streamingtwitterapp/tweets.json") #}
/UB DIC Projects/Project1_R Data Analytics/Streaming Tweets and Extended Analysis/streamingtwitterapp/helpers.R
no_license
aniket898/UBProjects
R
false
false
2,164
r
library(streamR) library(twitteR) library(ROAuth) library(jsonlite) library(devtools) loadAuth <- function() { if(file.exists("F:/Projects/streamingtwitterapp/my_oauth.Rdata")) { #oauth_file<-file.path("F:/Projects/streamingtwitterapp", "my_oauth.Rdata") load("F:/Projects/streamingtwitterapp/my_oauth.Rdata") } else { cat("my_oauth doesnt exist... creating") install_github("streamR", "pablobarbera", subdir = "streamR") requestURL <- "https://api.twitter.com/oauth/request_token" accessURL <- "https://api.twitter.com/oauth/access_token" authURL <- "https://api.twitter.com/oauth/authorize" consumerKey <- "ax4TCkpNczz2gGZCQPzlTieZ1" consumerSecret <- "t6anJn4xZHfkNGubGDqh5CrWUJW9pXT9rqNvTd1Rao0twux6pg" my_oauth <- OAuthFactory$new(consumerKey = consumerKey, consumerSecret = consumerSecret, requestURL = requestURL, accessURL = accessURL, authURL = authURL) my_oauth$handshake(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl"))+ save(my_oauth, file = "my_oauth.Rdata") load("F:/Projects/streamingtwitterapp/my_oauth.Rdata") } } # clean text function clean.text <- function(some_txt) { some_txt = gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", some_txt) some_txt = gsub("@\\w+", "", some_txt) some_txt = gsub("[[:punct:]]", "", some_txt) some_txt = gsub("[[:digit:]]", "", some_txt) some_txt = gsub("http\\w+", "", some_txt) some_txt = gsub("[ \t]{2,}", "", some_txt) some_txt = gsub("^\\s+|\\s+$", "", some_txt) # Remove non-english characters some_txt = gsub("[^\x20-\x7E]", "", some_txt) # define "tolower error handling" function try.tolower = function(x) { y = NA try_error = tryCatch(tolower(x), error=function(e) e) if (!inherits(try_error, "error")) y = tolower(x) return(y) } some_txt = sapply(some_txt, try.tolower) some_txt = some_txt[some_txt != ""] names(some_txt) = NULL return(some_txt) } #readFile <- function() { # if(file.exists("F:/Projects/streamingtwitterapp/tweets.json")) # tweets <<- parseTweets("F:/Projects/streamingtwitterapp/tweets.json") #}
stripComments <- function(content) { gsub("#.*", "", content, perl = TRUE) } hasAbsolutePaths <- function(content) { regex <- c( "[\'\"]\\s*[a-zA-Z]:/[^\"\']", ## windows-style absolute paths "[\'\"]\\s*\\\\\\\\", ## windows UNC paths "[\'\"]\\s*/(?!/)(.*?)/(.*?)", ## unix-style absolute paths "[\'\"]\\s*~/", ## path to home directory "\\[(.*?)\\]\\(\\s*[a-zA-Z]:/[^\"\']", ## windows-style markdown references [Some image](C:/...) "\\[(.*?)\\]\\(\\s*/", ## unix-style markdown references [Some image](/Users/...) NULL ## so we don't worry about commas above ) results <- as.logical(Reduce(`+`, lapply(regex, function(rex) { grepl(rex, content, perl = TRUE) }))) } noMatch <- function(x) { identical(attr(x, "match.length"), -1L) } badRelativePaths <- function(content, project, path) { ## Figure out how deeply the path of the file is nested ## (it is relative to the project root) slashMatches <- gregexpr("/", path) nestLevel <- if (noMatch(slashMatches)) 0 else length(slashMatches[[1]]) ## Identify occurrences of "../" regexResults <- gregexpr("../", content, fixed = TRUE) ## Figure out sequential runs of `../` runs <- lapply(regexResults, function(x) { if (noMatch(x)) return(NULL) rle <- rle(as.integer(x) - seq(0, by = 3, length.out = length(x))) rle$lengths }) badPaths <- vapply(runs, function(x) { any(x > nestLevel) }, logical(1)) badPaths } enumerate <- function(X, FUN, ...) { FUN <- match.fun(FUN) result <- vector("list", length(X)) for (i in seq_along(X)) { result[[i]] <- FUN(X[[i]], i, ...) } names(result) <- names(X) result } #' Construct a Linter Message #' #' Pretty-prints a linter message. Primarily used as a helper #' for constructing linter messages with \code{\link{linter}}. #' #' @param header A header message describing the linter. #' @param content The content of the file that was linted. #' @param lines The line numbers from \code{content} that contain lint. makeLinterMessage <- function(header, content, lines) { c( paste0(header, ":"), paste(lines, ": ", content[lines], sep = ""), "\n" ) } hasLint <- function(x) { any(unlist(lapply(x, function(x) { lapply(x, function(x) { length(x$indices) > 0 }) }))) } isRCodeFile <- function(path) { grepl("\\.[rR]$|\\.[rR]md$|\\.[rR]nw$", path) }
/R/lint-utils.R
no_license
jimhester/shinyapps
R
false
false
2,394
r
stripComments <- function(content) { gsub("#.*", "", content, perl = TRUE) } hasAbsolutePaths <- function(content) { regex <- c( "[\'\"]\\s*[a-zA-Z]:/[^\"\']", ## windows-style absolute paths "[\'\"]\\s*\\\\\\\\", ## windows UNC paths "[\'\"]\\s*/(?!/)(.*?)/(.*?)", ## unix-style absolute paths "[\'\"]\\s*~/", ## path to home directory "\\[(.*?)\\]\\(\\s*[a-zA-Z]:/[^\"\']", ## windows-style markdown references [Some image](C:/...) "\\[(.*?)\\]\\(\\s*/", ## unix-style markdown references [Some image](/Users/...) NULL ## so we don't worry about commas above ) results <- as.logical(Reduce(`+`, lapply(regex, function(rex) { grepl(rex, content, perl = TRUE) }))) } noMatch <- function(x) { identical(attr(x, "match.length"), -1L) } badRelativePaths <- function(content, project, path) { ## Figure out how deeply the path of the file is nested ## (it is relative to the project root) slashMatches <- gregexpr("/", path) nestLevel <- if (noMatch(slashMatches)) 0 else length(slashMatches[[1]]) ## Identify occurrences of "../" regexResults <- gregexpr("../", content, fixed = TRUE) ## Figure out sequential runs of `../` runs <- lapply(regexResults, function(x) { if (noMatch(x)) return(NULL) rle <- rle(as.integer(x) - seq(0, by = 3, length.out = length(x))) rle$lengths }) badPaths <- vapply(runs, function(x) { any(x > nestLevel) }, logical(1)) badPaths } enumerate <- function(X, FUN, ...) { FUN <- match.fun(FUN) result <- vector("list", length(X)) for (i in seq_along(X)) { result[[i]] <- FUN(X[[i]], i, ...) } names(result) <- names(X) result } #' Construct a Linter Message #' #' Pretty-prints a linter message. Primarily used as a helper #' for constructing linter messages with \code{\link{linter}}. #' #' @param header A header message describing the linter. #' @param content The content of the file that was linted. #' @param lines The line numbers from \code{content} that contain lint. makeLinterMessage <- function(header, content, lines) { c( paste0(header, ":"), paste(lines, ": ", content[lines], sep = ""), "\n" ) } hasLint <- function(x) { any(unlist(lapply(x, function(x) { lapply(x, function(x) { length(x$indices) > 0 }) }))) } isRCodeFile <- function(path) { grepl("\\.[rR]$|\\.[rR]md$|\\.[rR]nw$", path) }
## Below are two functions that are used to create a special object that stores ##a matrix and cache's its inverse matrix ## This function creates a special "matrix" object that can cache its inverse makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { x <<- y m <<- NULL } get <- function() x setinverse <- function(inverse) m <<- inverse getinverse <- function() m list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## 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, ...) { m <- x$getinverse() ## Return a matrix that is the inverse of 'x' if(!is.null(m)) { message("getting cached data") return(m) } matr <- x$get() m <- solve(matr, ...) x$setinverse(m) m }
/cachematrix.R
no_license
PostoronnimV/ProgrammingAssignment2
R
false
false
1,034
r
## Below are two functions that are used to create a special object that stores ##a matrix and cache's its inverse matrix ## This function creates a special "matrix" object that can cache its inverse makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { x <<- y m <<- NULL } get <- function() x setinverse <- function(inverse) m <<- inverse getinverse <- function() m list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## 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, ...) { m <- x$getinverse() ## Return a matrix that is the inverse of 'x' if(!is.null(m)) { message("getting cached data") return(m) } matr <- x$get() m <- solve(matr, ...) x$setinverse(m) m }
# Plik proszę nazwać numerem swojego indeksu. # Plik powinien zawierać tylko definicję funkcji z Zadanie 1-3. # # Zadanie 0: # a) Stwórz macierz rozmiaru "1000x1001". # Przypisz nazwę "Y" do pierwszej kolumny. Przypisz nazwy od "x_1" do "x_1000" do następnych kolumn. # b) Wstaw losowe wartości z wektora od 1 do 100 w kolumnę "Y". set.seed = (555). # c) Wstaw do kolumn od "x_1" do "x_1000" wartości zgodne z nastepujacym schematem # "x_i = Y + wartość losowa z rozkładu normalnego". set.seed = (555). # # Zadanie 1: # a) Stwórz funkcję przyjmującą nastęujące parametry: "dane", "Ynazwa", "XnazwyList", "Nrdzeni", "metoda". # b) Funkcja operując na zbiorze "dane" powinna tworzyć model regresji liniowej dla Ynazwa w odniesieniu do zmiennych XnazwyList. # W najprostszej postaci dla danych z "Zadanie 0" są to modele: ("Y~x1", "Y~x2", "Y~x3" etc.). # To jakiej postaci model powinien być zbudowany, definiowane jest przez parametr "XnazwyList", przyjmujący obiekt typu lista. # Lista ma tyle elementów, ile modeli będzie zbudowanych. Każdy element listy jest wektorem nazw zmiennych "x". # Przykład: "list(x1,c(x1,x5,x7))" buduje dwa modele 1) "Y~x1" oraz 2) "Y~x1+x5+x7". # c) Funkcja powinna budować każdą kombinację modeli równolegle. # d) W zależności od przekazanego argumentu do "metoda", funkcja wykorzystywać powinna albo równoleglą wersję "lapply", # albo równoleglą wersję pętli "for". # e) Każda równoległa pętla powinna zwracać informacje o nazwach zmiennej/zmiennych (pierwsza kolumna tekstowa) # i oszacowaniach parametrów (druga kolumna numeryczna). # f) Funkja powinna zwracać wyniki w formie listy. # g) Nazwa funkcji to "ModelParallel". # # Zadanie 2: # a) Stwórz funkcję "ModelOcena" przyjmującą nastęujące parametry: "y_tar" (rzeczywista), "y_hat" (prognoza). # b) Funkcja w pierwszym kroku powinna rozpoznawać czy mamy do czynienia z problemem regresji czy klasyfikacji. # y_tar: regresja -> numeric, klasyfikacja -> factor. # c) W zależności od problemu funkcja szacować powinna różnego rodzaju błędy: # Regresja: MAE, MSE, MAPE. # Klasyfikacja: AUC (szacowanie metodą trapezów), macierz klasyfikacji (punkt odcięcia wyznaczany jest poprzez index Youdena), # Czułość, Specyficzność, Jakość. # d) Dla czytelności kodu, wszystkie miary powinny być liczone w oparciu o zewnętrzne funkcje (dowolne nazwy), # których definicje znajdować się powinny przed definicją funkcji "ModelOcena". # e) Funkja powinna zwracać wyniki w formie: # Regresja: nazwany wektor (MAE, MSE, MAPE) o trzech elementach. # Klasyfikacja: nazwana lista (Mat, J, Miary) o trzech elementach: # Mat = macierz klasyfikacji, w wierszach znajdują się wartości "y_tar" a w kolumnach wartości "y_hat", # nazwy wierszy i kolumn muszą być zgodne z dostępnymi etykietami klas. # J = wartość indexu Youdena, # Miary = nazwany wektor o elementach AUC, Czułość, Specyficzność, Jakość. # f) Funkcja będzie testowana tylko dla klasyfikacji binarnej i regresji. # # Zadanie 3: # a) Stwórz funkcję "CrossValidTune" przyjmującą nastęujące parametry: "dane", "kFold", "parTune", "seed". # W skrócie: funkcja powinna krosswalidacyjnie tunować parametry danego algorytu. # b) Funkcja powinna w pierwszym kroku stworzyć listę przechowującą informację, które obserwacje posłużą jako zbiór treningowy, # a które wejdą do zbioru walidacyjnego. Ilość elementów listy zdefiniowana jest przez parametr "kFold" (liczba podzbiorów walidacyjnych). # Każdy element listy jest wektorem o tej samej długości, równej nrow("dane"). # Każdy z wektorów zawiera albo liczbę 1 (obserwacja jest w zbiorze treningowym) albo 2 (obserwacja jest w zbiorze walidacyjnym). # Przykład: list( c(1,2,1,1), c(2,1,1,2) ) - oznacza, że mamy doczynienia z 2-krotną walidacją na zbiorze z 4 obserwacjami, # gdzie dla pierwszej iteracji tylko jeden element jest w podzbiorze walidacyjnym. # Losowanie rozpoczyna się od ustawienia ziarna na wartość "seed". # c) W kolejnym kroku funkcja powinna stworzyć ramkę danych, w której przechowywane będą wyniki oraz kombinacje parametrów. # Liczba wierszy i kolumn zależy od zagadnienia (klasyfikacja, regresja) oraz od liczby tunowanych parametrów "parTune" i "kFold": # Przykład: "parTune" = data.frame( a = c(1,2), b = c(1,1) ) - oznacza, że algorytm ma 2 parametry do tunowania, # Dla "kFold" = 2 oraz "parTune", kombinacja parametrów to data.frame( "kFold" = c(1,2,1,2), a = c(1,2), b = c(1,1) ). # Kolejne kolumny tabeli wynikowej powinny stanowić miary uzyskane dzięki funkcji "ModelOcena". # Regresja: MAEt, MSEt, MAPEt, MAEw, MSEw, MAPEw - ozanczają miary dla zbioru treningowego i walidacyjnego. # Finalnie tabele jest rozmiaru 4x9. # Klasyfikacja: AUCT, CzułośćT, SpecyficznośćT, JakośćT, AUCW, SpecyficznośćW, MAPEW, JakośćW - j.w. # Finalnie tabele jest rozmiaru 4x11. # d) W ostatnim kroku funkcja powinna budować w pętli model predykcyjny dla danej kombincaji parametrów i uzupełniać tabelę wynikową. # Z racji tego, że nie stworzyliśmy na razie żadnego algorytmu ta część powinna działać następująco: # Każda pętla tworzy dwa podzbiory zdefiniowane przez wektor znajdujący się w liście z pkt b) dla danej kombinacji. # Do kolumn z miarami jakości wstawiane są wartości równe 0. # e) Funkcja zwraca tabelę wynikową. rep (c(2,5),c(4,5))
/R_scripts/R_knn_Tree_SVM/Kody_z_zajec_R/Zaj2 TED/Zadania_2.R
no_license
Samox1/Python_Micro_Codes
R
false
false
5,711
r
# Plik proszę nazwać numerem swojego indeksu. # Plik powinien zawierać tylko definicję funkcji z Zadanie 1-3. # # Zadanie 0: # a) Stwórz macierz rozmiaru "1000x1001". # Przypisz nazwę "Y" do pierwszej kolumny. Przypisz nazwy od "x_1" do "x_1000" do następnych kolumn. # b) Wstaw losowe wartości z wektora od 1 do 100 w kolumnę "Y". set.seed = (555). # c) Wstaw do kolumn od "x_1" do "x_1000" wartości zgodne z nastepujacym schematem # "x_i = Y + wartość losowa z rozkładu normalnego". set.seed = (555). # # Zadanie 1: # a) Stwórz funkcję przyjmującą nastęujące parametry: "dane", "Ynazwa", "XnazwyList", "Nrdzeni", "metoda". # b) Funkcja operując na zbiorze "dane" powinna tworzyć model regresji liniowej dla Ynazwa w odniesieniu do zmiennych XnazwyList. # W najprostszej postaci dla danych z "Zadanie 0" są to modele: ("Y~x1", "Y~x2", "Y~x3" etc.). # To jakiej postaci model powinien być zbudowany, definiowane jest przez parametr "XnazwyList", przyjmujący obiekt typu lista. # Lista ma tyle elementów, ile modeli będzie zbudowanych. Każdy element listy jest wektorem nazw zmiennych "x". # Przykład: "list(x1,c(x1,x5,x7))" buduje dwa modele 1) "Y~x1" oraz 2) "Y~x1+x5+x7". # c) Funkcja powinna budować każdą kombinację modeli równolegle. # d) W zależności od przekazanego argumentu do "metoda", funkcja wykorzystywać powinna albo równoleglą wersję "lapply", # albo równoleglą wersję pętli "for". # e) Każda równoległa pętla powinna zwracać informacje o nazwach zmiennej/zmiennych (pierwsza kolumna tekstowa) # i oszacowaniach parametrów (druga kolumna numeryczna). # f) Funkja powinna zwracać wyniki w formie listy. # g) Nazwa funkcji to "ModelParallel". # # Zadanie 2: # a) Stwórz funkcję "ModelOcena" przyjmującą nastęujące parametry: "y_tar" (rzeczywista), "y_hat" (prognoza). # b) Funkcja w pierwszym kroku powinna rozpoznawać czy mamy do czynienia z problemem regresji czy klasyfikacji. # y_tar: regresja -> numeric, klasyfikacja -> factor. # c) W zależności od problemu funkcja szacować powinna różnego rodzaju błędy: # Regresja: MAE, MSE, MAPE. # Klasyfikacja: AUC (szacowanie metodą trapezów), macierz klasyfikacji (punkt odcięcia wyznaczany jest poprzez index Youdena), # Czułość, Specyficzność, Jakość. # d) Dla czytelności kodu, wszystkie miary powinny być liczone w oparciu o zewnętrzne funkcje (dowolne nazwy), # których definicje znajdować się powinny przed definicją funkcji "ModelOcena". # e) Funkja powinna zwracać wyniki w formie: # Regresja: nazwany wektor (MAE, MSE, MAPE) o trzech elementach. # Klasyfikacja: nazwana lista (Mat, J, Miary) o trzech elementach: # Mat = macierz klasyfikacji, w wierszach znajdują się wartości "y_tar" a w kolumnach wartości "y_hat", # nazwy wierszy i kolumn muszą być zgodne z dostępnymi etykietami klas. # J = wartość indexu Youdena, # Miary = nazwany wektor o elementach AUC, Czułość, Specyficzność, Jakość. # f) Funkcja będzie testowana tylko dla klasyfikacji binarnej i regresji. # # Zadanie 3: # a) Stwórz funkcję "CrossValidTune" przyjmującą nastęujące parametry: "dane", "kFold", "parTune", "seed". # W skrócie: funkcja powinna krosswalidacyjnie tunować parametry danego algorytu. # b) Funkcja powinna w pierwszym kroku stworzyć listę przechowującą informację, które obserwacje posłużą jako zbiór treningowy, # a które wejdą do zbioru walidacyjnego. Ilość elementów listy zdefiniowana jest przez parametr "kFold" (liczba podzbiorów walidacyjnych). # Każdy element listy jest wektorem o tej samej długości, równej nrow("dane"). # Każdy z wektorów zawiera albo liczbę 1 (obserwacja jest w zbiorze treningowym) albo 2 (obserwacja jest w zbiorze walidacyjnym). # Przykład: list( c(1,2,1,1), c(2,1,1,2) ) - oznacza, że mamy doczynienia z 2-krotną walidacją na zbiorze z 4 obserwacjami, # gdzie dla pierwszej iteracji tylko jeden element jest w podzbiorze walidacyjnym. # Losowanie rozpoczyna się od ustawienia ziarna na wartość "seed". # c) W kolejnym kroku funkcja powinna stworzyć ramkę danych, w której przechowywane będą wyniki oraz kombinacje parametrów. # Liczba wierszy i kolumn zależy od zagadnienia (klasyfikacja, regresja) oraz od liczby tunowanych parametrów "parTune" i "kFold": # Przykład: "parTune" = data.frame( a = c(1,2), b = c(1,1) ) - oznacza, że algorytm ma 2 parametry do tunowania, # Dla "kFold" = 2 oraz "parTune", kombinacja parametrów to data.frame( "kFold" = c(1,2,1,2), a = c(1,2), b = c(1,1) ). # Kolejne kolumny tabeli wynikowej powinny stanowić miary uzyskane dzięki funkcji "ModelOcena". # Regresja: MAEt, MSEt, MAPEt, MAEw, MSEw, MAPEw - ozanczają miary dla zbioru treningowego i walidacyjnego. # Finalnie tabele jest rozmiaru 4x9. # Klasyfikacja: AUCT, CzułośćT, SpecyficznośćT, JakośćT, AUCW, SpecyficznośćW, MAPEW, JakośćW - j.w. # Finalnie tabele jest rozmiaru 4x11. # d) W ostatnim kroku funkcja powinna budować w pętli model predykcyjny dla danej kombincaji parametrów i uzupełniać tabelę wynikową. # Z racji tego, że nie stworzyliśmy na razie żadnego algorytmu ta część powinna działać następująco: # Każda pętla tworzy dwa podzbiory zdefiniowane przez wektor znajdujący się w liście z pkt b) dla danej kombinacji. # Do kolumn z miarami jakości wstawiane są wartości równe 0. # e) Funkcja zwraca tabelę wynikową. rep (c(2,5),c(4,5))
# CollegeStudentsDatasets.R # Read the data. Do not change the following block url <- "CollegePlans.csv" Students <- read.csv(url, header=T, stringsAsFactors=FALSE) Students <- Students[order(-Students$ParentIncome), ] Students$CollegePlans <- as.numeric(Students$CollegePlans == "Plans to attend") formula <- CollegePlans ~ Gender + ParentIncome + IQ + ParentEncouragement # Set repeatable random seed. Do not change the following line set.seed(4) PartitionWrong <- function(dataSet, fractionOfTest = 0.3) { numberOfRows <- nrow(dataSet) numberOfTestRows <- fractionOfTest * numberOfRows testFlag <- 1:numberOfRows <= numberOfTestRows testingData <- dataSet[testFlag, ] trainingData <- dataSet[!testFlag, ] dataSetSplit <- list(trainingData=trainingData, testingData=testingData) return(dataSetSplit) } PartitionExact <- function(dataSet, fractionOfTest = 0.3) { # ********** Add code here return(dataSetSplit) } PartitionFast <- function(dataSet, fractionOfTest = 0.3) { # ********** Add code here return(dataSetSplit) }
/1 - Intro to Data Science/assignment_4/CollegeStudentsDatasets_template.R
no_license
jessie-jensen/uw_data_science_cert
R
false
false
1,051
r
# CollegeStudentsDatasets.R # Read the data. Do not change the following block url <- "CollegePlans.csv" Students <- read.csv(url, header=T, stringsAsFactors=FALSE) Students <- Students[order(-Students$ParentIncome), ] Students$CollegePlans <- as.numeric(Students$CollegePlans == "Plans to attend") formula <- CollegePlans ~ Gender + ParentIncome + IQ + ParentEncouragement # Set repeatable random seed. Do not change the following line set.seed(4) PartitionWrong <- function(dataSet, fractionOfTest = 0.3) { numberOfRows <- nrow(dataSet) numberOfTestRows <- fractionOfTest * numberOfRows testFlag <- 1:numberOfRows <= numberOfTestRows testingData <- dataSet[testFlag, ] trainingData <- dataSet[!testFlag, ] dataSetSplit <- list(trainingData=trainingData, testingData=testingData) return(dataSetSplit) } PartitionExact <- function(dataSet, fractionOfTest = 0.3) { # ********** Add code here return(dataSetSplit) } PartitionFast <- function(dataSet, fractionOfTest = 0.3) { # ********** Add code here return(dataSetSplit) }
goal_count_over_time <- function(namespace, date_begin = FALSE, date_end = FALSE){ if(date_begin == FALSE){ date_begin <- lubridate::floor_date(seq(from = Sys.Date(), by = '-1 year', length.out = 2)[2], unit = 'year') } else { date_begin <- as.Date(date_begin) } if(date_end == FALSE){ date_end <- lubridate::ceiling_date(seq(from = Sys.Date(), by = '-1 month', length.out = 2)[1], unit = 'month') - 1 } else { date_end <- as.Date(date_end) } goals %>% filter(table_id == namespace, when >= date_begin, when <= date_end, !goal_name %in% c('start_ios', 'start_android')) %>% select(key2, when, count) %>% mutate(date = as.Date(stringr::str_c(format(when, '%m'), '01', format(when, '%Y'), sep = '-'), format = '%m-%d-%Y')) %>% group_by(key2, date) %>% summarize(count = sum(count, na.rm = TRUE)) -> tmp_df_goals daily_counters %>% filter(table_id == namespace, date >= date_begin, date <= date_end) %>% select(key, campaign_type) %>% mutate(campaign_type = recode(campaign_type, 'adaptive' = 'Adaptive', 'auto' = 'Lifecycle', 'one_time' = 'One Time', 'trigger' = 'Conversion', 'immediate_trigger' = 'Conversion', 'program_message' = 'Experience')) %>% group_by(key, campaign_type) %>% unique() -> tmp_df_counters tmp_df_goals %>% left_join(tmp_df_counters, by = c("key2" = "key")) %>% select(-key2) %>% group_by(date, campaign_type) %>% summarize(count = sum(count)) %>% #mutate(campaign_type = forcats::fct_reorder(campaign_type, count)) %>% #arrange(desc(count)) %>% #mutate(rn = row_number()) %>% # goal_name2 = ifelse(rn %in% c(1:5), goal_name, 'other'), # rn_color = ifelse(rn == 1, '1', # ifelse(rn == 2, '2', # ifelse(rn == 3, '3', # ifelse(rn == 4, '4', # ifelse(rn == 5, '5', '6')))))) %>% ggplot(., aes(x = date, y = count, group = forcats::fct_reorder(campaign_type, count))) + geom_bar(aes(fill = campaign_type), stat = 'identity') + labs(x = '', y = '') + #geom_col(position = position_stack(reverse = FALSE), aes(fill = campaign_type)) + #geom_text(position = position_stack(vjust = .5, reverse = TRUE), size = 2, aes(label = campaign_type)) + scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") + scale_y_continuous(labels = scales::comma, breaks = pretty_breaks()) + scale_fill_manual(values = c("Adaptive" = "#28235e", "Lifecycle" = "#ae0a45ff", "One Time" = "#2a5191", "Conversion" = "#27ab7eff", "Experience" = "#66308dff"), na.value = "#999999ff") + theme_bw() + theme(axis.text.x = element_text(), plot.title = element_text(hjust = 0.5, size = 11), axis.title.x = element_text(size = 9), axis.title.y = element_text(size = 9), panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(), rect = element_blank(), line = element_blank(), legend.position = 'bottom', legend.direction = 'horizontal', legend.title = element_blank()) }
/functions/goal_count_over_time.R
no_license
blakeschiafone/qbr
R
false
false
3,720
r
goal_count_over_time <- function(namespace, date_begin = FALSE, date_end = FALSE){ if(date_begin == FALSE){ date_begin <- lubridate::floor_date(seq(from = Sys.Date(), by = '-1 year', length.out = 2)[2], unit = 'year') } else { date_begin <- as.Date(date_begin) } if(date_end == FALSE){ date_end <- lubridate::ceiling_date(seq(from = Sys.Date(), by = '-1 month', length.out = 2)[1], unit = 'month') - 1 } else { date_end <- as.Date(date_end) } goals %>% filter(table_id == namespace, when >= date_begin, when <= date_end, !goal_name %in% c('start_ios', 'start_android')) %>% select(key2, when, count) %>% mutate(date = as.Date(stringr::str_c(format(when, '%m'), '01', format(when, '%Y'), sep = '-'), format = '%m-%d-%Y')) %>% group_by(key2, date) %>% summarize(count = sum(count, na.rm = TRUE)) -> tmp_df_goals daily_counters %>% filter(table_id == namespace, date >= date_begin, date <= date_end) %>% select(key, campaign_type) %>% mutate(campaign_type = recode(campaign_type, 'adaptive' = 'Adaptive', 'auto' = 'Lifecycle', 'one_time' = 'One Time', 'trigger' = 'Conversion', 'immediate_trigger' = 'Conversion', 'program_message' = 'Experience')) %>% group_by(key, campaign_type) %>% unique() -> tmp_df_counters tmp_df_goals %>% left_join(tmp_df_counters, by = c("key2" = "key")) %>% select(-key2) %>% group_by(date, campaign_type) %>% summarize(count = sum(count)) %>% #mutate(campaign_type = forcats::fct_reorder(campaign_type, count)) %>% #arrange(desc(count)) %>% #mutate(rn = row_number()) %>% # goal_name2 = ifelse(rn %in% c(1:5), goal_name, 'other'), # rn_color = ifelse(rn == 1, '1', # ifelse(rn == 2, '2', # ifelse(rn == 3, '3', # ifelse(rn == 4, '4', # ifelse(rn == 5, '5', '6')))))) %>% ggplot(., aes(x = date, y = count, group = forcats::fct_reorder(campaign_type, count))) + geom_bar(aes(fill = campaign_type), stat = 'identity') + labs(x = '', y = '') + #geom_col(position = position_stack(reverse = FALSE), aes(fill = campaign_type)) + #geom_text(position = position_stack(vjust = .5, reverse = TRUE), size = 2, aes(label = campaign_type)) + scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") + scale_y_continuous(labels = scales::comma, breaks = pretty_breaks()) + scale_fill_manual(values = c("Adaptive" = "#28235e", "Lifecycle" = "#ae0a45ff", "One Time" = "#2a5191", "Conversion" = "#27ab7eff", "Experience" = "#66308dff"), na.value = "#999999ff") + theme_bw() + theme(axis.text.x = element_text(), plot.title = element_text(hjust = 0.5, size = 11), axis.title.x = element_text(size = 9), axis.title.y = element_text(size = 9), panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank(), rect = element_blank(), line = element_blank(), legend.position = 'bottom', legend.direction = 'horizontal', legend.title = element_blank()) }
library(ggplot2) d1 <- read.table('multiMTL.bed',header=F,sep="\t") d1$peakwidth <- (d1[,3] - d1[,2]) d1$group <- "multiMTL" d1 <- subset(d1, select=c("peakwidth","group")) d2 <- read.table('MTL.H3K27ac.bed',header=F,sep="\t") d2$peakwidth <- (d2[,3] - d2[,2]) d2$group <- "MTL.H3K27ac" d2 <- subset(d2, select=c("peakwidth","group")) d3 <- read.table('MTL.H3K9ac.bed',header=F,sep="\t") d3$peakwidth <- (d3[,3] - d3[,2]) d3$group <- "MTL.H3K9ac" d3 <- subset(d3, select=c("peakwidth","group")) d4 <- read.table('MTL.H3K122ac.bed',header=F,sep="\t") d4$peakwidth <- (d4[,3] - d4[,2]) d4$group <- "MTL.H3K122ac" d4 <- subset(d4, select=c("peakwidth","group")) d <- rbind(d1,d2,d3,d4) d$group <- factor(d$group,c("multiMTL","MTL.H3K27ac","MTL.H3K9ac","MTL.H3K122ac")) pdf('peak_size.pdf',height=4,width=6) ggplot(d,aes(log10(peakwidth),col=group)) + #geom_density() + geom_freqpoly() + theme_bw(base_size=16) + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + geom_hline(yintercept = 0) dev.off()
/peak_size.R
no_license
qiongmeng-m/ADEpigenetics
R
false
false
1,041
r
library(ggplot2) d1 <- read.table('multiMTL.bed',header=F,sep="\t") d1$peakwidth <- (d1[,3] - d1[,2]) d1$group <- "multiMTL" d1 <- subset(d1, select=c("peakwidth","group")) d2 <- read.table('MTL.H3K27ac.bed',header=F,sep="\t") d2$peakwidth <- (d2[,3] - d2[,2]) d2$group <- "MTL.H3K27ac" d2 <- subset(d2, select=c("peakwidth","group")) d3 <- read.table('MTL.H3K9ac.bed',header=F,sep="\t") d3$peakwidth <- (d3[,3] - d3[,2]) d3$group <- "MTL.H3K9ac" d3 <- subset(d3, select=c("peakwidth","group")) d4 <- read.table('MTL.H3K122ac.bed',header=F,sep="\t") d4$peakwidth <- (d4[,3] - d4[,2]) d4$group <- "MTL.H3K122ac" d4 <- subset(d4, select=c("peakwidth","group")) d <- rbind(d1,d2,d3,d4) d$group <- factor(d$group,c("multiMTL","MTL.H3K27ac","MTL.H3K9ac","MTL.H3K122ac")) pdf('peak_size.pdf',height=4,width=6) ggplot(d,aes(log10(peakwidth),col=group)) + #geom_density() + geom_freqpoly() + theme_bw(base_size=16) + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + geom_hline(yintercept = 0) dev.off()
# correct wrong specification of parameters "correctp" <- function( x, y, eta, K, kappa, select, fit ) { # eta if ( min(eta)<0 | max(eta)>=1 ) { if ( max(eta)==1 ) { stop('eta should be strictly less than 1!') } if ( length(eta)==1 ) { stop('eta should be between 0 and 1!') } else { stop('eta should be between 0 and 1! \n Choose appropriate range of eta!') } } # K if ( max(K) > ncol(x) ) { stop('K cannot exceed the number of predictors! Pick up smaller K!') } if ( max(K) >= nrow(x) ) { stop('K cannot exceed the sample size! Pick up smaller K!') } if ( min(K)<=0 | !all(K%%1==0) ) { if ( length(K)==1 ) { stop('K should be a positive integer!') } else { stop('K should be a positive integer! \n Choose appropriate range of K!') } } # kappa if ( kappa>0.5 | kappa<0 ) { cat('kappa should be between 0 and 0.5! kappa=0.5 is used. \n\n') kappa <- 0.5 } # select if ( select!="pls2" & select!="simpls" ) { cat('Invalid PLS algorithm for variable selection.\n') cat('pls2 algorithm is used. \n\n') select <- 'pls2' } # fit fits <- c("simpls", "kernelpls", "widekernelpls", "oscorespls") if ( !any(fit==fits) ) { cat('Invalid PLS algorithm for model fitting\n') cat('simpls algorithm is used. \n\n') fit <- 'simpls' } list( K=K, eta=eta, kappa=kappa, select=select, fit=fit ) }
/R_Codes/3-PLS/spls_scores/R/correctp.R
no_license
ManonMartin/thesisMaterial
R
false
false
1,775
r
# correct wrong specification of parameters "correctp" <- function( x, y, eta, K, kappa, select, fit ) { # eta if ( min(eta)<0 | max(eta)>=1 ) { if ( max(eta)==1 ) { stop('eta should be strictly less than 1!') } if ( length(eta)==1 ) { stop('eta should be between 0 and 1!') } else { stop('eta should be between 0 and 1! \n Choose appropriate range of eta!') } } # K if ( max(K) > ncol(x) ) { stop('K cannot exceed the number of predictors! Pick up smaller K!') } if ( max(K) >= nrow(x) ) { stop('K cannot exceed the sample size! Pick up smaller K!') } if ( min(K)<=0 | !all(K%%1==0) ) { if ( length(K)==1 ) { stop('K should be a positive integer!') } else { stop('K should be a positive integer! \n Choose appropriate range of K!') } } # kappa if ( kappa>0.5 | kappa<0 ) { cat('kappa should be between 0 and 0.5! kappa=0.5 is used. \n\n') kappa <- 0.5 } # select if ( select!="pls2" & select!="simpls" ) { cat('Invalid PLS algorithm for variable selection.\n') cat('pls2 algorithm is used. \n\n') select <- 'pls2' } # fit fits <- c("simpls", "kernelpls", "widekernelpls", "oscorespls") if ( !any(fit==fits) ) { cat('Invalid PLS algorithm for model fitting\n') cat('simpls algorithm is used. \n\n') fit <- 'simpls' } list( K=K, eta=eta, kappa=kappa, select=select, fit=fit ) }
### # test retrieving user location data from profile ### library(ggmap) library(RCurl) library(XML) library(Rwebdriver) #start webdriver session start_session(root="http://127.0.0.1:4444/wd/hub/",browser="firefox") #specify the member profile url member.url.fragment <- "/titericz" kaggle.base.url <- "https://www.kaggle.com" #retrieve member profile page post.url(url=paste0(kaggle.base.url,member.url.fragment)) #get member page data member.page <- htmlParse(page_source()) #find user location member.location <- xmlValue(xpathApply(member.page,'//dd[@data-bind="text: location"]')[[1]]) fileConn<-file("./data/member_page.txt") writeLines(member.page, fileConn) close(fileConn) quit_session()
/src/test_extract_user_data.R
no_license
jimthompson5802/kaggle-RScript
R
false
false
713
r
### # test retrieving user location data from profile ### library(ggmap) library(RCurl) library(XML) library(Rwebdriver) #start webdriver session start_session(root="http://127.0.0.1:4444/wd/hub/",browser="firefox") #specify the member profile url member.url.fragment <- "/titericz" kaggle.base.url <- "https://www.kaggle.com" #retrieve member profile page post.url(url=paste0(kaggle.base.url,member.url.fragment)) #get member page data member.page <- htmlParse(page_source()) #find user location member.location <- xmlValue(xpathApply(member.page,'//dd[@data-bind="text: location"]')[[1]]) fileConn<-file("./data/member_page.txt") writeLines(member.page, fileConn) close(fileConn) quit_session()
library(tidyverse) tuition_cost <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_cost.csv') tuition_income <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_income.csv') salary_potential <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/salary_potential.csv') historical_tuition <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/historical_tuition.csv') diversity_school <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/diversity_school.csv') tuition_cost %>% group_by(state, type) %>% summarise(avg_tuition = mean(in_state_tuition)) %>% arrange(-avg_tuition) tuition_income tuition_cost new <- salary_potential %>% mutate(diff = abs(mid_career_pay-early_career_pay)) salary_potential %>% right_join(tuition_income) historical_tuition %>% mutate(new_year = str_extract(year, pattern = "\\d{4}")) %>% #filter(tuition_type == "All Constant") %>% ggplot(aes(x = new_year, y= tuition_cost, group = type, color = type))+ geom_line()+ facet_wrap(~ tuition_type) ?facet_wrap View() count(new_year) ?str_extract separate(col = year, into = "new_year", sep = "([1-9])\\1\\1\\1\\1") ?separate ggplot(aes(x = stem_percent, make_world_better_percent))+ geom_point() max(salary_potential$make_world_better_percent, na.rm = T) summarise(avg_p = mean(make_world_better_percent)) %>% View() arrange(-avg_p) right_join(tuition_cost, by = "name") cor.test(new$mid_career_pay, new$make_world_better_percent) ggplot(salary_potential,aes(mid_career_pay, make_world_better_percent, fill = ifelse(rank < 40, "red", "black")))+ geom_point() ?cor.test tuition_cost historical_tuition %>% count(year) tuition_cost %>% right_join(diversity_school) %>% mutate(id = row_number()) %>% pivot_wider(names_from = "category", values_from = "enrollment") %>% select(c(1,2,4,"total_enrollment":"Total Minority")) View() ?pivot_wider View() diversity_school %>% drop_na() %>% pivot_wider(names_from = "category", values_from = "enrollment")
/2020/week11_college/trial.R
no_license
AmitLevinson/TidyTuesday
R
false
false
2,318
r
library(tidyverse) tuition_cost <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_cost.csv') tuition_income <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_income.csv') salary_potential <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/salary_potential.csv') historical_tuition <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/historical_tuition.csv') diversity_school <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/diversity_school.csv') tuition_cost %>% group_by(state, type) %>% summarise(avg_tuition = mean(in_state_tuition)) %>% arrange(-avg_tuition) tuition_income tuition_cost new <- salary_potential %>% mutate(diff = abs(mid_career_pay-early_career_pay)) salary_potential %>% right_join(tuition_income) historical_tuition %>% mutate(new_year = str_extract(year, pattern = "\\d{4}")) %>% #filter(tuition_type == "All Constant") %>% ggplot(aes(x = new_year, y= tuition_cost, group = type, color = type))+ geom_line()+ facet_wrap(~ tuition_type) ?facet_wrap View() count(new_year) ?str_extract separate(col = year, into = "new_year", sep = "([1-9])\\1\\1\\1\\1") ?separate ggplot(aes(x = stem_percent, make_world_better_percent))+ geom_point() max(salary_potential$make_world_better_percent, na.rm = T) summarise(avg_p = mean(make_world_better_percent)) %>% View() arrange(-avg_p) right_join(tuition_cost, by = "name") cor.test(new$mid_career_pay, new$make_world_better_percent) ggplot(salary_potential,aes(mid_career_pay, make_world_better_percent, fill = ifelse(rank < 40, "red", "black")))+ geom_point() ?cor.test tuition_cost historical_tuition %>% count(year) tuition_cost %>% right_join(diversity_school) %>% mutate(id = row_number()) %>% pivot_wider(names_from = "category", values_from = "enrollment") %>% select(c(1,2,4,"total_enrollment":"Total Minority")) View() ?pivot_wider View() diversity_school %>% drop_na() %>% pivot_wider(names_from = "category", values_from = "enrollment")
\name{ibex} \alias{ibex} \docType{data} \title{ Rumen Temperature In An Alpine Ibex } \description{ Telemetric measurements of rumen temperature in a free-living alpine ibex (\emph{Capra ibex}) measured at unequal time intervals. } \usage{data(ibex)} \format{ A data frame with 1201 observations on 3 variables. \describe{ \item{date}{a character variable giving date and time of measurements.} \item{hours}{a numerical variable giving hours elapsed since the first measurement.} \item{temp}{a numerical variable giving rumen (stomach) temperature in degrees Celsius.} } } \source{ A subset of data from Signer, C., Ruf, T., Arnold, W. (2011) \emph{Functional Ecology} \bold{25}: 537-547. } \examples{ data(ibex) datetime <- as.POSIXlt(ibex$date) plot(datetime,ibex$temp,pch=19,cex=0.3) } \keyword{datasets}
/man/ibex.Rd
no_license
cran/lomb
R
false
false
832
rd
\name{ibex} \alias{ibex} \docType{data} \title{ Rumen Temperature In An Alpine Ibex } \description{ Telemetric measurements of rumen temperature in a free-living alpine ibex (\emph{Capra ibex}) measured at unequal time intervals. } \usage{data(ibex)} \format{ A data frame with 1201 observations on 3 variables. \describe{ \item{date}{a character variable giving date and time of measurements.} \item{hours}{a numerical variable giving hours elapsed since the first measurement.} \item{temp}{a numerical variable giving rumen (stomach) temperature in degrees Celsius.} } } \source{ A subset of data from Signer, C., Ruf, T., Arnold, W. (2011) \emph{Functional Ecology} \bold{25}: 537-547. } \examples{ data(ibex) datetime <- as.POSIXlt(ibex$date) plot(datetime,ibex$temp,pch=19,cex=0.3) } \keyword{datasets}
## Feb 26 4 2018 ## Goal: create exposome globe ## Initialize the workspace rm(list=ls()) # clear workspace; # ls() # list objects in the workspace cat("\014") # same as ctrl-L # dev.off() # reset graphic par # quartz(height=6, width=6) # ***************************************************************************** ## Notes #' 1. EWAS sign = 113 mz; correlation matrix = 104 (filter bad m/z or not enough obs) #' 2. mzmatch_table (row = 113): conversion table with ewas results + ID, class, color etc for chord; from corr.R #' Section A: create list (RT class x10) #' a) conversion table: row = 104 and create time class for parents #' b) create the chemical-time-class list for ASD from a) #' c) create the chemical-time-class list for parent from a) #' #' Switch: #' Section A: create list (cluster class x9) #' 3. next time modify to have map() to run array of setting for best color/width setting # ***************************************************************************** # ******** ----- # A. Create-lists ------------------------------------------- library(tidyverse) # load("results/hilic_corr_sign.Rdata") load("results/c18_ewas_sign_corr.Rdata") ## Switch for saving # saveName = "hilic" saveName = "c18" # # ********* # ##' By RT class # # ## 1 mzmatch table matching the new mz list in corr (i.e. lesser mz) # tmp_index_match <- match(mzmatch_table$mzid_a, colnames(autism_case3)) # # mzmatch_table_2 <- mzmatch_table[!is.na(tmp_index_match), ] # # mzmatch_table_2$timeclassp <- sprintf("%s.", mzmatch_table_2$timeclass) # timeclass label for parents # # ## 2 chem-RT list for ASD # # ### spread into short format (timeclass and mz partial dummy) # mzmatch_long <- spread(mzmatch_table_2, timeclass, mzid_a) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later # mzmatch_long <- mzmatch_long %>% select("A", "B", "C", "D", "E", "F", "G", "H", "I", "J") # # ### list # tmp_mzmatch_list <- as.list(mzmatch_long) # autism_case3_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # # # ## 3 chem-RT list for parents # # ### spread into short format (timeclass and mz partial dummy) # mzmatch_long <- spread(mzmatch_table_2, timeclassp, mzid_p) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later # mzmatch_long <- mzmatch_long %>% select("A.", "B.", "C.", "D.", "E.", "F.", "G.", "H.", "I.", "J.") # # ### list # tmp_mzmatch_list <- as.list(mzmatch_long) # tmp_parents_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # # ## chem-RT parents-asd list # # chord_list <- c(tmp_parents_list, autism_case3_list) # ********* ##' By cluster class ## 1 create conversion dataframe # read outdirectory <- "./results" # outfilename <- sprintf("chemOrder_fatherCaseIntra_%s.rds", saveName) outfilename <- sprintf("chemOrder_motherCaseIntra_%s.rds", saveName) #using mother for consistent chemOrder <- readRDS(file.path(outdirectory, outfilename)) # replace with correct mz name chemOrder$chemIDp <- str_replace(chemOrder$chemIDp, ".x$", ".y") # .x is asd, .y is parent (mother or father) chemOrder$mzid <- str_replace(chemOrder$mzid, ".x$", "") # .x is asd, .y is parent (mother or father) chemOrder$group <- as.character(chemOrder$group) # numeric grp to char for asd chemOrder$groupp <- paste(chemOrder$group, ".", sep = "") # char grp for parents # create color for groups colorCodes <- c("#89C5DA", "#DA5724", "#74D944", "#CE50CA", "#3F4921", "#C0717C", "#CBD588", "#5F7FC7", "#673770") names(colorCodes) <- table(chemOrder$group) %>% names %>% dput() which(names(colorCodes) %in% chemOrder$group) chemOrder$grpcolor <- "n____" for(i in 1:length(colorCodes)) { mtchC <- which(chemOrder$group %in% names(colorCodes)[i]) chemOrder$grpcolor[mtchC] <- colorCodes[i] } ## save outdirectory <- "./results" outfilename <- sprintf("chemOrderClusTab_Father_%s.rds", saveName) saveRDS(chemOrder, file.path(outdirectory,outfilename)) # hello <- readRDS("results/chemOrder.rds") ## 2 chem-cluster list for ASD # spread into short format (timeclass and mz partial dummy) mzmatch_long <- spread(chemOrder, group, chemID) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later mzmatch_long <- mzmatch_long %>% select(table(chemOrder$group) %>% names %>% dput()) # list tmp_mzmatch_list <- as.list(mzmatch_long) autism_case3_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # rearrange the cluster group (after initial plotting) autism_case3_list <- autism_case3_list[c("9", "8", "5", "4", "3", "2", "6", "1", "7")] ## save outdirectory <- "./results" outfilename <- sprintf("chemOrderListASD_Father_%s.rds", saveName) saveRDS(autism_case3_list, file.path(outdirectory,outfilename)) # hello <- readRDS("results/chemOrder.rds") ## 3 chem-cluster list for parents # spread into short format (timeclass and mz partial dummy) mzmatch_long <- spread(chemOrder, groupp, chemIDp) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later mzmatch_long <- mzmatch_long %>% select(table(chemOrder$groupp) %>% names %>% dput()) # list tmp_mzmatch_list <- as.list(mzmatch_long) tmp_parents_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # rearrange the cluster group (after initial plotting) tmp_parents_list <- tmp_parents_list[c("9.", "8.", "5.", "4.", "3.", "2.", "6.", "1.", "7.")] ## 4 chem-cluster parents-asd list chord_list <- c(tmp_parents_list, autism_case3_list) # ******** ----- # B. chord-prep ------------------------------------------- # LIFE chord's code # Make parents (topright) and asd (topleft) symmetric in the plot: # reverse asd chem cateogry order ordertemp <- names(chord_list) ordertemp[(length(autism_case3_list)+1):length(ordertemp)] <- rev(ordertemp[(length(autism_case3_list)+1):length(ordertemp)]) chord_list <- chord_list[ordertemp] # revser asd chemical order within each cateogry # For cl male category has _m suffix # for(i in grep("m$", names(cl), ignore.case = T)) { # cl[[i]] <- rev(cl[[i]]) # } for(i in 11:length(ordertemp)) { chord_list[[i]] <- rev(chord_list[[i]]) } ## create a chemical and chemical category directory vector. unlist(cl, use.names = F) can avoid extract funny name from cd cd = structure(rep(names(chord_list), times = sapply(chord_list, length)), names = unlist(chord_list)) # structure(1:6, dim = 2:3); structure(1:9, dim = c(3,3)) # number of chem groups n_group = length(chord_list) # color x10 for RT # colorCodes <- c("#89C5DA", "#DA5724", "#74D944", "#CE50CA", "#3F4921", "#C0717C", "#CBD588", "#5F7FC7", # "#673770", "#D3D93E") # "#38333E", "#508578", "#D7C1B1" # color x9 for cluster colorCodes <- c("#89C5DA", "#DA5724", "#74D944", "#CE50CA", "#3F4921", "#C0717C", "#CBD588", "#5F7FC7", "#673770") # Chord category label (for making line break) # label in 2 rows test with name "pcb \n mcd" etc # linebrk <- c("PCBs", "OCPs", "Polybrominated_\ncpds", "PFASs", "Blood_metals", # "Cotinine", "Phytoestrogens", "Phthalates", "Phenols", "Anti_microbial_cpds", # "Paracetamols", "Urine_metals", "Urine_metalloids", "Urine_metalloids.m", # "Urine_metals.m", "Paracetamols.m", "Anti_microbial_cpds.m", # "Phenols.m", "Phthalates.m", "Phytoestrogens.m", "Cotinine.m", # "Blood_metals.m", "PFASs.m", "Polybrominated_cpds.m", "OCPs.m", # "PCBs.m") # C. Chord diagram ------------------------------------------- library(circlize) circos.clear() circos.par( gap.degree = c(rep(2, n_group/2-1), 10, rep(2, n_group/2-1), 10), cell.padding = c(0, 0, 0, 0), start.degree = 84, canvas.xlim = c(-1.5, 1.5), # 1.2 canvas.ylim = c(-1.5, 1.5) ) # Why using without cell.padding, I see unequal cell width among sector? # the concept: dawing mechanism for circos rectangle. You have the whole things defined, then to draw what, its has "border" concept # You adj. boarder then it will auto draw the line to reveal rectangle. # thus, if I don't set cell.padding to 0 (i.e. board gap of cells within sector), only the whole rectangle sector is in sub equal width # and those with only 1 cell vs 30 cells, the 1 cell will be narrow # see figure 7 in the vingette (1. circlize intro.pdf) # after you set "cell.padding" to 0, doesn't matter you have "bg.border" or not as they will be overlapped # this "limit", "padding" and "your object" x3 concept should apply to canvas area and ploting area in figure! # You have have many invisible settings/ boundary/ padding(gap)/ concept in R graphic, implicityly needed for graphic # Table 1 in vingette got the default parameters circos.initialize(factors = names(chord_list), xlim = cbind(c(rep(0, n_group)), sapply(chord_list, length))) circos.trackPlotRegion( ylim = c(0, 1), bg.border = NA, bg.col = c(colorCodes, rev(colorCodes)), track.height = 0.04, panel.fun = function(x, y) { nm = get.cell.meta.data("sector.index") # ind = get.cell.meta.data("sector.numeric.index") For label line break r = chord_list[[nm]] n = length(r) circos.rect(seq(0, n-1), rep(0, n), 1:n, rep(1, n), lwd = 0.5) # circos.text(1:n - 0.5, rep(0.5, n), r, niceFacing = TRUE, cex = 0.7) #cell text circos.text(n/2, 3.7, nm, adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.65) # circos.text(n/2, 3.5, linebrk[ind], adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.6) # for label line break } ) ## color # col_fun = colorRamp2(c(-0.75, 0, 0.75), c("darkgreen", "white", "red")) # 0.75 range # col_fun = colorRamp2(c(-1.4, -0.25, 0.05, 0.9), c("darkgreen", "white", "white", "red")) # col_fun = colorRamp2(c(-0.9, -0.45, 0.45, 0.9), c("darkgreen", "white", "white", "red")) # max range best double of what I want to show at with top 20% sth col_fun = colorRamp2(c(-1.3, 0, 1.3), c("darkgreen", "white", "red")) # 0.75 range # col_fun = colorRamp2(c(-1, 0, 1), c("darkgreen", "white", "red")) # 0.75 range # https://jsfiddle.net/teddyrised/g02s07n4/embedded/result/ site to read 8 digits hex code to rgb and color # C. links for within family ------------------------------------------- mat_fm = as.matrix(cor_father) # hist(mat_fm) ###' start trial at rougly with 20% as cutoff mat_fm[mat_fm < 0.45 & mat_fm > -0.45] <- NA # set NA threshold n = nrow(mat_fm) rn = rownames(mat_fm) cn = colnames(mat_fm) for(i in 1:n) { for(j in 1:n) { g1 = cd[rn[i]] g2 = cd[cn[j]] r1 = cd[cd == g1] k1 = which(names(r1) == rn[i]) r2 = cd[cd == g2] k2 = which(names(r2) == cn[j]) if (is.na(mat_fm[i, j])) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_mf[i, j]*4, # col = "#00000000") # set transparency } else { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_fm[i, j]/1.5, h = 0.5, # h = 0.6, col = col_fun(mat_fm[i, j]) )#, rou1 = 0.8, rou2 = 0.8) # rou1 = 0.5, rou2 = 0.5 are optional to shrink # lwd: use log to max the scale diff vs simple: mat_m[i, j]; log base: pick a value output 0-1 range, for the given input r range. # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track } } } # circos.clear() # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_fm[i, j]*2, h = 0.6, # h = 0.6, # D. links for within parents ------------------------------------------- mat_f = as.matrix(cor_fatherIntra) mat_f[mat_f < 0.45 & mat_f > -0.45] <- NA # set NA threshold nf = nrow(mat_f) rnf = rownames(mat_f) for(i in 1:(nf-1)) { for(j in seq(i+1, nf)) { # rev(seq(i+1, nf)) g1 = cd[rnf[i]] g2 = cd[rnf[j]] r1 = cd[cd == g1] k1 = which(names(r1) == rnf[i]) r2 = cd[cd == g2] k2 = which(names(r2) == rnf[j]) if (is.na(mat_f[i, j])) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_f[i, j]*2, h = (abs(j-i)/(nf-1)*0.7), # col = "#00000000") # set transparet } else if (g1 == g2) { # within class; k1-0.5 should be element cell in sector. width 1 by default in my layout, -0.5 = line from middle of the element cell circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_f[i, j]/1.5, h = (abs(j-i)/(nf-1)*-0.10), # h = (abs(j-i)/(nf-1)*0.68 + 0.02) col = col_fun(mat_f[i, j]), rou1 = 1.01, rou2 = 1.01) } else if (mat_f[i, j] > 0) { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_f[i, j]), 2)+1, h = (abs(j-i)/(nf-1)*0.10 + 0.1), col = col_fun(mat_f[i, j])) } else { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_f[i, j]), 2)+1, h = (abs(j-i)/(nf-1)*0.03 + 0.26), col = col_fun(mat_f[i, j])) # lwd: use log to max the scale diff vs simple: mat_m[i, j]; log base: pick a value output 0-1 range, for the given input r range. # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track } } } # circos.clear() # # E. links for within asd ------------------------------------------- # # mat_m = as.matrix(cor_asd) # # mat_m[mat_m < 0.6 & mat_m > -0.6] <- NA # set NA threshold # # nm = nrow(mat_m) # rnm = rownames(mat_m) # # for(i in 1:(nm-1)) { # for(j in seq(i+1, nm)) { # g1 = cd[rnm[i]] # g2 = cd[rnm[j]] # r1 = cd[cd == g1] # k1 = which(names(r1) == rnm[i]) # r2 = cd[cd == g2] # k2 = which(names(r2) == rnm[j]) # if (is.na(mat_m[i, j])) { # # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # # col = "#00000000") # set transparet # } else if (g1 == g2) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]/1.5, h = (abs(j-i)/(nm-1)*-0.10), # h = (abs(j-i)/(nm-1)*0.68 + 0.02) # col = col_fun(mat_m[i, j]), rou1 = 1.01, rou2 = 1.01) # } else { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j], h = (abs(j-i)/(nm-1)*0.20 + 0.04), # col = col_fun(mat_m[i, j])) # # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track # } # } # } # # circos.clear() # E. links for within asd ------------------------------------------- mat_m = as.matrix(cor_fathercaseIntra) mat_m[mat_m < 0.45 & mat_m > -0.45] <- NA # set NA threshold nm = nrow(mat_m) rnm = rownames(mat_m) for(i in 1:(nm-1)) { for(j in seq(i+1, nm)) { g1 = cd[rnm[i]] g2 = cd[rnm[j]] r1 = cd[cd == g1] k1 = which(names(r1) == rnm[i]) r2 = cd[cd == g2] k2 = which(names(r2) == rnm[j]) if (is.na(mat_m[i, j])) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # col = "#00000000") # set transparet } else if (g1 == g2) { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]/1.5, h = (abs(j-i)/(nm-1)*-0.10), # h = (abs(j-i)/(nm-1)*0.68 + 0.02) col = col_fun(mat_m[i, j]), rou1 = 1.01, rou2 = 1.01) } else if (mat_m[i, j] > 0) { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_m[i, j]), 2)+1, h = (abs(j-i)/(nm-1)*0.10 + 0.1), col = col_fun(mat_m[i, j])) } else { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_m[i, j]), 2)+1, h = (abs(j-i)/(nm-1)*0.03 + 0.26), col = col_fun(mat_m[i, j])) # lwd = # mat_m[i, j] # lwd: use log to max the scale diff vs simple: mat_m[i, j]; log base: pick a value output 0-1 range, for the given input r range. # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track } } } circos.clear() # quartz.save("results/hilic_chord.png", type = "png", device = dev.cur(), dpi = 400) outdirectory <- "./results" outfilename <- sprintf("chord_father_%s.pdf", saveName) quartz.save(file.path(outdirectory,outfilename), type = "pdf") # lwd test: # log(abs(0.65), 1.7)+1 # log(abs(0.68), 1.7)+1 # log(abs(0.8), 1.7)+1 # log(abs(0.9), 1.7)+1 # log(abs(1), 1.7)+1 # ******** ----- # x. TODO ----------------------------------------------------------- # link draw seq to have intra the uppest or as rou setting per group to show what I want as discussed in the paper # For this goal on links: # 1. done # color # thickness lwd # rou # h # w # 2. done # # the PCB to POP cluster, h seems got problem # non linear h for male # # > g1 # pcb177amt_M # "PCBsM" # > g2 # pophcbamt_M # "POPsM" # > i # [1] 25 # > j # [1] 48 # > (abs(j-i)/(nm-1)*0.7) # [1] 0.1219697 # > # # so, # it;s because the count of cell is in order, and female, it's left to right # for male: categ order reversed, but not the within class cell order. it's PCBsM left to right, categ class from right to left reversed # 3. # adj visual to you get the msg ASAP # longer link first, then shorter on top # done longer links draw first # male # links_m <- data.frame() # for(i in 1:(nm-1)) { # for(j in seq(i+1, nm)) { # g1 = cd[rnm[i]] # # print(i) # g2 = cd[rnm[j]] # # print(j) # r1 = cd[cd == g1] # k1 = which(names(r1) == rnm[i]) # r2 = cd[cd == g2] # k2 = which(names(r2) == rnm[j]) # links_m_tmp = data.frame(i, g1, k1, j, g2, k2) # vector can only hold 1 class of information # links_m <- rbind(links_m, links_m_tmp) # } # } # # links_m$dist <- abs(links_m$j-links_m$i) # links_m <- links_m[order(links_m$dist, decreasing = T),] # links_m$g1 <- as.character(links_m$g1) # links_m$g2 <- as.character(links_m$g2) # # for(i in 1:nrow(links_m)) { # m <- links_m[i,] # if (is.na(mat_m[m$i, m$j])) { # } else { # circos.link(m$g1, m$k1 - 0.5, m$g2, m$k2 - 0.5, lwd = mat_m[m$i, m$j]*2, h = (abs(m$j-m$i)/(nm-1)*0.7), # col = col_fun(mat_m[m$i, m$j])) # } # } # 4. done # update the plot region. after setting the region in initalized, create andother class list (e.g. no PCBsF) # and have it to draw the circle withtout PCBsF, then I can update PCBsF with thicker track # circos.trackPlotRegion( # ylim = c(0, 1), # bg.border = NA, # bg.col = c(colorCodes, rev(colorCodes)), # track.height = 0.04, # panel.fun = function(x, y) { # nm = get.cell.meta.data("sector.index") # r = cl[[nm]] # n = length(r) # if (nm == "PCBsF") { # } else { # circos.rect(seq(0, n-1), rep(0, n), 1:n, rep(1, n), lwd = 0.5) # # circos.text(1:n - 0.5, rep(0.5, n), r, niceFacing = TRUE, cex = 0.7) #cell text # circos.text(n/2, 1.5, nm, adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.8) # } # } # ) # # # circos.updatePlotRegion(sector.index = "PCBsF", track.index = 1, bg.col = NA, bg.border = NA) # r = cl[["PCBsF"]] # n = length(r) # circos.rect(seq(0, n-1), rep(0, n), 1:n, rep(2, n), lwd = 0.5, col = "#89C5DA") # circos.text(n/2, 3, "PCBsF", adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.8) # # ******** ----- # X. Errors ----------------------------------------------------------------- # Note: 1 point is out of plotting region in sector 'PCBsF', track '1'. # Can ignore it, it will still draw. It's just saying it's outside the region # ******** ----- # W. Learning ----------------------------------------------------------------- ######################################################### # ## \\ W1. Learning.[Color_space_gradient_comparison] ---- ######################################################### # # library(circlize) # # space = c("RGB", "HSV", "LAB", "XYZ", "sRGB", "LUV") # par(xpd = NA) # plot(NULL, xlim = c(-1, 1), ylim = c(0, length(space)+1), type = "n") # for(i in seq_along(space)) { # f = colorRamp2(c(-1, 0, 1), c("green", "black", "red"), space = space[i]) # x = seq(-1, 1, length = 200) # rect(x-1/200, i-0.5, x+1/200, i+0.5, col = f(x), border = NA) # text(1, i, space[i], adj = c(-0.2, 0.5)) # } # par(xpd = FALSE) # # ######################################################### # # ## \\ W1. Learning.[Gradient_ramp_with_transparency] ---- # ######################################################### # # # myColours = c(1, "steelblue", "#FFBB00", rgb(0.4, 0.2, 0.3)) # adjustcolor(myColours, 0.4) # also see my firefox bookmark addalpha and colorramppalettealpha package # most color space has no transpancy (alpha channel). it's addon # HEX code with 2 more number in front to indicate # !! HEX code is *NOT* a color space as c("RGB", "HSV", "LAB", "XYZ", "sRGB", "LUV"), but a notation # RGBA color space has alpha # R can read HEX and thus with alpha; but colorramp etc use the color space without alpha component ## rect example # # rm(list=ls()) # clear workspace; # ls() # list objects in the workspace # cat("\014") # same as ctrl-L # require(grDevices) # ## set up the plot region: # op <- par(bg = "thistle") # plot(c(100, 250), c(300, 450), type = "n", xlab = "", ylab = "", # main = "2 x 11 rectangles; 'rect(100+i,300+i, 150+i,380+i)'") # the above just set the title, nth to do with "i" # i <- 4*(0:10) # ## draw rectangles with bottom left (100, 300)+i # ## and top right (150, 380)+i # rect(100+i, 300+i, 150+i, 380+i, col = rainbow(11, start = 0.7, end = 0.1)) # rect(240-i, 320+i, 250-i, 410+i, col = heat.colors(11), lwd = i/5) # ******** ----- # X. Playground ---------------------------------------------------------------- # X1 rou ------------------------------------------- # # mat_m = as.matrix(corrubinm) # # mat_m[mat_m < 0.25 & mat_m > -0.25] <- NA # set NA threshold # # nm = nrow(mat_m) # rnm = rownames(mat_m) # # for(i in 1:(nm-1)) { # for(j in seq(i+1, nm)) { # g1 = cd[rnm[i]] # g2 = cd[rnm[j]] # r1 = cd[cd == g1] # k1 = which(names(r1) == rnm[i]) # r2 = cd[cd == g2] # k2 = which(names(r2) == rnm[j]) # if (is.na(mat_m[i, j])) { # # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # # col = "#00000000") # set transparet # } # else { # if (all(c("PCBsM", "POPsM") %in% c(g1, g2))){ # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # rou = 0.76, # col = col_fun(mat_m[i, j])) # } # else { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # col = col_fun(mat_m[i, j])) # } # } # } # } # circos.clear()
/src/c18_ewasSign_chord_Father.R
permissive
jakemkc/autism_shared_env
R
false
false
23,315
r
## Feb 26 4 2018 ## Goal: create exposome globe ## Initialize the workspace rm(list=ls()) # clear workspace; # ls() # list objects in the workspace cat("\014") # same as ctrl-L # dev.off() # reset graphic par # quartz(height=6, width=6) # ***************************************************************************** ## Notes #' 1. EWAS sign = 113 mz; correlation matrix = 104 (filter bad m/z or not enough obs) #' 2. mzmatch_table (row = 113): conversion table with ewas results + ID, class, color etc for chord; from corr.R #' Section A: create list (RT class x10) #' a) conversion table: row = 104 and create time class for parents #' b) create the chemical-time-class list for ASD from a) #' c) create the chemical-time-class list for parent from a) #' #' Switch: #' Section A: create list (cluster class x9) #' 3. next time modify to have map() to run array of setting for best color/width setting # ***************************************************************************** # ******** ----- # A. Create-lists ------------------------------------------- library(tidyverse) # load("results/hilic_corr_sign.Rdata") load("results/c18_ewas_sign_corr.Rdata") ## Switch for saving # saveName = "hilic" saveName = "c18" # # ********* # ##' By RT class # # ## 1 mzmatch table matching the new mz list in corr (i.e. lesser mz) # tmp_index_match <- match(mzmatch_table$mzid_a, colnames(autism_case3)) # # mzmatch_table_2 <- mzmatch_table[!is.na(tmp_index_match), ] # # mzmatch_table_2$timeclassp <- sprintf("%s.", mzmatch_table_2$timeclass) # timeclass label for parents # # ## 2 chem-RT list for ASD # # ### spread into short format (timeclass and mz partial dummy) # mzmatch_long <- spread(mzmatch_table_2, timeclass, mzid_a) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later # mzmatch_long <- mzmatch_long %>% select("A", "B", "C", "D", "E", "F", "G", "H", "I", "J") # # ### list # tmp_mzmatch_list <- as.list(mzmatch_long) # autism_case3_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # # # ## 3 chem-RT list for parents # # ### spread into short format (timeclass and mz partial dummy) # mzmatch_long <- spread(mzmatch_table_2, timeclassp, mzid_p) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later # mzmatch_long <- mzmatch_long %>% select("A.", "B.", "C.", "D.", "E.", "F.", "G.", "H.", "I.", "J.") # # ### list # tmp_mzmatch_list <- as.list(mzmatch_long) # tmp_parents_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # # ## chem-RT parents-asd list # # chord_list <- c(tmp_parents_list, autism_case3_list) # ********* ##' By cluster class ## 1 create conversion dataframe # read outdirectory <- "./results" # outfilename <- sprintf("chemOrder_fatherCaseIntra_%s.rds", saveName) outfilename <- sprintf("chemOrder_motherCaseIntra_%s.rds", saveName) #using mother for consistent chemOrder <- readRDS(file.path(outdirectory, outfilename)) # replace with correct mz name chemOrder$chemIDp <- str_replace(chemOrder$chemIDp, ".x$", ".y") # .x is asd, .y is parent (mother or father) chemOrder$mzid <- str_replace(chemOrder$mzid, ".x$", "") # .x is asd, .y is parent (mother or father) chemOrder$group <- as.character(chemOrder$group) # numeric grp to char for asd chemOrder$groupp <- paste(chemOrder$group, ".", sep = "") # char grp for parents # create color for groups colorCodes <- c("#89C5DA", "#DA5724", "#74D944", "#CE50CA", "#3F4921", "#C0717C", "#CBD588", "#5F7FC7", "#673770") names(colorCodes) <- table(chemOrder$group) %>% names %>% dput() which(names(colorCodes) %in% chemOrder$group) chemOrder$grpcolor <- "n____" for(i in 1:length(colorCodes)) { mtchC <- which(chemOrder$group %in% names(colorCodes)[i]) chemOrder$grpcolor[mtchC] <- colorCodes[i] } ## save outdirectory <- "./results" outfilename <- sprintf("chemOrderClusTab_Father_%s.rds", saveName) saveRDS(chemOrder, file.path(outdirectory,outfilename)) # hello <- readRDS("results/chemOrder.rds") ## 2 chem-cluster list for ASD # spread into short format (timeclass and mz partial dummy) mzmatch_long <- spread(chemOrder, group, chemID) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later mzmatch_long <- mzmatch_long %>% select(table(chemOrder$group) %>% names %>% dput()) # list tmp_mzmatch_list <- as.list(mzmatch_long) autism_case3_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # rearrange the cluster group (after initial plotting) autism_case3_list <- autism_case3_list[c("9", "8", "5", "4", "3", "2", "6", "1", "7")] ## save outdirectory <- "./results" outfilename <- sprintf("chemOrderListASD_Father_%s.rds", saveName) saveRDS(autism_case3_list, file.path(outdirectory,outfilename)) # hello <- readRDS("results/chemOrder.rds") ## 3 chem-cluster list for parents # spread into short format (timeclass and mz partial dummy) mzmatch_long <- spread(chemOrder, groupp, chemIDp) # on the whole df because spread will say error if 2 rows are the same. You can remove columns later mzmatch_long <- mzmatch_long %>% select(table(chemOrder$groupp) %>% names %>% dput()) # list tmp_mzmatch_list <- as.list(mzmatch_long) tmp_parents_list <- lapply(tmp_mzmatch_list, function(x) x[!is.na(x)]) # rearrange the cluster group (after initial plotting) tmp_parents_list <- tmp_parents_list[c("9.", "8.", "5.", "4.", "3.", "2.", "6.", "1.", "7.")] ## 4 chem-cluster parents-asd list chord_list <- c(tmp_parents_list, autism_case3_list) # ******** ----- # B. chord-prep ------------------------------------------- # LIFE chord's code # Make parents (topright) and asd (topleft) symmetric in the plot: # reverse asd chem cateogry order ordertemp <- names(chord_list) ordertemp[(length(autism_case3_list)+1):length(ordertemp)] <- rev(ordertemp[(length(autism_case3_list)+1):length(ordertemp)]) chord_list <- chord_list[ordertemp] # revser asd chemical order within each cateogry # For cl male category has _m suffix # for(i in grep("m$", names(cl), ignore.case = T)) { # cl[[i]] <- rev(cl[[i]]) # } for(i in 11:length(ordertemp)) { chord_list[[i]] <- rev(chord_list[[i]]) } ## create a chemical and chemical category directory vector. unlist(cl, use.names = F) can avoid extract funny name from cd cd = structure(rep(names(chord_list), times = sapply(chord_list, length)), names = unlist(chord_list)) # structure(1:6, dim = 2:3); structure(1:9, dim = c(3,3)) # number of chem groups n_group = length(chord_list) # color x10 for RT # colorCodes <- c("#89C5DA", "#DA5724", "#74D944", "#CE50CA", "#3F4921", "#C0717C", "#CBD588", "#5F7FC7", # "#673770", "#D3D93E") # "#38333E", "#508578", "#D7C1B1" # color x9 for cluster colorCodes <- c("#89C5DA", "#DA5724", "#74D944", "#CE50CA", "#3F4921", "#C0717C", "#CBD588", "#5F7FC7", "#673770") # Chord category label (for making line break) # label in 2 rows test with name "pcb \n mcd" etc # linebrk <- c("PCBs", "OCPs", "Polybrominated_\ncpds", "PFASs", "Blood_metals", # "Cotinine", "Phytoestrogens", "Phthalates", "Phenols", "Anti_microbial_cpds", # "Paracetamols", "Urine_metals", "Urine_metalloids", "Urine_metalloids.m", # "Urine_metals.m", "Paracetamols.m", "Anti_microbial_cpds.m", # "Phenols.m", "Phthalates.m", "Phytoestrogens.m", "Cotinine.m", # "Blood_metals.m", "PFASs.m", "Polybrominated_cpds.m", "OCPs.m", # "PCBs.m") # C. Chord diagram ------------------------------------------- library(circlize) circos.clear() circos.par( gap.degree = c(rep(2, n_group/2-1), 10, rep(2, n_group/2-1), 10), cell.padding = c(0, 0, 0, 0), start.degree = 84, canvas.xlim = c(-1.5, 1.5), # 1.2 canvas.ylim = c(-1.5, 1.5) ) # Why using without cell.padding, I see unequal cell width among sector? # the concept: dawing mechanism for circos rectangle. You have the whole things defined, then to draw what, its has "border" concept # You adj. boarder then it will auto draw the line to reveal rectangle. # thus, if I don't set cell.padding to 0 (i.e. board gap of cells within sector), only the whole rectangle sector is in sub equal width # and those with only 1 cell vs 30 cells, the 1 cell will be narrow # see figure 7 in the vingette (1. circlize intro.pdf) # after you set "cell.padding" to 0, doesn't matter you have "bg.border" or not as they will be overlapped # this "limit", "padding" and "your object" x3 concept should apply to canvas area and ploting area in figure! # You have have many invisible settings/ boundary/ padding(gap)/ concept in R graphic, implicityly needed for graphic # Table 1 in vingette got the default parameters circos.initialize(factors = names(chord_list), xlim = cbind(c(rep(0, n_group)), sapply(chord_list, length))) circos.trackPlotRegion( ylim = c(0, 1), bg.border = NA, bg.col = c(colorCodes, rev(colorCodes)), track.height = 0.04, panel.fun = function(x, y) { nm = get.cell.meta.data("sector.index") # ind = get.cell.meta.data("sector.numeric.index") For label line break r = chord_list[[nm]] n = length(r) circos.rect(seq(0, n-1), rep(0, n), 1:n, rep(1, n), lwd = 0.5) # circos.text(1:n - 0.5, rep(0.5, n), r, niceFacing = TRUE, cex = 0.7) #cell text circos.text(n/2, 3.7, nm, adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.65) # circos.text(n/2, 3.5, linebrk[ind], adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.6) # for label line break } ) ## color # col_fun = colorRamp2(c(-0.75, 0, 0.75), c("darkgreen", "white", "red")) # 0.75 range # col_fun = colorRamp2(c(-1.4, -0.25, 0.05, 0.9), c("darkgreen", "white", "white", "red")) # col_fun = colorRamp2(c(-0.9, -0.45, 0.45, 0.9), c("darkgreen", "white", "white", "red")) # max range best double of what I want to show at with top 20% sth col_fun = colorRamp2(c(-1.3, 0, 1.3), c("darkgreen", "white", "red")) # 0.75 range # col_fun = colorRamp2(c(-1, 0, 1), c("darkgreen", "white", "red")) # 0.75 range # https://jsfiddle.net/teddyrised/g02s07n4/embedded/result/ site to read 8 digits hex code to rgb and color # C. links for within family ------------------------------------------- mat_fm = as.matrix(cor_father) # hist(mat_fm) ###' start trial at rougly with 20% as cutoff mat_fm[mat_fm < 0.45 & mat_fm > -0.45] <- NA # set NA threshold n = nrow(mat_fm) rn = rownames(mat_fm) cn = colnames(mat_fm) for(i in 1:n) { for(j in 1:n) { g1 = cd[rn[i]] g2 = cd[cn[j]] r1 = cd[cd == g1] k1 = which(names(r1) == rn[i]) r2 = cd[cd == g2] k2 = which(names(r2) == cn[j]) if (is.na(mat_fm[i, j])) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_mf[i, j]*4, # col = "#00000000") # set transparency } else { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_fm[i, j]/1.5, h = 0.5, # h = 0.6, col = col_fun(mat_fm[i, j]) )#, rou1 = 0.8, rou2 = 0.8) # rou1 = 0.5, rou2 = 0.5 are optional to shrink # lwd: use log to max the scale diff vs simple: mat_m[i, j]; log base: pick a value output 0-1 range, for the given input r range. # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track } } } # circos.clear() # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_fm[i, j]*2, h = 0.6, # h = 0.6, # D. links for within parents ------------------------------------------- mat_f = as.matrix(cor_fatherIntra) mat_f[mat_f < 0.45 & mat_f > -0.45] <- NA # set NA threshold nf = nrow(mat_f) rnf = rownames(mat_f) for(i in 1:(nf-1)) { for(j in seq(i+1, nf)) { # rev(seq(i+1, nf)) g1 = cd[rnf[i]] g2 = cd[rnf[j]] r1 = cd[cd == g1] k1 = which(names(r1) == rnf[i]) r2 = cd[cd == g2] k2 = which(names(r2) == rnf[j]) if (is.na(mat_f[i, j])) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_f[i, j]*2, h = (abs(j-i)/(nf-1)*0.7), # col = "#00000000") # set transparet } else if (g1 == g2) { # within class; k1-0.5 should be element cell in sector. width 1 by default in my layout, -0.5 = line from middle of the element cell circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_f[i, j]/1.5, h = (abs(j-i)/(nf-1)*-0.10), # h = (abs(j-i)/(nf-1)*0.68 + 0.02) col = col_fun(mat_f[i, j]), rou1 = 1.01, rou2 = 1.01) } else if (mat_f[i, j] > 0) { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_f[i, j]), 2)+1, h = (abs(j-i)/(nf-1)*0.10 + 0.1), col = col_fun(mat_f[i, j])) } else { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_f[i, j]), 2)+1, h = (abs(j-i)/(nf-1)*0.03 + 0.26), col = col_fun(mat_f[i, j])) # lwd: use log to max the scale diff vs simple: mat_m[i, j]; log base: pick a value output 0-1 range, for the given input r range. # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track } } } # circos.clear() # # E. links for within asd ------------------------------------------- # # mat_m = as.matrix(cor_asd) # # mat_m[mat_m < 0.6 & mat_m > -0.6] <- NA # set NA threshold # # nm = nrow(mat_m) # rnm = rownames(mat_m) # # for(i in 1:(nm-1)) { # for(j in seq(i+1, nm)) { # g1 = cd[rnm[i]] # g2 = cd[rnm[j]] # r1 = cd[cd == g1] # k1 = which(names(r1) == rnm[i]) # r2 = cd[cd == g2] # k2 = which(names(r2) == rnm[j]) # if (is.na(mat_m[i, j])) { # # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # # col = "#00000000") # set transparet # } else if (g1 == g2) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]/1.5, h = (abs(j-i)/(nm-1)*-0.10), # h = (abs(j-i)/(nm-1)*0.68 + 0.02) # col = col_fun(mat_m[i, j]), rou1 = 1.01, rou2 = 1.01) # } else { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j], h = (abs(j-i)/(nm-1)*0.20 + 0.04), # col = col_fun(mat_m[i, j])) # # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track # } # } # } # # circos.clear() # E. links for within asd ------------------------------------------- mat_m = as.matrix(cor_fathercaseIntra) mat_m[mat_m < 0.45 & mat_m > -0.45] <- NA # set NA threshold nm = nrow(mat_m) rnm = rownames(mat_m) for(i in 1:(nm-1)) { for(j in seq(i+1, nm)) { g1 = cd[rnm[i]] g2 = cd[rnm[j]] r1 = cd[cd == g1] k1 = which(names(r1) == rnm[i]) r2 = cd[cd == g2] k2 = which(names(r2) == rnm[j]) if (is.na(mat_m[i, j])) { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # col = "#00000000") # set transparet } else if (g1 == g2) { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]/1.5, h = (abs(j-i)/(nm-1)*-0.10), # h = (abs(j-i)/(nm-1)*0.68 + 0.02) col = col_fun(mat_m[i, j]), rou1 = 1.01, rou2 = 1.01) } else if (mat_m[i, j] > 0) { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_m[i, j]), 2)+1, h = (abs(j-i)/(nm-1)*0.10 + 0.1), col = col_fun(mat_m[i, j])) } else { circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = log(abs(mat_m[i, j]), 2)+1, h = (abs(j-i)/(nm-1)*0.03 + 0.26), col = col_fun(mat_m[i, j])) # lwd = # mat_m[i, j] # lwd: use log to max the scale diff vs simple: mat_m[i, j]; log base: pick a value output 0-1 range, for the given input r range. # h's (abs(j-i)/(nm-1): vary height by distance; h's *value: how tight the line band together; h's + value: how far the band away track } } } circos.clear() # quartz.save("results/hilic_chord.png", type = "png", device = dev.cur(), dpi = 400) outdirectory <- "./results" outfilename <- sprintf("chord_father_%s.pdf", saveName) quartz.save(file.path(outdirectory,outfilename), type = "pdf") # lwd test: # log(abs(0.65), 1.7)+1 # log(abs(0.68), 1.7)+1 # log(abs(0.8), 1.7)+1 # log(abs(0.9), 1.7)+1 # log(abs(1), 1.7)+1 # ******** ----- # x. TODO ----------------------------------------------------------- # link draw seq to have intra the uppest or as rou setting per group to show what I want as discussed in the paper # For this goal on links: # 1. done # color # thickness lwd # rou # h # w # 2. done # # the PCB to POP cluster, h seems got problem # non linear h for male # # > g1 # pcb177amt_M # "PCBsM" # > g2 # pophcbamt_M # "POPsM" # > i # [1] 25 # > j # [1] 48 # > (abs(j-i)/(nm-1)*0.7) # [1] 0.1219697 # > # # so, # it;s because the count of cell is in order, and female, it's left to right # for male: categ order reversed, but not the within class cell order. it's PCBsM left to right, categ class from right to left reversed # 3. # adj visual to you get the msg ASAP # longer link first, then shorter on top # done longer links draw first # male # links_m <- data.frame() # for(i in 1:(nm-1)) { # for(j in seq(i+1, nm)) { # g1 = cd[rnm[i]] # # print(i) # g2 = cd[rnm[j]] # # print(j) # r1 = cd[cd == g1] # k1 = which(names(r1) == rnm[i]) # r2 = cd[cd == g2] # k2 = which(names(r2) == rnm[j]) # links_m_tmp = data.frame(i, g1, k1, j, g2, k2) # vector can only hold 1 class of information # links_m <- rbind(links_m, links_m_tmp) # } # } # # links_m$dist <- abs(links_m$j-links_m$i) # links_m <- links_m[order(links_m$dist, decreasing = T),] # links_m$g1 <- as.character(links_m$g1) # links_m$g2 <- as.character(links_m$g2) # # for(i in 1:nrow(links_m)) { # m <- links_m[i,] # if (is.na(mat_m[m$i, m$j])) { # } else { # circos.link(m$g1, m$k1 - 0.5, m$g2, m$k2 - 0.5, lwd = mat_m[m$i, m$j]*2, h = (abs(m$j-m$i)/(nm-1)*0.7), # col = col_fun(mat_m[m$i, m$j])) # } # } # 4. done # update the plot region. after setting the region in initalized, create andother class list (e.g. no PCBsF) # and have it to draw the circle withtout PCBsF, then I can update PCBsF with thicker track # circos.trackPlotRegion( # ylim = c(0, 1), # bg.border = NA, # bg.col = c(colorCodes, rev(colorCodes)), # track.height = 0.04, # panel.fun = function(x, y) { # nm = get.cell.meta.data("sector.index") # r = cl[[nm]] # n = length(r) # if (nm == "PCBsF") { # } else { # circos.rect(seq(0, n-1), rep(0, n), 1:n, rep(1, n), lwd = 0.5) # # circos.text(1:n - 0.5, rep(0.5, n), r, niceFacing = TRUE, cex = 0.7) #cell text # circos.text(n/2, 1.5, nm, adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.8) # } # } # ) # # # circos.updatePlotRegion(sector.index = "PCBsF", track.index = 1, bg.col = NA, bg.border = NA) # r = cl[["PCBsF"]] # n = length(r) # circos.rect(seq(0, n-1), rep(0, n), 1:n, rep(2, n), lwd = 0.5, col = "#89C5DA") # circos.text(n/2, 3, "PCBsF", adj = c(0, 1), facing = c("clockwise"), niceFacing = TRUE, cex = 0.8) # # ******** ----- # X. Errors ----------------------------------------------------------------- # Note: 1 point is out of plotting region in sector 'PCBsF', track '1'. # Can ignore it, it will still draw. It's just saying it's outside the region # ******** ----- # W. Learning ----------------------------------------------------------------- ######################################################### # ## \\ W1. Learning.[Color_space_gradient_comparison] ---- ######################################################### # # library(circlize) # # space = c("RGB", "HSV", "LAB", "XYZ", "sRGB", "LUV") # par(xpd = NA) # plot(NULL, xlim = c(-1, 1), ylim = c(0, length(space)+1), type = "n") # for(i in seq_along(space)) { # f = colorRamp2(c(-1, 0, 1), c("green", "black", "red"), space = space[i]) # x = seq(-1, 1, length = 200) # rect(x-1/200, i-0.5, x+1/200, i+0.5, col = f(x), border = NA) # text(1, i, space[i], adj = c(-0.2, 0.5)) # } # par(xpd = FALSE) # # ######################################################### # # ## \\ W1. Learning.[Gradient_ramp_with_transparency] ---- # ######################################################### # # # myColours = c(1, "steelblue", "#FFBB00", rgb(0.4, 0.2, 0.3)) # adjustcolor(myColours, 0.4) # also see my firefox bookmark addalpha and colorramppalettealpha package # most color space has no transpancy (alpha channel). it's addon # HEX code with 2 more number in front to indicate # !! HEX code is *NOT* a color space as c("RGB", "HSV", "LAB", "XYZ", "sRGB", "LUV"), but a notation # RGBA color space has alpha # R can read HEX and thus with alpha; but colorramp etc use the color space without alpha component ## rect example # # rm(list=ls()) # clear workspace; # ls() # list objects in the workspace # cat("\014") # same as ctrl-L # require(grDevices) # ## set up the plot region: # op <- par(bg = "thistle") # plot(c(100, 250), c(300, 450), type = "n", xlab = "", ylab = "", # main = "2 x 11 rectangles; 'rect(100+i,300+i, 150+i,380+i)'") # the above just set the title, nth to do with "i" # i <- 4*(0:10) # ## draw rectangles with bottom left (100, 300)+i # ## and top right (150, 380)+i # rect(100+i, 300+i, 150+i, 380+i, col = rainbow(11, start = 0.7, end = 0.1)) # rect(240-i, 320+i, 250-i, 410+i, col = heat.colors(11), lwd = i/5) # ******** ----- # X. Playground ---------------------------------------------------------------- # X1 rou ------------------------------------------- # # mat_m = as.matrix(corrubinm) # # mat_m[mat_m < 0.25 & mat_m > -0.25] <- NA # set NA threshold # # nm = nrow(mat_m) # rnm = rownames(mat_m) # # for(i in 1:(nm-1)) { # for(j in seq(i+1, nm)) { # g1 = cd[rnm[i]] # g2 = cd[rnm[j]] # r1 = cd[cd == g1] # k1 = which(names(r1) == rnm[i]) # r2 = cd[cd == g2] # k2 = which(names(r2) == rnm[j]) # if (is.na(mat_m[i, j])) { # # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # # col = "#00000000") # set transparet # } # else { # if (all(c("PCBsM", "POPsM") %in% c(g1, g2))){ # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # rou = 0.76, # col = col_fun(mat_m[i, j])) # } # else { # circos.link(g1, k1 - 0.5, g2, k2 - 0.5, lwd = mat_m[i, j]*2, h = (abs(j-i)/(nm-1)*0.7), # col = col_fun(mat_m[i, j])) # } # } # } # } # circos.clear()
str(t) summary(t) ## missinng values dim(t) t_complete=t[complete.cases(t),] dim(t_complete) install.packages(dplyr) library(dplyr) cs2m cs2m_mutate<-mutate(cs2m, Chlstrl_bp=Chlstrl/BP) cs2m$ratio<-c(cs2m$BP/cs2m$Chlstrl) cs2m$ratio<-(cs2m$BP/cs2m$Chlstrl) cs2m head(cs2m_mutate) head(cs2m) cs2m_1<-cs2m ##Create new variable by another method cs2m_1$chlst_bp<-cs2m_1$chlstrl/cs2m_1$BP View(mtcars) View(cs2m) ##reshape m=cs2m j=m dim(j) install.packages("reshape") library(reshape) variable.names(j) ##j=rename(j,c(Reaction='DrugR', Pregnent='Prgnt')) j=rename(j,c(DrugR='Reaction', Prgnt='Pregnent')) variable.names(j) names(j) ##using names(j)[5]="Anxiety" names(j)[2]="Colesterol" names(j) ##arrange ascending descending library(dplyr) cs2m_asce<- arrange(cs2m,Age) cs2m_asce1<-arrange cs2m_asce1<-arrange head(cs2m_asce) ##rlang::last_error() View(grades) View(grades$quiz1) #sub set grades1<-subset(grades,select = c(quiz1,gpa,final)) head(grades1) View(grades1) grades2<-select(grades,quiz1,gpa,final) grades2 ##apply columns mean apply(cs2m,2,mean) mean(cs2m) mean(cs2m$BP) ##apply row mean apply(cs2m,1,mean) View(mtcars) ##average column by(mtcars[ ,-2], mtcars$cyl, colMeans) ##tapply tapply(cs2m$BP,cs2m$Chlstrl,mean) tapply(grades$gpa,grades$percent,mean) final_60<-subset(grades,final>60) head(final_60) boxplot(grades$final,main='final grade',col='red') boxplot(final_60$final,main='final 60',col='red') ##compare correlation cor.test(grades$gpa,grades$final) cor.test(final_60$gpa,final_60$final) ##applying filter cs2_m_21<-filter(cs2m,Age>20&Age<32) cs2_m_21 ##subset cs2_m_211<-subset(cs2m,Age>19 & Age<32) cs2_m_211 #create sub ethinicity=4 ethinicity_white<-subset(grades,ethnicity==4) head(ethinicity_white) boxplot(ethinicity_white$final,main='white eninicity',col='green') ethinicity_white1<-subset(grades,ethinicity==5) eth4=merge(ethinicity_white,ethinicity_white1) ##record final with sqrt final grades$sqrtfinal<-sqrt(grades$final) head(grades$sqrtfinal) ##compare his of final and sqrt final hist(grades$final) hist(grades$sqrtfinal) ## convert to catagorial variables grades$catgryfinal<-ifelse(grades$final<60,yes="final<60",no="final>60") head(grades) table(grades$catgryfinal) ##Convert final into categories with increment of 5 cat command grades$final_cat<-cut(grades$final,breaks = seq(40,75,5),labels=c("final1","final2","final3","final4","final5","final6","final7")) head(grades) #table command table(grades$catgryfinal) table(grades$final_cat) library(readr) install.packages("readr") library(readr) k<-read.csv("G:/Suman/batch34/cs2m.csv", stringsAsFactors=TRUE) str(k) summary(k$Age) m=k summary(m) View(m) ##within command m<-within(m,{ agecat<-NA agecat[Age>=15 & Age<=25]<-'Low' agecat[Age>=26 & Age<=41]<-'Middle' agecat[Age>41]<-'High' }) head(m,3) ##Convert ingethnicity into two categories category 1 = 1, 3& 5; category 2 = 2 & 4 grades$cateth<-grades$ethnicity grades$cateth[grades$cateth==1|grades$cateth==3|grades$cateth==5]=1 grades$cateth[grades$cateth==2|grades$cateth==4]=2 View(grades) head(grades) ##Take out 20% observations randomly from the file sam<-sample(x=1:nrow(grades),size = 0.2*nrow(grades)) grade20<-grades[sam,] head(grade20) ##all grade 20 grade20 ##case sam ##Summarize library(psych) summarise(cs2m,mean_age=mean(Age,na.rm = T),median_age=median(Age,na.rm = T)) 42=bb a<-grades[,c(13,18,19)] pairs.panels(a) a names(grades) colnames(grades) variable.names(grades) df<-cs2m %>% df
/DataManupulation.R
no_license
suman083/imarticusPractice
R
false
false
3,475
r
str(t) summary(t) ## missinng values dim(t) t_complete=t[complete.cases(t),] dim(t_complete) install.packages(dplyr) library(dplyr) cs2m cs2m_mutate<-mutate(cs2m, Chlstrl_bp=Chlstrl/BP) cs2m$ratio<-c(cs2m$BP/cs2m$Chlstrl) cs2m$ratio<-(cs2m$BP/cs2m$Chlstrl) cs2m head(cs2m_mutate) head(cs2m) cs2m_1<-cs2m ##Create new variable by another method cs2m_1$chlst_bp<-cs2m_1$chlstrl/cs2m_1$BP View(mtcars) View(cs2m) ##reshape m=cs2m j=m dim(j) install.packages("reshape") library(reshape) variable.names(j) ##j=rename(j,c(Reaction='DrugR', Pregnent='Prgnt')) j=rename(j,c(DrugR='Reaction', Prgnt='Pregnent')) variable.names(j) names(j) ##using names(j)[5]="Anxiety" names(j)[2]="Colesterol" names(j) ##arrange ascending descending library(dplyr) cs2m_asce<- arrange(cs2m,Age) cs2m_asce1<-arrange cs2m_asce1<-arrange head(cs2m_asce) ##rlang::last_error() View(grades) View(grades$quiz1) #sub set grades1<-subset(grades,select = c(quiz1,gpa,final)) head(grades1) View(grades1) grades2<-select(grades,quiz1,gpa,final) grades2 ##apply columns mean apply(cs2m,2,mean) mean(cs2m) mean(cs2m$BP) ##apply row mean apply(cs2m,1,mean) View(mtcars) ##average column by(mtcars[ ,-2], mtcars$cyl, colMeans) ##tapply tapply(cs2m$BP,cs2m$Chlstrl,mean) tapply(grades$gpa,grades$percent,mean) final_60<-subset(grades,final>60) head(final_60) boxplot(grades$final,main='final grade',col='red') boxplot(final_60$final,main='final 60',col='red') ##compare correlation cor.test(grades$gpa,grades$final) cor.test(final_60$gpa,final_60$final) ##applying filter cs2_m_21<-filter(cs2m,Age>20&Age<32) cs2_m_21 ##subset cs2_m_211<-subset(cs2m,Age>19 & Age<32) cs2_m_211 #create sub ethinicity=4 ethinicity_white<-subset(grades,ethnicity==4) head(ethinicity_white) boxplot(ethinicity_white$final,main='white eninicity',col='green') ethinicity_white1<-subset(grades,ethinicity==5) eth4=merge(ethinicity_white,ethinicity_white1) ##record final with sqrt final grades$sqrtfinal<-sqrt(grades$final) head(grades$sqrtfinal) ##compare his of final and sqrt final hist(grades$final) hist(grades$sqrtfinal) ## convert to catagorial variables grades$catgryfinal<-ifelse(grades$final<60,yes="final<60",no="final>60") head(grades) table(grades$catgryfinal) ##Convert final into categories with increment of 5 cat command grades$final_cat<-cut(grades$final,breaks = seq(40,75,5),labels=c("final1","final2","final3","final4","final5","final6","final7")) head(grades) #table command table(grades$catgryfinal) table(grades$final_cat) library(readr) install.packages("readr") library(readr) k<-read.csv("G:/Suman/batch34/cs2m.csv", stringsAsFactors=TRUE) str(k) summary(k$Age) m=k summary(m) View(m) ##within command m<-within(m,{ agecat<-NA agecat[Age>=15 & Age<=25]<-'Low' agecat[Age>=26 & Age<=41]<-'Middle' agecat[Age>41]<-'High' }) head(m,3) ##Convert ingethnicity into two categories category 1 = 1, 3& 5; category 2 = 2 & 4 grades$cateth<-grades$ethnicity grades$cateth[grades$cateth==1|grades$cateth==3|grades$cateth==5]=1 grades$cateth[grades$cateth==2|grades$cateth==4]=2 View(grades) head(grades) ##Take out 20% observations randomly from the file sam<-sample(x=1:nrow(grades),size = 0.2*nrow(grades)) grade20<-grades[sam,] head(grade20) ##all grade 20 grade20 ##case sam ##Summarize library(psych) summarise(cs2m,mean_age=mean(Age,na.rm = T),median_age=median(Age,na.rm = T)) 42=bb a<-grades[,c(13,18,19)] pairs.panels(a) a names(grades) colnames(grades) variable.names(grades) df<-cs2m %>% df
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/BETS.save.spss.R \name{BETS.save.spss} \alias{BETS.save.spss} \title{Export a time series to SPSS} \usage{ BETS.save.spss(code = NULL, data = NULL, file.name = "series") } \arguments{ \item{code}{An \code{integer}. The unique identifier of the series within the BETS database.} \item{data}{A \code{data.frame} or a \code{ts}. Contains the data to be written. If \code{data} is supplied, the BETS database will not be searched.} \item{file.name}{A \code{character}. The name of the output file. The default is 'series.spss'.} } \description{ Writes a time series to a .spss (SPSS) file. } \examples{ #Exchange rate - Free - United States dollar (purchase) #us.brl <- BETS.get(3691) #requires(seasonal) #us.brl.seasonally_adjusted <- seas(us.brl) #BETS.save.spss(data = us.brl.seasonally_adjusted,file.name="us.brl.seasonally_adjusted") # Or #BETS.save.spss(code=3691,file.name="us.brl") }
/man/BETS.save.spss.Rd
no_license
talithafs/BETS
R
false
true
1,007
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/BETS.save.spss.R \name{BETS.save.spss} \alias{BETS.save.spss} \title{Export a time series to SPSS} \usage{ BETS.save.spss(code = NULL, data = NULL, file.name = "series") } \arguments{ \item{code}{An \code{integer}. The unique identifier of the series within the BETS database.} \item{data}{A \code{data.frame} or a \code{ts}. Contains the data to be written. If \code{data} is supplied, the BETS database will not be searched.} \item{file.name}{A \code{character}. The name of the output file. The default is 'series.spss'.} } \description{ Writes a time series to a .spss (SPSS) file. } \examples{ #Exchange rate - Free - United States dollar (purchase) #us.brl <- BETS.get(3691) #requires(seasonal) #us.brl.seasonally_adjusted <- seas(us.brl) #BETS.save.spss(data = us.brl.seasonally_adjusted,file.name="us.brl.seasonally_adjusted") # Or #BETS.save.spss(code=3691,file.name="us.brl") }
#' @importFrom magrittr "%>%" #' @importFrom tibble tibble #' @importFrom httr GET #' @importFrom lubridate parse_date_time #' @importFrom xml2 read_xml #' @importFrom xml2 as_list #' @importFrom xml2 xml_contents #' @importFrom xml2 xml_text #' @importFrom xml2 xml_find_all #' @importFrom xml2 xml_find_first #' @importFrom dplyr select #' @importFrom dplyr full_join #' @importFrom sf st_as_sf #' @importFrom stringr str_extract #' @importFrom purrr map #' @author Robert Myles McDonnell, \email{robertmylesmcdonnell@gmail.com} #' @references \url{https://en.wikipedia.org/wiki/RSS} #' @title Extract a tidy data frame from RSS and Atom and JSON feeds #' @description \code{tidyfeed()} downloads and parses rss feeds. The function #' produces a tidy data frame, easy to use for further manipulation and #' analysis. #' @inheritParams httr::GET #' @param feed (\code{character}). The url for the feed that you want to parse. #' @param sf . If TRUE, returns sf dataframe. #' @param config . Passed off to httr::GET(). #' @examples #' \dontrun{ #' # Atom feed: #' tidyfeed("http://journal.r-project.org/rss.atom") #' # rss/xml: #' tidyfeed("http://fivethirtyeight.com/all/feed") #' # jsonfeed: #' tidyfeed("https://daringfireball.net/feeds/json") #' # georss: #' tidyfeed("http://www.geonames.org/recent-changes.xml") #' } #' @export tidyfeed <- function(feed, sf = TRUE, config = list()){ invisible({ suppressWarnings({ stopifnot(identical(length(feed), 1L)) # exit if more than 1 feed provided msg <- "Error in feed parse; please check URL.\nIf you're certain that this is a valid rss feed, please file an issue at https://github.com/RobertMyles/tidyRSS/issues. Please note that the feed may also be undergoing maintenance." doc <- try(httr::GET(feed, config), silent = TRUE) if(grepl("json", doc$headers$`content-type`)){ result <- json_parse(feed) return(result) } else{ doc <- doc %>% xml2::read_xml() } if(unique(grepl('try-error', class(doc)))){ stop(msg) } if(grepl("http://www.w3.org/2005/Atom", xml2::xml_attr(doc, "xmlns"))){ result <- atom_parse(doc) return(result) } else if(grepl("http://www.georss.org/georss", xml2::xml_attr(doc, "xmlns:georss"))){ result <- geo_parse(doc) if(!exists('result$item_long')) { result <- rss_parse(doc) return(result) } else{ if(sf == TRUE){ result <- sf::st_as_sf(x = result, coords = c("item_long", "item_lat"), crs = "+proj=longlat +datum=WGS84") } return(result) } } else{ result <- rss_parse(doc) return(result) } }) }) }
/R/tidyfeed.R
no_license
tombroekel/tidyRSS
R
false
false
2,666
r
#' @importFrom magrittr "%>%" #' @importFrom tibble tibble #' @importFrom httr GET #' @importFrom lubridate parse_date_time #' @importFrom xml2 read_xml #' @importFrom xml2 as_list #' @importFrom xml2 xml_contents #' @importFrom xml2 xml_text #' @importFrom xml2 xml_find_all #' @importFrom xml2 xml_find_first #' @importFrom dplyr select #' @importFrom dplyr full_join #' @importFrom sf st_as_sf #' @importFrom stringr str_extract #' @importFrom purrr map #' @author Robert Myles McDonnell, \email{robertmylesmcdonnell@gmail.com} #' @references \url{https://en.wikipedia.org/wiki/RSS} #' @title Extract a tidy data frame from RSS and Atom and JSON feeds #' @description \code{tidyfeed()} downloads and parses rss feeds. The function #' produces a tidy data frame, easy to use for further manipulation and #' analysis. #' @inheritParams httr::GET #' @param feed (\code{character}). The url for the feed that you want to parse. #' @param sf . If TRUE, returns sf dataframe. #' @param config . Passed off to httr::GET(). #' @examples #' \dontrun{ #' # Atom feed: #' tidyfeed("http://journal.r-project.org/rss.atom") #' # rss/xml: #' tidyfeed("http://fivethirtyeight.com/all/feed") #' # jsonfeed: #' tidyfeed("https://daringfireball.net/feeds/json") #' # georss: #' tidyfeed("http://www.geonames.org/recent-changes.xml") #' } #' @export tidyfeed <- function(feed, sf = TRUE, config = list()){ invisible({ suppressWarnings({ stopifnot(identical(length(feed), 1L)) # exit if more than 1 feed provided msg <- "Error in feed parse; please check URL.\nIf you're certain that this is a valid rss feed, please file an issue at https://github.com/RobertMyles/tidyRSS/issues. Please note that the feed may also be undergoing maintenance." doc <- try(httr::GET(feed, config), silent = TRUE) if(grepl("json", doc$headers$`content-type`)){ result <- json_parse(feed) return(result) } else{ doc <- doc %>% xml2::read_xml() } if(unique(grepl('try-error', class(doc)))){ stop(msg) } if(grepl("http://www.w3.org/2005/Atom", xml2::xml_attr(doc, "xmlns"))){ result <- atom_parse(doc) return(result) } else if(grepl("http://www.georss.org/georss", xml2::xml_attr(doc, "xmlns:georss"))){ result <- geo_parse(doc) if(!exists('result$item_long')) { result <- rss_parse(doc) return(result) } else{ if(sf == TRUE){ result <- sf::st_as_sf(x = result, coords = c("item_long", "item_lat"), crs = "+proj=longlat +datum=WGS84") } return(result) } } else{ result <- rss_parse(doc) return(result) } }) }) }
#Gelman standardization gel_stand <- function(x){(x - mean(x))/(2*sd(x))} #Inverse hyperbolic sine transformation ihs_trans <- function(x){log(x + sqrt(x^2 + 1))} #In terms of standard deviation of un-treated y_stand <- function(x, data){ x2 <-x[data$treated == 0] (x - mean(x2,na.rm = TRUE))/(sd(x2,na.rm = TRUE)) } ##########do_sampling()------------- #y = column of responses (including NA for missings, pre-transformed if needed) #X = matrix of predictor variables, pre-standardized #hh_id = household id vector (should be same dimension as y) #loc_id = location id vector (" ") do_sampling <- function(y, X, X_cntr, hh_id, loc_id,kappa,file){ #compile BSFA model incorporating missingness mechanism compiled_selection_model <- stan_model(file) f <- y index_miss <- which(is.na(f)) N_miss <- length(index_miss) #Missingness - empirical Bayes R <- as.numeric(is.na(f)) m1 <- lm(f~ X) #some of f elements are NA, X is complete imputed_f <- f #impute missing f values based on observed relationship with X imputed_f[index_miss] <- predict(m1, newdata = data.frame(X))[index_miss] #model linking P(missing) to y and X ## (needed imputed f to do this) ML <- glm(R ~ imputed_f , family = binomial) phi_prior_mean <- coef(ML)[1:2] phi_prior_var <- vcov(ML) #replace y values with missing indicator #these values will be replaced in Stan with parameter values to be sampled #(so they will get a capability set too) f[index_miss] <- -99 data.list <- list(N = length(f), todo = which(X[,"treated"] == 1 & X[,"year"] == 1), N2 = length(which(X[,"treated"] == 1 & X[,"year"] == 1)), F = length(unique(hh_id)), L = length(unique(loc_id)), K = ncol(X), hh = as.numeric(as.factor(hh_id)), loc = as.numeric(as.factor(loc_id)), f = f, X = X, X_cntr=X_cntr, R = R, N_miss = N_miss, index_miss = index_miss, phi_prior_mean = phi_prior_mean, phi_prior_var = phi_prior_var, kappa = kappa) #set reasonable initial values initc <- list(gamma1 = -1, gamma2 = rep(0, 7), mu_a = coef(m1)[1], beta = coef(m1)[-1], sigma_a = .5*mean(m1$residuals^2)^(.5), sigma_a2 = .5*mean(m1$residuals^2), sigma_v = .5*mean(m1$residuals^2)^(.5), sigma_v2 = .5*mean(m1$residuals^2), sigma_l = .5*mean(m1$residuals^2)^(.5), sigma_l2 =.5*mean(m1$residuals^2), u =.5*(max(imputed_f)-imputed_f) + .01, #approx. 50 percent of distance from max rho = .9, f_imp = rep(mean(imputed_f), N_miss), phi = phi_prior_mean) inits <- list(initc,initc,initc,initc) #Sample with rstan sm_sampled <- sampling(compiled_selection_model, data = data.list, chains = 4, iter =10000, warmup = 5000, pars = par_keep, include=TRUE, init = inits, control = list(adapt_delta = 0.9)) return(sm_sampled) } ##########plot_cs()----------- #sampled = stanfit object #y = response variable - transformed if applicable #response = character string of y variable (just for labels) #data = kenya data frame #backtrans = logical TRUE if on original (untransformed) scale plot_cs <- function(sampled, y, response, data, backtrans = FALSE){ #draws from posterior predictive (CS) f_pred_trt <- rstan::extract(sampled, "f_pred")%>% data.frame() #draws from counterfactual posterior predictive (CS) f_pred_cntr <- rstan::extract(sampled, "f_pred_cntr")%>% data.frame() if (backtrans == TRUE) { f_pred_trt <- exp(f_pred_trt) f_pred_cntr<- exp(f_pred_cntr) y <- exp(y) } d <- data %>% subset(year == 1 & treated == 1) data.frame(f =y[data$year == 1 & data$treated == 1], missing = is.na(y[data$year == 1 & data$treated == 1]), sex = factor(d$head_sex, levels = c(0,1), labels = c("Male", "Female")), lb_trt = apply(f_pred_trt , 2, "quantile", c(0.05)), ub_trt = apply(f_pred_trt , 2, "quantile", c(0.95)), lb_notrt = apply(f_pred_cntr, 2, "quantile", c(0.05)), ub_notrt = apply(f_pred_cntr, 2, "quantile", c(0.95))) %>% arrange(sex, ub_notrt)%>% mutate(id = c(1:sum(d$head_sex == 0), 1:sum(d$head_sex == 1))) %>% #subset(missing == FALSE)%>% ggplot() + geom_errorbar(aes(x=id, ymin=lb_trt, ymax=ub_trt), colour = "grey50") + geom_line(aes(x=id, y=lb_notrt )) + geom_line(aes(x=id, y=ub_notrt )) + labs(x = "Household ID", y = response)+ geom_point(aes(x = id, y =f),size = .5,alpha = I(.3), colour ="black")+ facet_wrap(.~sex, scales = "free_x")+ theme(plot.title = element_text(hjust = 0.5)) + scale_colour_grey() #+scale_y_continuous(limits = c(-4, 4)) } #########plot_cs_agg()------- #same arguments as plot_cs() plot_cs_agg <- function(sampled, y, response, data, backtrans = FALSE){ f_pred_trt <- rstan::extract(sampled, "f_pred")%>% data.frame() f_pred_cntr <- rstan::extract(sampled, "f_pred_cntr")%>% data.frame() if (backtrans == TRUE) { f_pred_trt <- exp(f_pred_trt) f_pred_cntr<- exp(f_pred_cntr) y <- exp(y) } d <- data %>% subset(year == 1 & treated == 1) data.frame(f =y[data$year == 1 & data$treated == 1], missing = is.na(y[data$year == 1 & data$treated == 1]), sex = factor(d$head_sex, levels = c(0,1), labels = c("Male", "Female")), lb_trt = apply(f_pred_trt , 2, "quantile", c(0.05)), ub_trt = apply(f_pred_trt , 2, "quantile", c(0.95)), lb_notrt = apply(f_pred_cntr, 2, "quantile", c(0.05)), ub_notrt = apply(f_pred_cntr, 2, "quantile", c(0.95))) %>% arrange( ub_notrt)%>% mutate(id = c(1:length(d$head_sex))) %>% #subset(missing == FALSE)%>% ggplot() + geom_errorbar(aes(x=id, ymin=lb_trt, ymax=ub_trt), colour = "grey50") + geom_line(aes(x=id, y=lb_notrt )) + geom_line(aes(x=id, y=ub_notrt )) + labs(x = "Household ID", y = response)+ geom_point(aes(x = id, y =f),size = .5,alpha = I(.3), colour ="black")+ theme(plot.title = element_text(hjust = 0.5)) + scale_colour_grey() #+scale_y_continuous(limits = c(-4, 4)) } #########derivatives() : posterior draws from quantities in Eq (18)------- #full_X: X matrix #samples = stanfit object derivatives <- function(full_X, samples){ full_X_mean <- c(1,apply(full_X, 2, mean))[1:8] full_X_mean[c("treated", "head_sex", "year", "treated_year", "treated_sex", "year_sex", "treated_year_sex")] <- c(1, full_X_mean["head_sex"], 1, 1*1, 1*full_X_mean["head_sex"],full_X_mean["head_sex"]*1, full_X_mean["head_sex"]*1*1) female_X_mean <- c(1,apply(full_X, 2, mean))[1:8] female_X_mean[c("treated", "head_sex", "year", "treated_year", "treated_sex", "year_sex", "treated_year_sex")] <- c(1, 1, 1, 1*1, 1*1,1*1, 1*1*1) male_X_mean <- c(1,apply(full_X, 2, mean))[1:8] male_X_mean[c("treated", "head_sex", "year", "treated_year", "treated_sex", "year_sex", "treated_year_sex")] <- c(1, 0, 1, 1*1, 1*0,0*1, 0*1*1) gamma_samps <- do.call("cbind", rstan::extract(samples, par = c("gamma1","gamma2"))) rho_samps <- rstan::extract(samples, par = c("rho"))[[1]] #CHOICE effect #overall effect temp1 <- apply(gamma_samps, 1, function(x){exp(x%*%full_X_mean)}) #exp(X*gamma) = lambda(1) temp2 <- exp(-apply(gamma_samps[,c(5,8)], 1, function(x){x%*%full_X_mean[c(5,8)]})) # 1/exp(g2 + g3*.6244) dudb <- temp1*(temp2-1)*rho_samps #female effect temp1 <- apply(gamma_samps, 1, function(x){exp(x%*%female_X_mean)}) #exp(X*gamma) = lambda(1) temp2 <- exp(-apply(gamma_samps[,c(5,8)], 1, function(x){x%*%female_X_mean[c(5,8)]})) # 1/exp(g2 + g3*1) dudb_female <- temp1*(temp2-1)*rho_samps #male effect temp1 <- apply(gamma_samps, 1, function(x){exp(x%*%male_X_mean)}) #exp(X*gamma) = lambda(1) temp2 <- exp(-apply(gamma_samps[,c(5,8)], 1, function(x){x%*%male_X_mean[c(5,8)]})) # 1/exp(g2 + g3*0) dudb_male <- temp1*(temp2-1)*rho_samps rm(gamma_samps) rm(rho_samps) #CAPABILITIES effect beta_samps <- do.call("cbind", rstan::extract(samples, par = c("beta"))) #overall effect dcdb <- beta_samps[,4] + beta_samps[,7]*full_X_mean["head_sex"] #female effect dcdb_female <- beta_samps[,4] + beta_samps[,7]*1 #male effect dcdb_male <- beta_samps[,4] + beta_samps[,7]*0 rm(beta_samps) #FUNCTIONING effect dydb <- dcdb + dudb dydb_female <- dcdb_female + dudb_female dydb_male <- dcdb_male + dudb_male all <- rbind(data.frame(effect = dydb, type = "Functioning", by = "Overall"), data.frame(effect = dydb_female, type = "Functioning", by = "Female"), data.frame(effect = dydb_male, type = "Functioning", by = "Male"), data.frame(effect = dudb, type = "Choice", by = "Overall"), data.frame(effect = dudb_female, type = "Choice", by = "Female"), data.frame(effect = dudb_male, type = "Choice", by = "Male"), data.frame(effect = dcdb, type = "Capabilities", by = "Overall"), data.frame(effect = dcdb_female, type = "Capabilities", by = "Female"), data.frame(effect = dcdb_male, type = "Capabilities", by = "Male")) return(all) }
/functions.R
no_license
LendieFollett/Cash-and-Capabilities
R
false
false
10,221
r
#Gelman standardization gel_stand <- function(x){(x - mean(x))/(2*sd(x))} #Inverse hyperbolic sine transformation ihs_trans <- function(x){log(x + sqrt(x^2 + 1))} #In terms of standard deviation of un-treated y_stand <- function(x, data){ x2 <-x[data$treated == 0] (x - mean(x2,na.rm = TRUE))/(sd(x2,na.rm = TRUE)) } ##########do_sampling()------------- #y = column of responses (including NA for missings, pre-transformed if needed) #X = matrix of predictor variables, pre-standardized #hh_id = household id vector (should be same dimension as y) #loc_id = location id vector (" ") do_sampling <- function(y, X, X_cntr, hh_id, loc_id,kappa,file){ #compile BSFA model incorporating missingness mechanism compiled_selection_model <- stan_model(file) f <- y index_miss <- which(is.na(f)) N_miss <- length(index_miss) #Missingness - empirical Bayes R <- as.numeric(is.na(f)) m1 <- lm(f~ X) #some of f elements are NA, X is complete imputed_f <- f #impute missing f values based on observed relationship with X imputed_f[index_miss] <- predict(m1, newdata = data.frame(X))[index_miss] #model linking P(missing) to y and X ## (needed imputed f to do this) ML <- glm(R ~ imputed_f , family = binomial) phi_prior_mean <- coef(ML)[1:2] phi_prior_var <- vcov(ML) #replace y values with missing indicator #these values will be replaced in Stan with parameter values to be sampled #(so they will get a capability set too) f[index_miss] <- -99 data.list <- list(N = length(f), todo = which(X[,"treated"] == 1 & X[,"year"] == 1), N2 = length(which(X[,"treated"] == 1 & X[,"year"] == 1)), F = length(unique(hh_id)), L = length(unique(loc_id)), K = ncol(X), hh = as.numeric(as.factor(hh_id)), loc = as.numeric(as.factor(loc_id)), f = f, X = X, X_cntr=X_cntr, R = R, N_miss = N_miss, index_miss = index_miss, phi_prior_mean = phi_prior_mean, phi_prior_var = phi_prior_var, kappa = kappa) #set reasonable initial values initc <- list(gamma1 = -1, gamma2 = rep(0, 7), mu_a = coef(m1)[1], beta = coef(m1)[-1], sigma_a = .5*mean(m1$residuals^2)^(.5), sigma_a2 = .5*mean(m1$residuals^2), sigma_v = .5*mean(m1$residuals^2)^(.5), sigma_v2 = .5*mean(m1$residuals^2), sigma_l = .5*mean(m1$residuals^2)^(.5), sigma_l2 =.5*mean(m1$residuals^2), u =.5*(max(imputed_f)-imputed_f) + .01, #approx. 50 percent of distance from max rho = .9, f_imp = rep(mean(imputed_f), N_miss), phi = phi_prior_mean) inits <- list(initc,initc,initc,initc) #Sample with rstan sm_sampled <- sampling(compiled_selection_model, data = data.list, chains = 4, iter =10000, warmup = 5000, pars = par_keep, include=TRUE, init = inits, control = list(adapt_delta = 0.9)) return(sm_sampled) } ##########plot_cs()----------- #sampled = stanfit object #y = response variable - transformed if applicable #response = character string of y variable (just for labels) #data = kenya data frame #backtrans = logical TRUE if on original (untransformed) scale plot_cs <- function(sampled, y, response, data, backtrans = FALSE){ #draws from posterior predictive (CS) f_pred_trt <- rstan::extract(sampled, "f_pred")%>% data.frame() #draws from counterfactual posterior predictive (CS) f_pred_cntr <- rstan::extract(sampled, "f_pred_cntr")%>% data.frame() if (backtrans == TRUE) { f_pred_trt <- exp(f_pred_trt) f_pred_cntr<- exp(f_pred_cntr) y <- exp(y) } d <- data %>% subset(year == 1 & treated == 1) data.frame(f =y[data$year == 1 & data$treated == 1], missing = is.na(y[data$year == 1 & data$treated == 1]), sex = factor(d$head_sex, levels = c(0,1), labels = c("Male", "Female")), lb_trt = apply(f_pred_trt , 2, "quantile", c(0.05)), ub_trt = apply(f_pred_trt , 2, "quantile", c(0.95)), lb_notrt = apply(f_pred_cntr, 2, "quantile", c(0.05)), ub_notrt = apply(f_pred_cntr, 2, "quantile", c(0.95))) %>% arrange(sex, ub_notrt)%>% mutate(id = c(1:sum(d$head_sex == 0), 1:sum(d$head_sex == 1))) %>% #subset(missing == FALSE)%>% ggplot() + geom_errorbar(aes(x=id, ymin=lb_trt, ymax=ub_trt), colour = "grey50") + geom_line(aes(x=id, y=lb_notrt )) + geom_line(aes(x=id, y=ub_notrt )) + labs(x = "Household ID", y = response)+ geom_point(aes(x = id, y =f),size = .5,alpha = I(.3), colour ="black")+ facet_wrap(.~sex, scales = "free_x")+ theme(plot.title = element_text(hjust = 0.5)) + scale_colour_grey() #+scale_y_continuous(limits = c(-4, 4)) } #########plot_cs_agg()------- #same arguments as plot_cs() plot_cs_agg <- function(sampled, y, response, data, backtrans = FALSE){ f_pred_trt <- rstan::extract(sampled, "f_pred")%>% data.frame() f_pred_cntr <- rstan::extract(sampled, "f_pred_cntr")%>% data.frame() if (backtrans == TRUE) { f_pred_trt <- exp(f_pred_trt) f_pred_cntr<- exp(f_pred_cntr) y <- exp(y) } d <- data %>% subset(year == 1 & treated == 1) data.frame(f =y[data$year == 1 & data$treated == 1], missing = is.na(y[data$year == 1 & data$treated == 1]), sex = factor(d$head_sex, levels = c(0,1), labels = c("Male", "Female")), lb_trt = apply(f_pred_trt , 2, "quantile", c(0.05)), ub_trt = apply(f_pred_trt , 2, "quantile", c(0.95)), lb_notrt = apply(f_pred_cntr, 2, "quantile", c(0.05)), ub_notrt = apply(f_pred_cntr, 2, "quantile", c(0.95))) %>% arrange( ub_notrt)%>% mutate(id = c(1:length(d$head_sex))) %>% #subset(missing == FALSE)%>% ggplot() + geom_errorbar(aes(x=id, ymin=lb_trt, ymax=ub_trt), colour = "grey50") + geom_line(aes(x=id, y=lb_notrt )) + geom_line(aes(x=id, y=ub_notrt )) + labs(x = "Household ID", y = response)+ geom_point(aes(x = id, y =f),size = .5,alpha = I(.3), colour ="black")+ theme(plot.title = element_text(hjust = 0.5)) + scale_colour_grey() #+scale_y_continuous(limits = c(-4, 4)) } #########derivatives() : posterior draws from quantities in Eq (18)------- #full_X: X matrix #samples = stanfit object derivatives <- function(full_X, samples){ full_X_mean <- c(1,apply(full_X, 2, mean))[1:8] full_X_mean[c("treated", "head_sex", "year", "treated_year", "treated_sex", "year_sex", "treated_year_sex")] <- c(1, full_X_mean["head_sex"], 1, 1*1, 1*full_X_mean["head_sex"],full_X_mean["head_sex"]*1, full_X_mean["head_sex"]*1*1) female_X_mean <- c(1,apply(full_X, 2, mean))[1:8] female_X_mean[c("treated", "head_sex", "year", "treated_year", "treated_sex", "year_sex", "treated_year_sex")] <- c(1, 1, 1, 1*1, 1*1,1*1, 1*1*1) male_X_mean <- c(1,apply(full_X, 2, mean))[1:8] male_X_mean[c("treated", "head_sex", "year", "treated_year", "treated_sex", "year_sex", "treated_year_sex")] <- c(1, 0, 1, 1*1, 1*0,0*1, 0*1*1) gamma_samps <- do.call("cbind", rstan::extract(samples, par = c("gamma1","gamma2"))) rho_samps <- rstan::extract(samples, par = c("rho"))[[1]] #CHOICE effect #overall effect temp1 <- apply(gamma_samps, 1, function(x){exp(x%*%full_X_mean)}) #exp(X*gamma) = lambda(1) temp2 <- exp(-apply(gamma_samps[,c(5,8)], 1, function(x){x%*%full_X_mean[c(5,8)]})) # 1/exp(g2 + g3*.6244) dudb <- temp1*(temp2-1)*rho_samps #female effect temp1 <- apply(gamma_samps, 1, function(x){exp(x%*%female_X_mean)}) #exp(X*gamma) = lambda(1) temp2 <- exp(-apply(gamma_samps[,c(5,8)], 1, function(x){x%*%female_X_mean[c(5,8)]})) # 1/exp(g2 + g3*1) dudb_female <- temp1*(temp2-1)*rho_samps #male effect temp1 <- apply(gamma_samps, 1, function(x){exp(x%*%male_X_mean)}) #exp(X*gamma) = lambda(1) temp2 <- exp(-apply(gamma_samps[,c(5,8)], 1, function(x){x%*%male_X_mean[c(5,8)]})) # 1/exp(g2 + g3*0) dudb_male <- temp1*(temp2-1)*rho_samps rm(gamma_samps) rm(rho_samps) #CAPABILITIES effect beta_samps <- do.call("cbind", rstan::extract(samples, par = c("beta"))) #overall effect dcdb <- beta_samps[,4] + beta_samps[,7]*full_X_mean["head_sex"] #female effect dcdb_female <- beta_samps[,4] + beta_samps[,7]*1 #male effect dcdb_male <- beta_samps[,4] + beta_samps[,7]*0 rm(beta_samps) #FUNCTIONING effect dydb <- dcdb + dudb dydb_female <- dcdb_female + dudb_female dydb_male <- dcdb_male + dudb_male all <- rbind(data.frame(effect = dydb, type = "Functioning", by = "Overall"), data.frame(effect = dydb_female, type = "Functioning", by = "Female"), data.frame(effect = dydb_male, type = "Functioning", by = "Male"), data.frame(effect = dudb, type = "Choice", by = "Overall"), data.frame(effect = dudb_female, type = "Choice", by = "Female"), data.frame(effect = dudb_male, type = "Choice", by = "Male"), data.frame(effect = dcdb, type = "Capabilities", by = "Overall"), data.frame(effect = dcdb_female, type = "Capabilities", by = "Female"), data.frame(effect = dcdb_male, type = "Capabilities", by = "Male")) return(all) }
#' Spatial Bayesian quantile regression models using predictive processes #' #' This function estimates a spatial Bayesian quantile regression model #' The Asymmetric Laplace Predictive Process (ALPP) is considered to fit this #' spatial model. #' #' @param formula a formula object, with the response on the left of a ~ #' operator, and the terms, separated by + operators, on the right. #' @param tau Quantile of interest. #' @param data A data.frame from which to find the variables defined in the #' formula #' @param itNum Number of iterations. #' @param thin Thinning parameter. Default value is 1. #' @param betaValue Initial values for the parameter beta for the continuous #' part. #' @param sigmaValue Initial value for the scale parameter. #' @param spCoord1 Name of the first spatial coordinate, as character. #' @param spCoord2 Name of the second spatial coordinate, as character. #' @param lambdaVec Vector of lambdas to be used in the estimation process. #' @param lambda Initial value for the parameter in the covariance matrix. #' @param shapeL Shape hyperparameter value for Gamma prior for the lambda #' parameter. #' @param rateL Rate hyperparameter value for Gamma prior for the lambda #' parameter. #' @param tuneP Tuning parameter for the Metropolis-Hastings algorithm to draw #' samples from the posterior distribution of kappa. #' @param m Number of knots. #' @param indexes Vector with indexes from the knots. These are randomly #' selected given the integer m. #' @param alpha Value between 0 and 1 of the pure error variance in the #' covariance matrix. Default is 0.5. #' @param tuneA Tuning parameter for the Metropolis_Hastings algorithm to draw #' samples from the posterior distribution of alpha. #' @param priorVar Value that multiplies an identity matrix in the elicition #' process of the prior variance of the regression parameters. #' @param refresh Interval between printing a message during the iteration #' process. Default is set to 100. #' @param quiet If TRUE, the default, it does not print messages to check if #' the MCMC is actually updating. If FALSE, it will use the value of refresh #' to print messages to control the iteration process. #' @param jitter Ammount of jitter added to help in the process for inverting #' the covariance matrix. Default is 1e-10. #' @param includeAlpha If TRUE, the default, the model will include the alpha #' parameter. If FALSE, alpha is set to zero for all draws of the chain. #' @param tuneV Tuning parameter to the multiple-try Metropolis to sample for #' the posterior distribution of the latent variables. Default value is 0.5. #' @param kMT Integer, number of Metropolis samples in the multiple-try #' Metropolis. Default value is 5. #' @param discLambda use discretization for the lambda parameter #' @return A list with the chains of all parameters of interest. #' @references Lum and Gelfand (2012) - Spatial Quantile Multiple Regression #' Using the Asymmetric Laplace process. Bayesian Analysis. #' @useDynLib baquantreg #' @examples #' set.seed(1) sppBQR <- function(formula, tau = 0.5, data, itNum, thin=1, betaValue = NULL, sigmaValue=1, spCoord1, spCoord2, lambdaVec, lambda = sample(lambdaVec, 1), shapeL = 1, rateL = 50, tuneP = 1, m, indexes = sample((1:dim(data)[1]-1), size = m), alpha = 0.5, tuneA = 1e3, priorVar = 100, refresh = 100, quiet = T, jitter = 1e-10, includeAlpha = TRUE, tuneV = 0.5, kMT = 5, discLambda = FALSE){ y <- as.numeric(stats::model.extract(stats::model.frame(formula, data), 'response')) X <- stats::model.matrix(formula, data) if (is.null(betaValue)) betaValue <- rep(0, dim(X)[2]) output <- list() spatial1 <- data[, spCoord1] spatial2 <- data[, spCoord2] matDist <- outer(spatial1, spatial1, "-")^2 + outer(spatial2, spatial2, "-")^2 output$chains <- lapply(tau, function(a){ sppBayesQR(tau = tau, y = y, X = X, itNum = itNum, thin = thin, betaValue = betaValue, sigmaValue = sigmaValue, matDist = matDist, lambdaVec = lambdaVec, lambda = lambda, shapeL = shapeL, rateL = rateL, tuneP = tuneP, indices = indexes, m = m, alphaValue = alpha, tuneA = tuneA, priorVar = priorVar, quiet = quiet, refresh = refresh, jitter = jitter, includeAlpha = includeAlpha, tuneV = tuneV, kMT = kMT, discLambda = discLambda) }) output$acceptRateKappa <- lapply(output$chains, function(b){ 1-sum(diff(b$LambdaSample)==0)/(itNum-1) }) output$acceptRateAlpha <- lapply(output$chains, function(b){ 1-sum(diff(b$alphaSample)==0)/(itNum-1) }) # output$acceptRateV <- lapply(output$chains, function(b){ # 1-apply(b$vSample, 2, function(bb){ # sum(diff(bb)==0)/length(diff(bb)) # }) # }) output$tau <- tau output$formula <- formula output$data <- data class(output) <- "spBQR" return(output) }
/R/sppBQR.R
no_license
why94nb/baquantreg
R
false
false
5,090
r
#' Spatial Bayesian quantile regression models using predictive processes #' #' This function estimates a spatial Bayesian quantile regression model #' The Asymmetric Laplace Predictive Process (ALPP) is considered to fit this #' spatial model. #' #' @param formula a formula object, with the response on the left of a ~ #' operator, and the terms, separated by + operators, on the right. #' @param tau Quantile of interest. #' @param data A data.frame from which to find the variables defined in the #' formula #' @param itNum Number of iterations. #' @param thin Thinning parameter. Default value is 1. #' @param betaValue Initial values for the parameter beta for the continuous #' part. #' @param sigmaValue Initial value for the scale parameter. #' @param spCoord1 Name of the first spatial coordinate, as character. #' @param spCoord2 Name of the second spatial coordinate, as character. #' @param lambdaVec Vector of lambdas to be used in the estimation process. #' @param lambda Initial value for the parameter in the covariance matrix. #' @param shapeL Shape hyperparameter value for Gamma prior for the lambda #' parameter. #' @param rateL Rate hyperparameter value for Gamma prior for the lambda #' parameter. #' @param tuneP Tuning parameter for the Metropolis-Hastings algorithm to draw #' samples from the posterior distribution of kappa. #' @param m Number of knots. #' @param indexes Vector with indexes from the knots. These are randomly #' selected given the integer m. #' @param alpha Value between 0 and 1 of the pure error variance in the #' covariance matrix. Default is 0.5. #' @param tuneA Tuning parameter for the Metropolis_Hastings algorithm to draw #' samples from the posterior distribution of alpha. #' @param priorVar Value that multiplies an identity matrix in the elicition #' process of the prior variance of the regression parameters. #' @param refresh Interval between printing a message during the iteration #' process. Default is set to 100. #' @param quiet If TRUE, the default, it does not print messages to check if #' the MCMC is actually updating. If FALSE, it will use the value of refresh #' to print messages to control the iteration process. #' @param jitter Ammount of jitter added to help in the process for inverting #' the covariance matrix. Default is 1e-10. #' @param includeAlpha If TRUE, the default, the model will include the alpha #' parameter. If FALSE, alpha is set to zero for all draws of the chain. #' @param tuneV Tuning parameter to the multiple-try Metropolis to sample for #' the posterior distribution of the latent variables. Default value is 0.5. #' @param kMT Integer, number of Metropolis samples in the multiple-try #' Metropolis. Default value is 5. #' @param discLambda use discretization for the lambda parameter #' @return A list with the chains of all parameters of interest. #' @references Lum and Gelfand (2012) - Spatial Quantile Multiple Regression #' Using the Asymmetric Laplace process. Bayesian Analysis. #' @useDynLib baquantreg #' @examples #' set.seed(1) sppBQR <- function(formula, tau = 0.5, data, itNum, thin=1, betaValue = NULL, sigmaValue=1, spCoord1, spCoord2, lambdaVec, lambda = sample(lambdaVec, 1), shapeL = 1, rateL = 50, tuneP = 1, m, indexes = sample((1:dim(data)[1]-1), size = m), alpha = 0.5, tuneA = 1e3, priorVar = 100, refresh = 100, quiet = T, jitter = 1e-10, includeAlpha = TRUE, tuneV = 0.5, kMT = 5, discLambda = FALSE){ y <- as.numeric(stats::model.extract(stats::model.frame(formula, data), 'response')) X <- stats::model.matrix(formula, data) if (is.null(betaValue)) betaValue <- rep(0, dim(X)[2]) output <- list() spatial1 <- data[, spCoord1] spatial2 <- data[, spCoord2] matDist <- outer(spatial1, spatial1, "-")^2 + outer(spatial2, spatial2, "-")^2 output$chains <- lapply(tau, function(a){ sppBayesQR(tau = tau, y = y, X = X, itNum = itNum, thin = thin, betaValue = betaValue, sigmaValue = sigmaValue, matDist = matDist, lambdaVec = lambdaVec, lambda = lambda, shapeL = shapeL, rateL = rateL, tuneP = tuneP, indices = indexes, m = m, alphaValue = alpha, tuneA = tuneA, priorVar = priorVar, quiet = quiet, refresh = refresh, jitter = jitter, includeAlpha = includeAlpha, tuneV = tuneV, kMT = kMT, discLambda = discLambda) }) output$acceptRateKappa <- lapply(output$chains, function(b){ 1-sum(diff(b$LambdaSample)==0)/(itNum-1) }) output$acceptRateAlpha <- lapply(output$chains, function(b){ 1-sum(diff(b$alphaSample)==0)/(itNum-1) }) # output$acceptRateV <- lapply(output$chains, function(b){ # 1-apply(b$vSample, 2, function(bb){ # sum(diff(bb)==0)/length(diff(bb)) # }) # }) output$tau <- tau output$formula <- formula output$data <- data class(output) <- "spBQR" return(output) }
library("BSgenome.Hsapiens.UCSC.hg38", lib.loc="/Library/Frameworks/R.framework/Versions/3.4/Resources/library") library("deconstructSigs", lib.loc="/Library/Frameworks/R.framework/Versions/3.4/Resources/library") Test8.1 <- as.data.frame(Test8) sigs.input = mut.to.sigs.input(mut.ref = Test8.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) #Error in .Call2("solve_user_SEW", refwidths, start, end, width, translate.negative.coord, : #solving row 1196: 'allow.nonnarrowing' is FALSE and the supplied start (242281689) is > refwidth + 1 Test9.1 <- as.data.frame(Test9) sigs.input = mut.to.sigs.input(mut.ref = Test9.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) #Error in .Call2("solve_user_SEW", refwidths, start, end, width, translate.negative.coord, : #solving row 1196: 'allow.nonnarrowing' is FALSE and the supplied start (242820456) is > refwidth + 1 Test10.1 <- as.data.frame(Test10) sigs.input = mut.to.sigs.input(mut.ref = Test10.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test11.1 <- as.data.frame(Test11) sigs.input = mut.to.sigs.input(mut.ref = Test11.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test12.1 <- as.data.frame(Test12) sigs.input = mut.to.sigs.input(mut.ref = Test12.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test13.1 <- as.data.frame(Test13) sigs.input = mut.to.sigs.input(mut.ref = Test13.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test14.1 <- as.data.frame(Test14) sigs.input = mut.to.sigs.input(mut.ref = Test14.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test15.1 <- as.data.frame(Test15) sigs.input = mut.to.sigs.input(mut.ref = Test15.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test16.1 <- as.data.frame(Test16) sigs.input = mut.to.sigs.input(mut.ref = Test16.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test17.1 <- as.data.frame(Test17) sigs.input = mut.to.sigs.input(mut.ref = Test16.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test18.1 <- as.data.frame(Test18) sigs.input = mut.to.sigs.input(mut.ref = Test18.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test19.1 <- as.data.frame(Test19) sigs.input = mut.to.sigs.input(mut.ref = Test19.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test20.1 <- as.data.frame(Test20) sigs.input = mut.to.sigs.input(mut.ref = Test20.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test21.1 <- as.data.frame(Test21) sigs.input = mut.to.sigs.input(mut.ref = Test21.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test22.1 <- as.data.frame(Test22) sigs.input = mut.to.sigs.input(mut.ref = Test22.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test23.1 <- as.data.frame(Test23) sigs.input = mut.to.sigs.input(mut.ref = Test23.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test24.1 <- as.data.frame(Test24) sigs.input = mut.to.sigs.input(mut.ref = Test24.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) ## Warning messages: Check ref bases -- not all matchcontex: MB-REC-01:chr1:725841:T:G, MB-REC-01:chr1:815736:A:G, MB-REC-01:chr1:823634:C:T, MB-REC-01:chr1:2049281:T:C, MB-REC-01:chr1:2852148:T:C, MB-REC-01:chr1:5155501:T:A, MB-REC-01:chr1:5225280:G:T, MB-REC-01:chr1:5395209:G:C, MB-REC-01:chr1:5595097:T:G, MB-REC-01:chr1:6446728:C:G, MB-REC-01:chr1:6563220:C:A, MB-REC-01:chr1:7300718:A:G, MB-REC-01:chr1:9013537:G:T, MB-REC-01:chr1:9155756:C:G, MB-REC-01:chr1:10568900:A:G, MB-REC-01:chr1:10876140:G:A, MB-REC-01:chr1:10887712:G:T, MB-REC-01:chr1:11617270:A:T, MB-REC-01:chr1:12786246:C:A, MB-REC-01:chr1:12895034:C:G, MB-REC-01:chr1:14960380:C:A, MB-REC-01:chr1:15499803:C:T, MB-REC-01:chr1:16870506:G:A, MB-REC-01:chr1:16958388:G:T, MB-REC-01:chr1:17045759:A:G, MB-REC-01:chr1:18648056:C:T, MB-REC-01:chr1:19075392:C:T, MB-REC-01:chr1:19435323:T:C, MB-REC-01:chr1:20039618:G:A, MB-REC-01:chr1:23589077:C:T, MB-REC-01:chr1:25343632:G:A, MB-REC-01:chr1:25751563:C:A, MB-REC-01:chr1:25967685:G:A, MB-REC-01:chr1:2 [... truncated]
/612018_Chromsome_pos_Hg38.R
no_license
aditibagchi/Reading_files_R
R
false
false
4,959
r
library("BSgenome.Hsapiens.UCSC.hg38", lib.loc="/Library/Frameworks/R.framework/Versions/3.4/Resources/library") library("deconstructSigs", lib.loc="/Library/Frameworks/R.framework/Versions/3.4/Resources/library") Test8.1 <- as.data.frame(Test8) sigs.input = mut.to.sigs.input(mut.ref = Test8.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) #Error in .Call2("solve_user_SEW", refwidths, start, end, width, translate.negative.coord, : #solving row 1196: 'allow.nonnarrowing' is FALSE and the supplied start (242281689) is > refwidth + 1 Test9.1 <- as.data.frame(Test9) sigs.input = mut.to.sigs.input(mut.ref = Test9.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) #Error in .Call2("solve_user_SEW", refwidths, start, end, width, translate.negative.coord, : #solving row 1196: 'allow.nonnarrowing' is FALSE and the supplied start (242820456) is > refwidth + 1 Test10.1 <- as.data.frame(Test10) sigs.input = mut.to.sigs.input(mut.ref = Test10.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test11.1 <- as.data.frame(Test11) sigs.input = mut.to.sigs.input(mut.ref = Test11.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test12.1 <- as.data.frame(Test12) sigs.input = mut.to.sigs.input(mut.ref = Test12.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test13.1 <- as.data.frame(Test13) sigs.input = mut.to.sigs.input(mut.ref = Test13.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test14.1 <- as.data.frame(Test14) sigs.input = mut.to.sigs.input(mut.ref = Test14.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test15.1 <- as.data.frame(Test15) sigs.input = mut.to.sigs.input(mut.ref = Test15.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test16.1 <- as.data.frame(Test16) sigs.input = mut.to.sigs.input(mut.ref = Test16.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test17.1 <- as.data.frame(Test17) sigs.input = mut.to.sigs.input(mut.ref = Test16.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test18.1 <- as.data.frame(Test18) sigs.input = mut.to.sigs.input(mut.ref = Test18.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test19.1 <- as.data.frame(Test19) sigs.input = mut.to.sigs.input(mut.ref = Test19.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test20.1 <- as.data.frame(Test20) sigs.input = mut.to.sigs.input(mut.ref = Test20.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test21.1 <- as.data.frame(Test21) sigs.input = mut.to.sigs.input(mut.ref = Test21.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test22.1 <- as.data.frame(Test22) sigs.input = mut.to.sigs.input(mut.ref = Test22.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test23.1 <- as.data.frame(Test23) sigs.input = mut.to.sigs.input(mut.ref = Test23.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) Test24.1 <- as.data.frame(Test24) sigs.input = mut.to.sigs.input(mut.ref = Test24.1, sample.id = "Sample", chr = "chr", pos = "pos", ref = "ref", alt = "alt", bsg = BSgenome.Hsapiens.UCSC.hg38) ## Warning messages: Check ref bases -- not all matchcontex: MB-REC-01:chr1:725841:T:G, MB-REC-01:chr1:815736:A:G, MB-REC-01:chr1:823634:C:T, MB-REC-01:chr1:2049281:T:C, MB-REC-01:chr1:2852148:T:C, MB-REC-01:chr1:5155501:T:A, MB-REC-01:chr1:5225280:G:T, MB-REC-01:chr1:5395209:G:C, MB-REC-01:chr1:5595097:T:G, MB-REC-01:chr1:6446728:C:G, MB-REC-01:chr1:6563220:C:A, MB-REC-01:chr1:7300718:A:G, MB-REC-01:chr1:9013537:G:T, MB-REC-01:chr1:9155756:C:G, MB-REC-01:chr1:10568900:A:G, MB-REC-01:chr1:10876140:G:A, MB-REC-01:chr1:10887712:G:T, MB-REC-01:chr1:11617270:A:T, MB-REC-01:chr1:12786246:C:A, MB-REC-01:chr1:12895034:C:G, MB-REC-01:chr1:14960380:C:A, MB-REC-01:chr1:15499803:C:T, MB-REC-01:chr1:16870506:G:A, MB-REC-01:chr1:16958388:G:T, MB-REC-01:chr1:17045759:A:G, MB-REC-01:chr1:18648056:C:T, MB-REC-01:chr1:19075392:C:T, MB-REC-01:chr1:19435323:T:C, MB-REC-01:chr1:20039618:G:A, MB-REC-01:chr1:23589077:C:T, MB-REC-01:chr1:25343632:G:A, MB-REC-01:chr1:25751563:C:A, MB-REC-01:chr1:25967685:G:A, MB-REC-01:chr1:2 [... truncated]
### function for estimating the MTMM parameters using ASREML, to get passed on to a non-ASREML programm !! #library(lattice) #library(asreml) #library(msm) #library(nadiv) #source('emma.r') mtmm_estimates<-function(Y,k=2,l=3,K,method='default',only.vca=FALSE) { name<-paste(colnames(Y)[k],colnames(Y)[l],'mtmm_estimates.rda',sep='_') Y<-Y[,c(1,k,l)] rm(k,l) if(anyDuplicated(Y[,1])>0) { cat('duplicated ecotypes detected','\n') stopifnot(anyDuplicated(Y[,1])==0)} Y_<-na.omit(Y) Y<-Y_[which(Y_[,1]%in%rownames(K)),] cat('analysis performed on',nrow(Y),'ecotypes',sep=' ') Y1<-(Y[,2]) Y2<-(Y[,3]) names(Y1)<-Y[,1] names(Y2)<-Y[,1] # ecot_id<-as.integer(names(Y1)) ecot_id<-names(Y1) K<-as.matrix(K[which(rownames(K)%in%names(Y1)),which(colnames(K)%in%names(Y1))]) n<-nrow(Y) # combining the traits Y_ok<-c(Y1,Y2) #environment Env<-c(rep(0,n),rep(1,n)) #standardize kinship K_stand<-(n-1)/sum((diag(n)-matrix(1,n,n)/n)*K)*K K_inv<<-solve(K_stand) ############# #ANALYSIS ### #####Y1 Xo<-rep(1,n) ex<-as.matrix(Xo) null1<<-emma.REMLE(Y1,ex,K_stand) herit1<<-null1$vg/(null1$vg+null1$ve) null2<<-emma.REMLE(Y2,ex,K_stand) herit2<<-null2$vg/(null2$vg+null2$ve) #### if single analysis is to include !:. ## ### attention if exclude ==FALSE ncol(out_models1)<> ncol(out_models2) ! ##### START MTMM ##### #intercept Xo<-rep(1,2*n) # preparing the data data_asr<-data.frame(ecot_id=c(ecot_id,ecot_id),Env=Env,Y_ok=Y_ok) data_asr$ecot_id<-as.factor(data_asr$ecot_id) data_asr$Env<-as.factor(data_asr$Env) ## setting starting values sigma1<<-null1$vg sigma2<<-null2$vg rho<<-cor(Y1,Y2)/(sqrt(herit1)*sqrt(herit2)) ###set borders for rho between -1 and 1 if (rho>0.98) {rho<-0.98 }else { if (rho< -0.98) {rho<--0.98}} #alpha_e<-rho*sqrt((null1$vg+null1$ve)*(null2$vg+null2$ve)) alpha<<-rho*sqrt(null1$vg*null2$vg) beta2<<-cor(Y1,Y2)*sqrt(null1$ve*null2$ve) alpha2<<-cor(Y1,Y2)*sqrt(null1$vg*null2$vg) if ( method == "default" ) { mixmod.asr<-asreml(fixed=Y_ok~Env,random=~us(Env,init=c(sigma1,alpha,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~at(Env,init=c(null1$ve,null2$ve)):units,data=data_asr,maxit=50) varcov<-matrix(data=c(summary(mixmod.asr)$varcomp$component[1:2],summary(mixmod.asr)$varcomp$component[2:3]),nrow=2,ncol=2) ve<-matrix(data=c(summary(mixmod.asr)$varcomp$component[4],rep(0,2),summary(mixmod.asr)$varcomp$component[5]),nrow=2,ncol=2) } else if ( method == "errorcorrelation" ) { ### including autocorrelation mixmod.asr<-asreml(fixed=Y_ok~Env,random=~us(Env,init=c(sigma1,alpha2,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~us(Env,init=c(null1$ve,beta2,null2$ve)):id(ecot_id),data=data_asr,maxit=100) varcov<-matrix(data=c(summary(mixmod.asr)$varcomp$component[1:2],summary(mixmod.asr)$varcomp$component[2:3]),nrow=2,ncol=2) ve<-matrix(data=c(summary(mixmod.asr)$varcomp$component[5:6],summary(mixmod.asr)$varcomp$component[6:7]),nrow=2,ncol=2) } rho_g<-varcov[1,2]/sqrt(varcov[1,1]*varcov[2,2]) rho_e<-ve[1,2]/sqrt(ve[1,1]*ve[2,2]) rho_p<-(varcov[1,2]+ve[1,2])/sqrt((varcov[1,1]+ve[1,1])*(varcov[2,2]+ve[2,2])) pearson<-cor(Y1,Y2) heriti1<-varcov[1,1]/(varcov[1,1]+ve[1,1]) heriti2<-varcov[2,2]/(varcov[2,2]+ve[2,2]) G<-varcov[1,2] G1<-varcov[1,1]-varcov[1,2] G2<-varcov[2,2]-varcov[1,2] E<-ve[1,1]+ve[2,2] EE<-ve[1,2] tot_var<-G+G1+G2+E+EE var_G<-G/tot_var var_GE<-(G1+G2)/tot_var var_E<-E/tot_var var_EE<-EE/tot_var hallo<-mixmod.asr if ( method == "default" ) { werte<-summary(hallo)$varcomp$component [1:3] werte2<-summary(hallo)$varcomp$component [4:5] covG<-aiFun(hallo)[1:3,1:3] covH1<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[1,1],aiFun(hallo)[4,1],aiFun(hallo)[4,1],aiFun(hallo)[4,4])) covH2<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[3,3],aiFun(hallo)[5,3],aiFun(hallo)[5,3],aiFun(hallo)[5,5])) covP<-aiFun(hallo) covG[upper.tri(covG)==T]<-covG[lower.tri(covG)==T] covP[upper.tri(covP)==T]<-covP[lower.tri(covP)==T] null.g<-asreml(fixed=Y_ok~Env,random=~idh(Env,init=c(sigma1,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~at(Env,init=c(null1$ve,null2$ve)):units,data=data_asr,maxit=50) ap<-hallo$loglik cp<-null.g$loglik se_g<-deltamethod( ~ x2/sqrt(x1*x3),werte,covG) p_g<-1-pchisq(2*(ap-cp),1) se_e<-NA p_e<-NA se_p<-deltamethod( ~ (x2)/sqrt((x1+x4)*(x3+x5)), c(werte,werte2),covP) se_h1<-deltamethod( ~ x1/(x1+x2),c(werte[1],werte2[1]),covH1) se_h2<-deltamethod( ~ x1/(x1+x2),c(werte[3],werte2[2]),covH2) } else if ( method == "errorcorrelation" ) { werte<-summary(hallo)$varcomp$component [1:3] werte2<-summary(hallo)$varcomp$component [5:7] covG<-aiFun(hallo)[1:3,1:3] covE<-aiFun(hallo)[5:7,5:7] covH1<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[1,1],aiFun(hallo)[5,1],aiFun(hallo)[5,1],aiFun(hallo)[5,5])) covH2<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[3,3],aiFun(hallo)[7,3],aiFun(hallo)[7,3],aiFun(hallo)[7,7])) covP<-aiFun(hallo)[-4,-4] covG[upper.tri(covG)==T]<-covG[lower.tri(covG)==T] covE[upper.tri(covE)==T]<-covE[lower.tri(covE)==T] covP[upper.tri(covP)==T]<-covP[lower.tri(covP)==T] null.e<-asreml(fixed=Y_ok~Env,random=~us(Env,init=c(sigma1,alpha2,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~idh(Env,init=c(null1$ve,null2$ve)):id(ecot_id),data=data_asr,maxit=50) null.g<-asreml(fixed=Y_ok~Env,random=~idh(Env,init=c(sigma1,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~us(Env,init=c(null1$ve,beta2,null2$ve)):id(ecot_id),data=data_asr,maxit=50) ap<-hallo$loglik bp<-null.e$loglik cp<-null.g$loglik se_g<-deltamethod( ~ x2/sqrt(x1*x3),werte,covG) p_g<-1-pchisq(2*(ap-cp),1) se_e<-deltamethod( ~ x2/sqrt(x1*x3),werte2,covE) p_e<-1-pchisq(2*(ap-bp),1) se_p<-deltamethod( ~ (x2+x5)/sqrt((x1+x4)*(x3+x6)), c(werte,werte2),covP) se_h1<-deltamethod( ~ x1/(x1+x2),c(werte[1],werte2[1]),covH1) se_h2<-deltamethod( ~ x1/(x1+x2),c(werte[3],werte2[3]),covH2) } correlation<-list(converge=hallo$converge,pearson=pearson,gen_cor=rho_g,SE_gen_cor=se_g,p_gen_cor=p_g,env_cor=rho_e,SE_env_cor=se_e,p_env_cor=p_e,phen_cor=rho_p,SE_phen_cor=se_p,h1_joint=heriti1,SE_h1_joint=se_h1,h2_joint=heriti2,SE_h2_joint=se_h2,var_G=var_G,var_GE=var_GE,var_E=var_E,var_EE=var_EE) #extract variances from asreml output K_comb<-kronecker(varcov,K_stand) rownames(K_comb)<-c(ecot_id,ecot_id) colnames(K_comb)<-c(ecot_id,ecot_id) I_comb<-kronecker(ve,diag(n)) rownames(I_comb)<-rownames(K_comb) colnames(I_comb)<-colnames(K_comb) ### what is this step doing ??? bigK<-K_comb+I_comb M<-solve(chol(bigK)) # scaling of the SNPs to interpret GxE results Y_t<-crossprod(M,Y_ok) cof_t<-crossprod(M,cbind(Xo,Env)) if(only.vca==T) {return(unlist(correlation)) } else { save(n,cof_t,M,Env,correlation,varcov,Y_t,ecot_id,Xo,K_stand,ecot_id,file=name) }}
/scripts/mtmm_estimates.r
no_license
Gregor-Mendel-Institute/mtmm
R
false
false
6,725
r
### function for estimating the MTMM parameters using ASREML, to get passed on to a non-ASREML programm !! #library(lattice) #library(asreml) #library(msm) #library(nadiv) #source('emma.r') mtmm_estimates<-function(Y,k=2,l=3,K,method='default',only.vca=FALSE) { name<-paste(colnames(Y)[k],colnames(Y)[l],'mtmm_estimates.rda',sep='_') Y<-Y[,c(1,k,l)] rm(k,l) if(anyDuplicated(Y[,1])>0) { cat('duplicated ecotypes detected','\n') stopifnot(anyDuplicated(Y[,1])==0)} Y_<-na.omit(Y) Y<-Y_[which(Y_[,1]%in%rownames(K)),] cat('analysis performed on',nrow(Y),'ecotypes',sep=' ') Y1<-(Y[,2]) Y2<-(Y[,3]) names(Y1)<-Y[,1] names(Y2)<-Y[,1] # ecot_id<-as.integer(names(Y1)) ecot_id<-names(Y1) K<-as.matrix(K[which(rownames(K)%in%names(Y1)),which(colnames(K)%in%names(Y1))]) n<-nrow(Y) # combining the traits Y_ok<-c(Y1,Y2) #environment Env<-c(rep(0,n),rep(1,n)) #standardize kinship K_stand<-(n-1)/sum((diag(n)-matrix(1,n,n)/n)*K)*K K_inv<<-solve(K_stand) ############# #ANALYSIS ### #####Y1 Xo<-rep(1,n) ex<-as.matrix(Xo) null1<<-emma.REMLE(Y1,ex,K_stand) herit1<<-null1$vg/(null1$vg+null1$ve) null2<<-emma.REMLE(Y2,ex,K_stand) herit2<<-null2$vg/(null2$vg+null2$ve) #### if single analysis is to include !:. ## ### attention if exclude ==FALSE ncol(out_models1)<> ncol(out_models2) ! ##### START MTMM ##### #intercept Xo<-rep(1,2*n) # preparing the data data_asr<-data.frame(ecot_id=c(ecot_id,ecot_id),Env=Env,Y_ok=Y_ok) data_asr$ecot_id<-as.factor(data_asr$ecot_id) data_asr$Env<-as.factor(data_asr$Env) ## setting starting values sigma1<<-null1$vg sigma2<<-null2$vg rho<<-cor(Y1,Y2)/(sqrt(herit1)*sqrt(herit2)) ###set borders for rho between -1 and 1 if (rho>0.98) {rho<-0.98 }else { if (rho< -0.98) {rho<--0.98}} #alpha_e<-rho*sqrt((null1$vg+null1$ve)*(null2$vg+null2$ve)) alpha<<-rho*sqrt(null1$vg*null2$vg) beta2<<-cor(Y1,Y2)*sqrt(null1$ve*null2$ve) alpha2<<-cor(Y1,Y2)*sqrt(null1$vg*null2$vg) if ( method == "default" ) { mixmod.asr<-asreml(fixed=Y_ok~Env,random=~us(Env,init=c(sigma1,alpha,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~at(Env,init=c(null1$ve,null2$ve)):units,data=data_asr,maxit=50) varcov<-matrix(data=c(summary(mixmod.asr)$varcomp$component[1:2],summary(mixmod.asr)$varcomp$component[2:3]),nrow=2,ncol=2) ve<-matrix(data=c(summary(mixmod.asr)$varcomp$component[4],rep(0,2),summary(mixmod.asr)$varcomp$component[5]),nrow=2,ncol=2) } else if ( method == "errorcorrelation" ) { ### including autocorrelation mixmod.asr<-asreml(fixed=Y_ok~Env,random=~us(Env,init=c(sigma1,alpha2,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~us(Env,init=c(null1$ve,beta2,null2$ve)):id(ecot_id),data=data_asr,maxit=100) varcov<-matrix(data=c(summary(mixmod.asr)$varcomp$component[1:2],summary(mixmod.asr)$varcomp$component[2:3]),nrow=2,ncol=2) ve<-matrix(data=c(summary(mixmod.asr)$varcomp$component[5:6],summary(mixmod.asr)$varcomp$component[6:7]),nrow=2,ncol=2) } rho_g<-varcov[1,2]/sqrt(varcov[1,1]*varcov[2,2]) rho_e<-ve[1,2]/sqrt(ve[1,1]*ve[2,2]) rho_p<-(varcov[1,2]+ve[1,2])/sqrt((varcov[1,1]+ve[1,1])*(varcov[2,2]+ve[2,2])) pearson<-cor(Y1,Y2) heriti1<-varcov[1,1]/(varcov[1,1]+ve[1,1]) heriti2<-varcov[2,2]/(varcov[2,2]+ve[2,2]) G<-varcov[1,2] G1<-varcov[1,1]-varcov[1,2] G2<-varcov[2,2]-varcov[1,2] E<-ve[1,1]+ve[2,2] EE<-ve[1,2] tot_var<-G+G1+G2+E+EE var_G<-G/tot_var var_GE<-(G1+G2)/tot_var var_E<-E/tot_var var_EE<-EE/tot_var hallo<-mixmod.asr if ( method == "default" ) { werte<-summary(hallo)$varcomp$component [1:3] werte2<-summary(hallo)$varcomp$component [4:5] covG<-aiFun(hallo)[1:3,1:3] covH1<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[1,1],aiFun(hallo)[4,1],aiFun(hallo)[4,1],aiFun(hallo)[4,4])) covH2<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[3,3],aiFun(hallo)[5,3],aiFun(hallo)[5,3],aiFun(hallo)[5,5])) covP<-aiFun(hallo) covG[upper.tri(covG)==T]<-covG[lower.tri(covG)==T] covP[upper.tri(covP)==T]<-covP[lower.tri(covP)==T] null.g<-asreml(fixed=Y_ok~Env,random=~idh(Env,init=c(sigma1,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~at(Env,init=c(null1$ve,null2$ve)):units,data=data_asr,maxit=50) ap<-hallo$loglik cp<-null.g$loglik se_g<-deltamethod( ~ x2/sqrt(x1*x3),werte,covG) p_g<-1-pchisq(2*(ap-cp),1) se_e<-NA p_e<-NA se_p<-deltamethod( ~ (x2)/sqrt((x1+x4)*(x3+x5)), c(werte,werte2),covP) se_h1<-deltamethod( ~ x1/(x1+x2),c(werte[1],werte2[1]),covH1) se_h2<-deltamethod( ~ x1/(x1+x2),c(werte[3],werte2[2]),covH2) } else if ( method == "errorcorrelation" ) { werte<-summary(hallo)$varcomp$component [1:3] werte2<-summary(hallo)$varcomp$component [5:7] covG<-aiFun(hallo)[1:3,1:3] covE<-aiFun(hallo)[5:7,5:7] covH1<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[1,1],aiFun(hallo)[5,1],aiFun(hallo)[5,1],aiFun(hallo)[5,5])) covH2<-matrix(nrow=2,ncol=2,data=c(aiFun(hallo)[3,3],aiFun(hallo)[7,3],aiFun(hallo)[7,3],aiFun(hallo)[7,7])) covP<-aiFun(hallo)[-4,-4] covG[upper.tri(covG)==T]<-covG[lower.tri(covG)==T] covE[upper.tri(covE)==T]<-covE[lower.tri(covE)==T] covP[upper.tri(covP)==T]<-covP[lower.tri(covP)==T] null.e<-asreml(fixed=Y_ok~Env,random=~us(Env,init=c(sigma1,alpha2,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~idh(Env,init=c(null1$ve,null2$ve)):id(ecot_id),data=data_asr,maxit=50) null.g<-asreml(fixed=Y_ok~Env,random=~idh(Env,init=c(sigma1,sigma2)):giv(ecot_id),ginverse=list(ecot_id=K_inv),rcov=~us(Env,init=c(null1$ve,beta2,null2$ve)):id(ecot_id),data=data_asr,maxit=50) ap<-hallo$loglik bp<-null.e$loglik cp<-null.g$loglik se_g<-deltamethod( ~ x2/sqrt(x1*x3),werte,covG) p_g<-1-pchisq(2*(ap-cp),1) se_e<-deltamethod( ~ x2/sqrt(x1*x3),werte2,covE) p_e<-1-pchisq(2*(ap-bp),1) se_p<-deltamethod( ~ (x2+x5)/sqrt((x1+x4)*(x3+x6)), c(werte,werte2),covP) se_h1<-deltamethod( ~ x1/(x1+x2),c(werte[1],werte2[1]),covH1) se_h2<-deltamethod( ~ x1/(x1+x2),c(werte[3],werte2[3]),covH2) } correlation<-list(converge=hallo$converge,pearson=pearson,gen_cor=rho_g,SE_gen_cor=se_g,p_gen_cor=p_g,env_cor=rho_e,SE_env_cor=se_e,p_env_cor=p_e,phen_cor=rho_p,SE_phen_cor=se_p,h1_joint=heriti1,SE_h1_joint=se_h1,h2_joint=heriti2,SE_h2_joint=se_h2,var_G=var_G,var_GE=var_GE,var_E=var_E,var_EE=var_EE) #extract variances from asreml output K_comb<-kronecker(varcov,K_stand) rownames(K_comb)<-c(ecot_id,ecot_id) colnames(K_comb)<-c(ecot_id,ecot_id) I_comb<-kronecker(ve,diag(n)) rownames(I_comb)<-rownames(K_comb) colnames(I_comb)<-colnames(K_comb) ### what is this step doing ??? bigK<-K_comb+I_comb M<-solve(chol(bigK)) # scaling of the SNPs to interpret GxE results Y_t<-crossprod(M,Y_ok) cof_t<-crossprod(M,cbind(Xo,Env)) if(only.vca==T) {return(unlist(correlation)) } else { save(n,cof_t,M,Env,correlation,varcov,Y_t,ecot_id,Xo,K_stand,ecot_id,file=name) }}
\name{Importance} \alias{Importance} \title{ Measure input importance (including sensitivity analysis) given a supervised data mining model. } \description{ Measure input importance (including sensitivity analysis) given a supervised data mining model. } \usage{ Importance(M, data, RealL = 7, method = "1D-SA", measure = "AAD", sampling = "regular", baseline = "mean", responses = TRUE, outindex = NULL, task = "default", PRED = NULL, interactions = NULL, Aggregation = -1, LRandom = -1, MRandom = "discrete", Lfactor = FALSE) } \arguments{ \item{M}{fitted model, typically is the object returned by \code{\link{fit}}. Can also be any fitted model (i.e. not from rminer), provided that the predict function PRED is defined (see examples for details).} \item{data}{training data (the same data.frame that was used to fit the model, currently only used to add data histogram to VEC curve).} \item{RealL}{the number of sensitivity analysis levels (e.g. 7). Note: you need to use \code{RealL}>=2.} \item{method}{input importance method. Options are: \itemize{ \item 1D-SA -- 1 dimensional sensitivity analysis, very fast, sets interactions to NULL. \item sens or SA -- sensitivity analysis. There are some extra variants: sensa -- equal to \code{sens} but also sets \code{measure="AAD"}; sensv -- sets \code{measure="variance"}; sensg -- sets \code{measure="gradient"}; sensr -- sets \code{measure="range"}. if interactions is not null, then GSA is assumed, else 1D-SA is assumed. \item DSA -- Data-based SA (good option if input interactions need to be detected). \item MSA -- Monte-Carlo SA. \item CSA -- Cluster-based SA. \item GSA -- Global SA (very slow method, particularly if the number of inputs is large, should be avoided). \item randomForest -- uses method of Leo Breiman (type=1), only makes sense when M is a randomRorest. } } \item{measure}{sensitivity analysis measure (used to measure input importance). Options are: \itemize{ \item AAD -- average absolute deviation from the median. \item gradient -- average absolute gradient (y_i+1-y_i) of the responses. \item variance -- variance of the responses. \item range -- maximum - minimum of the responses. } } \item{sampling}{for numeric inputs, the sampling scan function. Options are: \itemize{ \item regular -- regular sequence (uniform distribution), do not change this value, kept here only due to compatibility issues. } } \item{baseline}{baseline vector used during the sensitivity analysis. Options are: \itemize{ \item mean -- uses a vector with the mean values of each attribute from \code{data}. \item median -- uses a vector with the median values of each attribute from \code{data}. \item a data.frame with the baseline example (should have the same attribute names as \code{data}). } } \item{responses}{if \code{TRUE} then all sensitivity analysis responses are stored and returned.} \item{outindex}{the output index (column) of \code{data} if \code{M} is not a model object (returned by fit).} \item{task}{the \code{task} as defined in \code{\link{fit}} if \code{M} is not a model object (returned by fit).} \item{PRED}{the prediction function of \code{M}, if \code{M} is not a model object (returned by fit). Note: this function should behave like the rminer \code{\link{predict-methods}}, i.e. return a numeric vector in case of regression; a matrix of examples (rows) vs probabilities (columns) (\code{task="prob"}) or a factor (\code{task="class"}) in case of classification. } \item{interactions}{numeric vector with the attributes (columns) used by Ith-D sensitivity analysis (2-D or higher, "GSA" method): \itemize{ \item if \code{NULL} then only a 1-D sensitivity analysis is performed. \item if \code{length(interactions)==1} then a "special" 2-D sensitivity analysis is performed using the index of interactions versus all remaining inputs. Note: the $sresponses[[interactions]] will be empty (in \code{\link{vecplot}} do not use \code{xval} \code{=interactions}). \item if \code{length(interactions)>1} then a full Ith-D sensitivity analysis is performed, where I=length(interactions). Note: Computational effort can highly increase if I is too large, i.e. O(RealL^I). Also, you need to preprocess the returned list (e.g. using \code{avg_imp}) to use the \code{\link{vecplot}} function (see the examples). } } \item{Aggregation}{numeric value that sets the number of multi-metric aggregation function (used only for "DSA", ""). Options are: \itemize{ \item -1 -- the default value that should work in most cases (if regression, sets Aggregation=3, else if classification then sets Aggregation=1). \item 1 -- value that should work for classification (only use the average of all sensitivity values). \item 3 -- value that should work for regression (use 3 metrics, the minimum, average and maximum of all sensitivity values). } } \item{LRandom}{number of samples used by DSA and MSA methods. The default value is -1, which means: use a number equal to training set size. If a different value is used (1<= value <= number of training samples), then LRandom samples are randomly selected.} \item{MRandom}{sampling type used by MSA: "discrete" (default discrete uniform distribution) or "continuous" (from continuous uniform distribution).} \item{Lfactor}{sets the maximum number of sensitivity levels for discrete inputs. if FALSE then a maximum of up to RealL levels are used (most frequent ones), else (TRUE) then all levels of the input are used in the SA analysis.} } \details{ This function provides several algorithms for measuring input importance of supervised data mining models and the average effect of a given input (or pair of inputs) in the model. A particular emphasis is given on sensitivity analysis (SA), which is a simple method that measures the effects on the output of a given model when the inputs are varied through their range of values. Check the references for more details. } \value{ A \code{list} with the components: \itemize{ \item $value -- numeric vector with the computed sensitivity analysis measure for each attribute. \item $imp -- numeric vector with the relative importance for each attribute (only makes sense for 1-D analysis). \item $sresponses -- vector list as described in the Value documentation of \code{\link{mining}}. \item $data -- if DSA or MSA, store the used data samples, needed for visualizations made by vecplot. \item $method -- SA method \item $measure -- SA measure \item $agg -- Aggregation value \item $nclasses -- if task="prob" or "class", the number of output classes, else nclasses=1 \item $inputs -- indexes of the input attributes \item $Llevels -- sensitivity levels used for each attribute (NA means output attribute) \item $interactions -- which attributes were interacted when method=GSA. } } \references{ \itemize{ \item To cite the Importance function, sensitivity analysis methods or synthetic datasets, please use:\cr P. Cortez and M.J. Embrechts.\cr Using Sensitivity Analysis and Visualization Techniques to Open Black Box Data Mining Models.\cr In Information Sciences, Elsevier, 225:1-17, March 2013.\cr \url{http://dx.doi.org/10.1016/j.ins.2012.10.039}\cr } } \author{ Paulo Cortez \url{http://www3.dsi.uminho.pt/pcortez/} } \note{ See also \url{http://www3.dsi.uminho.pt/pcortez/rminer.html} } \seealso{ \code{\link{vecplot}}, \code{\link{fit}}, \code{\link{mining}}, \code{\link{mgraph}}, \code{\link{mmetric}}, \code{\link{savemining}}. } \examples{ ### dontrun is used when the execution of the example requires some computational effort. ### 1st example, regression, 1-D sensitivity analysis \dontrun{ data(sa_ssin) # x1 should account for 55%, x2 for 27%, x3 for 18% and x4 for 0%. M=fit(y~.,sa_ssin,model="ksvm") I=Importance(M,sa_ssin,method="1D-SA") # 1-D SA, AAD print(round(I$imp,digits=2)) L=list(runs=1,sen=t(I$imp),sresponses=I$sresponses) mgraph(L,graph="IMP",leg=names(sa_ssin),col="gray",Grid=10) mgraph(L,graph="VEC",xval=1,Grid=10,data=sa_ssin, main="VEC curve for x1 influence on y") # or: vecplot(I,xval=1,Grid=10,data=sa_ssin,datacol="gray", main="VEC curve for x1 influence on y") # same graph vecplot(I,xval=c(1,2,3),pch=c(1,2,3),Grid=10, leg=list(pos="bottomright",leg=c("x1","x2","x3"))) # all x1, x2 and x3 VEC curves } ### 2nd example, regression, DSA sensitivity analysis: \dontrun{ I2=Importance(M,sa_ssin,method="DSA") print(I2) # influence of x1 and x2 over y vecplot(I2,graph="VEC",xval=1) # VEC curve vecplot(I2,graph="VECB",xval=1) # VEC curve with boxplots vecplot(I2,graph="VEC3",xval=c(1,2)) # VEC surface vecplot(I2,graph="VECC",xval=c(1,2)) # VEC contour } ### 3th example, classification (pure class labels, task="cla"), DSA: \dontrun{ data(sa_int2_3c) # pair (x1,x2) is more relevant than x3, all x1,x2,x3 affect y, # x4 has a null effect. M2=fit(y~.,sa_int2_3c,model="mlpe",task="class") I4=Importance(M2,sa_int2_3c,method="DSA") # VEC curve (should present a kind of "saw" shape curve) for class B (TC=2): vecplot(I4,graph="VEC",xval=2,cex=1.2,TC=2, main="VEC curve for x2 influence on y (class B)",xlab="x2") # same VEC curve but with boxplots: vecplot(I4,graph="VECB",xval=2,cex=1.2,TC=2, main="VEC curve with box plots for x2 influence on y (class B)",xlab="x2") } ### 4th example, regression, DSA: \dontrun{ data(sa_psin) # same model from Table 1 of the reference: M3=fit(y~.,sa_psin,model="ksvm",search=2^-2,C=2^6.87,epsilon=2^-8) # in this case: Aggregation is the same as NY I5=Importance(M3,sa_psin,method="DSA",Aggregation=3) # 2D analysis (check reference for more details), RealL=L=7: # need to aggregate results into a matrix of SA measure cm=agg_matrix_imp(I5) print("show Table 8 DSA results (from the reference):") print(round(cm$m1,digits=2)) print(round(cm$m2,digits=2)) # show most relevant (darker) input pairs, in this case (x1,x2) > (x1,x3) > (x2,x3) # to build a nice plot, a fixed threshold=c(0.05,0.05) is used. note that # in the paper and for real data, we use threshold=0.1, # which means threshold=rep(max(cm$m1,cm$m2)*threshold,2) fcm=cmatrixplot(cm,threshold=c(0.05,0.05)) # 2D analysis using pair AT=c(x1,x2') (check reference for more details), RealL=7: # nice 3D VEC surface plot: vecplot(I5,xval=c(1,2),graph="VEC3",xlab="x1",ylab="x2",zoom=1.1, main="VEC surface of (x1,x2') influence on y") # same influence but know shown using VEC contour: par(mar=c(4.0,4.0,1.0,0.3)) # change the graph window space size vecplot(I5,xval=c(1,2),graph="VECC",xlab="x1",ylab="x2", main="VEC surface of (x1,x2') influence on y") # slower GSA: I6=Importance(M3,sa_psin,method="GSA",interactions=1:4) cm2=agg_matrix_imp(I6) # compare cm2 with cm1, almost identical: print(round(cm2$m1,digits=2)) print(round(cm2$m2,digits=2)) fcm2=cmatrixplot(cm2,threshold=0.1) } ### If you want to use Importance over your own model (different than rminer ones): # 1st example, regression, uses the theoretical sin1reg function: x1=70% and x2=30% data(sin1reg) mypred=function(M,data) { return (M[1]*sin(pi*data[,1]/M[3])+M[2]*sin(pi*data[,2]/M[3])) } M=c(0.7,0.3,2000) # 4 is the column index of y I=Importance(M,sin1reg,method="sens",measure="AAD",PRED=mypred,outindex=4) print(I$imp) # x1=72.3% and x2=27.7% L=list(runs=1,sen=t(I$imp),sresponses=I$sresponses) mgraph(L,graph="IMP",leg=names(sin1reg),col="gray",Grid=10) mgraph(L,graph="VEC",xval=1,Grid=10) # equal to: par(mar=c(2.0,2.0,1.0,0.3)) # change the graph window space size vecplot(I,graph="VEC",xval=1,Grid=10,main="VEC curve for x1 influence on y:") ### 2nd example, 3-class classification for iris and lda model: \dontrun{ data(iris) library(MASS) predlda=function(M,data) # the PRED function { return (predict(M,data)$posterior) } LDA=lda(Species ~ .,iris, prior = c(1,1,1)/3) # 4 is the column index of Species I=Importance(LDA,iris,method="1D-SA",PRED=predlda,outindex=4) vecplot(I,graph="VEC",xval=1,Grid=10,TC=1, main="1-D VEC for Sepal.Lenght (x-axis) influence in setosa (prob.)") } ### 3rd example, binary classification for setosa iris and lda model: \dontrun{ data(iris) library(MASS) iris2=iris;iris2$Species=factor(iris$Species=="setosa") predlda2=function(M,data) # the PRED function { return (predict(M,data)$class) } LDA2=lda(Species ~ .,iris2) I=Importance(LDA2,iris2,method="1D-SA",PRED=predlda2,outindex=4) vecplot(I,graph="VEC",xval=1, main="1-D VEC for Sepal.Lenght (x-axis) influence in setosa (class)",Grid=10) } ### Example with discrete inputs \dontrun{ data(iris) ir1=iris ir1[,1]=cut(ir1[,1],breaks=4) ir1[,2]=cut(ir1[,2],breaks=4) M=fit(Species~.,ir1,model="mlpe") I=Importance(M,ir1,method="DSA") # discrete example: vecplot(I,graph="VEC",xval=1,TC=1,main="class: setosa (discrete x1)",data=ir1) # continuous example: vecplot(I,graph="VEC",xval=3,TC=1,main="class: setosa (cont. x1)",data=ir1) } } \keyword{ classif } \keyword{ neural }
/man/Importance.Rd
no_license
CBADS-SPI/rminer
R
false
false
13,842
rd
\name{Importance} \alias{Importance} \title{ Measure input importance (including sensitivity analysis) given a supervised data mining model. } \description{ Measure input importance (including sensitivity analysis) given a supervised data mining model. } \usage{ Importance(M, data, RealL = 7, method = "1D-SA", measure = "AAD", sampling = "regular", baseline = "mean", responses = TRUE, outindex = NULL, task = "default", PRED = NULL, interactions = NULL, Aggregation = -1, LRandom = -1, MRandom = "discrete", Lfactor = FALSE) } \arguments{ \item{M}{fitted model, typically is the object returned by \code{\link{fit}}. Can also be any fitted model (i.e. not from rminer), provided that the predict function PRED is defined (see examples for details).} \item{data}{training data (the same data.frame that was used to fit the model, currently only used to add data histogram to VEC curve).} \item{RealL}{the number of sensitivity analysis levels (e.g. 7). Note: you need to use \code{RealL}>=2.} \item{method}{input importance method. Options are: \itemize{ \item 1D-SA -- 1 dimensional sensitivity analysis, very fast, sets interactions to NULL. \item sens or SA -- sensitivity analysis. There are some extra variants: sensa -- equal to \code{sens} but also sets \code{measure="AAD"}; sensv -- sets \code{measure="variance"}; sensg -- sets \code{measure="gradient"}; sensr -- sets \code{measure="range"}. if interactions is not null, then GSA is assumed, else 1D-SA is assumed. \item DSA -- Data-based SA (good option if input interactions need to be detected). \item MSA -- Monte-Carlo SA. \item CSA -- Cluster-based SA. \item GSA -- Global SA (very slow method, particularly if the number of inputs is large, should be avoided). \item randomForest -- uses method of Leo Breiman (type=1), only makes sense when M is a randomRorest. } } \item{measure}{sensitivity analysis measure (used to measure input importance). Options are: \itemize{ \item AAD -- average absolute deviation from the median. \item gradient -- average absolute gradient (y_i+1-y_i) of the responses. \item variance -- variance of the responses. \item range -- maximum - minimum of the responses. } } \item{sampling}{for numeric inputs, the sampling scan function. Options are: \itemize{ \item regular -- regular sequence (uniform distribution), do not change this value, kept here only due to compatibility issues. } } \item{baseline}{baseline vector used during the sensitivity analysis. Options are: \itemize{ \item mean -- uses a vector with the mean values of each attribute from \code{data}. \item median -- uses a vector with the median values of each attribute from \code{data}. \item a data.frame with the baseline example (should have the same attribute names as \code{data}). } } \item{responses}{if \code{TRUE} then all sensitivity analysis responses are stored and returned.} \item{outindex}{the output index (column) of \code{data} if \code{M} is not a model object (returned by fit).} \item{task}{the \code{task} as defined in \code{\link{fit}} if \code{M} is not a model object (returned by fit).} \item{PRED}{the prediction function of \code{M}, if \code{M} is not a model object (returned by fit). Note: this function should behave like the rminer \code{\link{predict-methods}}, i.e. return a numeric vector in case of regression; a matrix of examples (rows) vs probabilities (columns) (\code{task="prob"}) or a factor (\code{task="class"}) in case of classification. } \item{interactions}{numeric vector with the attributes (columns) used by Ith-D sensitivity analysis (2-D or higher, "GSA" method): \itemize{ \item if \code{NULL} then only a 1-D sensitivity analysis is performed. \item if \code{length(interactions)==1} then a "special" 2-D sensitivity analysis is performed using the index of interactions versus all remaining inputs. Note: the $sresponses[[interactions]] will be empty (in \code{\link{vecplot}} do not use \code{xval} \code{=interactions}). \item if \code{length(interactions)>1} then a full Ith-D sensitivity analysis is performed, where I=length(interactions). Note: Computational effort can highly increase if I is too large, i.e. O(RealL^I). Also, you need to preprocess the returned list (e.g. using \code{avg_imp}) to use the \code{\link{vecplot}} function (see the examples). } } \item{Aggregation}{numeric value that sets the number of multi-metric aggregation function (used only for "DSA", ""). Options are: \itemize{ \item -1 -- the default value that should work in most cases (if regression, sets Aggregation=3, else if classification then sets Aggregation=1). \item 1 -- value that should work for classification (only use the average of all sensitivity values). \item 3 -- value that should work for regression (use 3 metrics, the minimum, average and maximum of all sensitivity values). } } \item{LRandom}{number of samples used by DSA and MSA methods. The default value is -1, which means: use a number equal to training set size. If a different value is used (1<= value <= number of training samples), then LRandom samples are randomly selected.} \item{MRandom}{sampling type used by MSA: "discrete" (default discrete uniform distribution) or "continuous" (from continuous uniform distribution).} \item{Lfactor}{sets the maximum number of sensitivity levels for discrete inputs. if FALSE then a maximum of up to RealL levels are used (most frequent ones), else (TRUE) then all levels of the input are used in the SA analysis.} } \details{ This function provides several algorithms for measuring input importance of supervised data mining models and the average effect of a given input (or pair of inputs) in the model. A particular emphasis is given on sensitivity analysis (SA), which is a simple method that measures the effects on the output of a given model when the inputs are varied through their range of values. Check the references for more details. } \value{ A \code{list} with the components: \itemize{ \item $value -- numeric vector with the computed sensitivity analysis measure for each attribute. \item $imp -- numeric vector with the relative importance for each attribute (only makes sense for 1-D analysis). \item $sresponses -- vector list as described in the Value documentation of \code{\link{mining}}. \item $data -- if DSA or MSA, store the used data samples, needed for visualizations made by vecplot. \item $method -- SA method \item $measure -- SA measure \item $agg -- Aggregation value \item $nclasses -- if task="prob" or "class", the number of output classes, else nclasses=1 \item $inputs -- indexes of the input attributes \item $Llevels -- sensitivity levels used for each attribute (NA means output attribute) \item $interactions -- which attributes were interacted when method=GSA. } } \references{ \itemize{ \item To cite the Importance function, sensitivity analysis methods or synthetic datasets, please use:\cr P. Cortez and M.J. Embrechts.\cr Using Sensitivity Analysis and Visualization Techniques to Open Black Box Data Mining Models.\cr In Information Sciences, Elsevier, 225:1-17, March 2013.\cr \url{http://dx.doi.org/10.1016/j.ins.2012.10.039}\cr } } \author{ Paulo Cortez \url{http://www3.dsi.uminho.pt/pcortez/} } \note{ See also \url{http://www3.dsi.uminho.pt/pcortez/rminer.html} } \seealso{ \code{\link{vecplot}}, \code{\link{fit}}, \code{\link{mining}}, \code{\link{mgraph}}, \code{\link{mmetric}}, \code{\link{savemining}}. } \examples{ ### dontrun is used when the execution of the example requires some computational effort. ### 1st example, regression, 1-D sensitivity analysis \dontrun{ data(sa_ssin) # x1 should account for 55%, x2 for 27%, x3 for 18% and x4 for 0%. M=fit(y~.,sa_ssin,model="ksvm") I=Importance(M,sa_ssin,method="1D-SA") # 1-D SA, AAD print(round(I$imp,digits=2)) L=list(runs=1,sen=t(I$imp),sresponses=I$sresponses) mgraph(L,graph="IMP",leg=names(sa_ssin),col="gray",Grid=10) mgraph(L,graph="VEC",xval=1,Grid=10,data=sa_ssin, main="VEC curve for x1 influence on y") # or: vecplot(I,xval=1,Grid=10,data=sa_ssin,datacol="gray", main="VEC curve for x1 influence on y") # same graph vecplot(I,xval=c(1,2,3),pch=c(1,2,3),Grid=10, leg=list(pos="bottomright",leg=c("x1","x2","x3"))) # all x1, x2 and x3 VEC curves } ### 2nd example, regression, DSA sensitivity analysis: \dontrun{ I2=Importance(M,sa_ssin,method="DSA") print(I2) # influence of x1 and x2 over y vecplot(I2,graph="VEC",xval=1) # VEC curve vecplot(I2,graph="VECB",xval=1) # VEC curve with boxplots vecplot(I2,graph="VEC3",xval=c(1,2)) # VEC surface vecplot(I2,graph="VECC",xval=c(1,2)) # VEC contour } ### 3th example, classification (pure class labels, task="cla"), DSA: \dontrun{ data(sa_int2_3c) # pair (x1,x2) is more relevant than x3, all x1,x2,x3 affect y, # x4 has a null effect. M2=fit(y~.,sa_int2_3c,model="mlpe",task="class") I4=Importance(M2,sa_int2_3c,method="DSA") # VEC curve (should present a kind of "saw" shape curve) for class B (TC=2): vecplot(I4,graph="VEC",xval=2,cex=1.2,TC=2, main="VEC curve for x2 influence on y (class B)",xlab="x2") # same VEC curve but with boxplots: vecplot(I4,graph="VECB",xval=2,cex=1.2,TC=2, main="VEC curve with box plots for x2 influence on y (class B)",xlab="x2") } ### 4th example, regression, DSA: \dontrun{ data(sa_psin) # same model from Table 1 of the reference: M3=fit(y~.,sa_psin,model="ksvm",search=2^-2,C=2^6.87,epsilon=2^-8) # in this case: Aggregation is the same as NY I5=Importance(M3,sa_psin,method="DSA",Aggregation=3) # 2D analysis (check reference for more details), RealL=L=7: # need to aggregate results into a matrix of SA measure cm=agg_matrix_imp(I5) print("show Table 8 DSA results (from the reference):") print(round(cm$m1,digits=2)) print(round(cm$m2,digits=2)) # show most relevant (darker) input pairs, in this case (x1,x2) > (x1,x3) > (x2,x3) # to build a nice plot, a fixed threshold=c(0.05,0.05) is used. note that # in the paper and for real data, we use threshold=0.1, # which means threshold=rep(max(cm$m1,cm$m2)*threshold,2) fcm=cmatrixplot(cm,threshold=c(0.05,0.05)) # 2D analysis using pair AT=c(x1,x2') (check reference for more details), RealL=7: # nice 3D VEC surface plot: vecplot(I5,xval=c(1,2),graph="VEC3",xlab="x1",ylab="x2",zoom=1.1, main="VEC surface of (x1,x2') influence on y") # same influence but know shown using VEC contour: par(mar=c(4.0,4.0,1.0,0.3)) # change the graph window space size vecplot(I5,xval=c(1,2),graph="VECC",xlab="x1",ylab="x2", main="VEC surface of (x1,x2') influence on y") # slower GSA: I6=Importance(M3,sa_psin,method="GSA",interactions=1:4) cm2=agg_matrix_imp(I6) # compare cm2 with cm1, almost identical: print(round(cm2$m1,digits=2)) print(round(cm2$m2,digits=2)) fcm2=cmatrixplot(cm2,threshold=0.1) } ### If you want to use Importance over your own model (different than rminer ones): # 1st example, regression, uses the theoretical sin1reg function: x1=70% and x2=30% data(sin1reg) mypred=function(M,data) { return (M[1]*sin(pi*data[,1]/M[3])+M[2]*sin(pi*data[,2]/M[3])) } M=c(0.7,0.3,2000) # 4 is the column index of y I=Importance(M,sin1reg,method="sens",measure="AAD",PRED=mypred,outindex=4) print(I$imp) # x1=72.3% and x2=27.7% L=list(runs=1,sen=t(I$imp),sresponses=I$sresponses) mgraph(L,graph="IMP",leg=names(sin1reg),col="gray",Grid=10) mgraph(L,graph="VEC",xval=1,Grid=10) # equal to: par(mar=c(2.0,2.0,1.0,0.3)) # change the graph window space size vecplot(I,graph="VEC",xval=1,Grid=10,main="VEC curve for x1 influence on y:") ### 2nd example, 3-class classification for iris and lda model: \dontrun{ data(iris) library(MASS) predlda=function(M,data) # the PRED function { return (predict(M,data)$posterior) } LDA=lda(Species ~ .,iris, prior = c(1,1,1)/3) # 4 is the column index of Species I=Importance(LDA,iris,method="1D-SA",PRED=predlda,outindex=4) vecplot(I,graph="VEC",xval=1,Grid=10,TC=1, main="1-D VEC for Sepal.Lenght (x-axis) influence in setosa (prob.)") } ### 3rd example, binary classification for setosa iris and lda model: \dontrun{ data(iris) library(MASS) iris2=iris;iris2$Species=factor(iris$Species=="setosa") predlda2=function(M,data) # the PRED function { return (predict(M,data)$class) } LDA2=lda(Species ~ .,iris2) I=Importance(LDA2,iris2,method="1D-SA",PRED=predlda2,outindex=4) vecplot(I,graph="VEC",xval=1, main="1-D VEC for Sepal.Lenght (x-axis) influence in setosa (class)",Grid=10) } ### Example with discrete inputs \dontrun{ data(iris) ir1=iris ir1[,1]=cut(ir1[,1],breaks=4) ir1[,2]=cut(ir1[,2],breaks=4) M=fit(Species~.,ir1,model="mlpe") I=Importance(M,ir1,method="DSA") # discrete example: vecplot(I,graph="VEC",xval=1,TC=1,main="class: setosa (discrete x1)",data=ir1) # continuous example: vecplot(I,graph="VEC",xval=3,TC=1,main="class: setosa (cont. x1)",data=ir1) } } \keyword{ classif } \keyword{ neural }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/EGRI.R \name{EGRI} \alias{EGRI} \title{Efficient Global Robust Inversion} \usage{ EGRI(T, model, method = NULL, fun, iter = 1, batchsize = 1, opt.index, inv.index, lower = NULL, upper = NULL, new.noise.var = NULL, integcontrol = NULL, optimcontrol = NULL, kmcontrol = NULL, ...) } \arguments{ \item{T}{Target threshold.} \item{model}{The current kriging model. km object.} \item{method}{Criterion used for choosing observations. Currently, only the \code{"surnew"} criterion is available.} \item{fun}{Objective function.} \item{iter}{Number of iterations. At each iteration, a batch of batchsize point is evaluated in parallel.} \item{batchsize}{The size of the batch of points evaluated at each iteration.} \item{opt.index}{Array with integers corresponding to the indices of the nuisance parameters.} \item{inv.index}{Array with integers corresponding to the indices of the controlled parameters.} \item{lower}{Array of size d. Lower bound of the input domain.} \item{upper}{Array of size d. Upper bound of the input domain.} \item{new.noise.var}{Optional scalar value of the noise variance of the new observations.} \item{integcontrol}{The integcontrol argument used in the \code{integration_design_robinv} function. This applies for the following criterion: \code{"surnew"}. See the help of the \code{integration_design_robinv} function.} \item{optimcontrol}{A list used to set up the optimization procedure of the chosen sampling criterion. For the \code{"surnew"} criterion, see the help of the \code{max_surnew_robinv} function.} \item{kmcontrol}{Optional list representing the control variables for the re-estimation of the kriging model once new points are sampled. The items are the same as in the \code{km} function of the DiceKriging package.} \item{...}{Other arguments of the objective function fun.} } \value{ A list with the following fields. (i) par: The added observations (iter*batchsize) x d matrix, (ii) value: The value of the function fun at the added observations, (iii) lastmodel: The current (last) kriging model of km class, (iv) lastvalue: The value of the criterion at the last added point, (v) allvalues: If an optimization on a discrete set of points is chosen, the value of the criterion at all these points, for the last iteration, (vi) lastintegration.param: For debug. The last value returned by the integration_design_robinv function, if applicable. } \description{ Sequential design of experiments for robust inversion. } \examples{ library(KrigInv) myfun <- function(x) return(-1 * branin_robinv(x)) d <- 4 set.seed(8) # an example with scaling n0 <- 40 T <- -10 opt.index <- c(3,4) inv.index <- c(1,2) lower <- rep(0,times=d) upper <- rep(1,times=d) design <- matrix(runif(d*n0),nrow=n0) response <- myfun(design) knots.number <- c(2,2,2,2) knots <- generate_knots(knots.number = knots.number , d = d) model <- km(formula = ~1,design = design,response = response,covtype = "matern3_2",scaling = TRUE,knots = knots) integcontrol <- list(distrib = "surnew",n.points = 100,finaldistrib="surnew",n.candidates=300, nsimu=100,n.optpoints = 50,choose_optpoints=TRUE,n.optpoints.candidates=200) optimcontrol <- list(method = "genoud", pop.size = 400, max.generations = 4, wait.generation = 1) \dontrun{ obj <- EGRI(T = T,method="surnew",model = model,fun = myfun,iter = 2, batchsize = 2,opt.index = opt.index,inv.index = inv.index, integcontrol=integcontrol,optimcontrol=optimcontrol) } } \author{ Clement Chevalier \email{clement.chevalier@unine.ch} }
/man/EGRI.Rd
no_license
IRSN/RobustInv
R
false
true
3,643
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/EGRI.R \name{EGRI} \alias{EGRI} \title{Efficient Global Robust Inversion} \usage{ EGRI(T, model, method = NULL, fun, iter = 1, batchsize = 1, opt.index, inv.index, lower = NULL, upper = NULL, new.noise.var = NULL, integcontrol = NULL, optimcontrol = NULL, kmcontrol = NULL, ...) } \arguments{ \item{T}{Target threshold.} \item{model}{The current kriging model. km object.} \item{method}{Criterion used for choosing observations. Currently, only the \code{"surnew"} criterion is available.} \item{fun}{Objective function.} \item{iter}{Number of iterations. At each iteration, a batch of batchsize point is evaluated in parallel.} \item{batchsize}{The size of the batch of points evaluated at each iteration.} \item{opt.index}{Array with integers corresponding to the indices of the nuisance parameters.} \item{inv.index}{Array with integers corresponding to the indices of the controlled parameters.} \item{lower}{Array of size d. Lower bound of the input domain.} \item{upper}{Array of size d. Upper bound of the input domain.} \item{new.noise.var}{Optional scalar value of the noise variance of the new observations.} \item{integcontrol}{The integcontrol argument used in the \code{integration_design_robinv} function. This applies for the following criterion: \code{"surnew"}. See the help of the \code{integration_design_robinv} function.} \item{optimcontrol}{A list used to set up the optimization procedure of the chosen sampling criterion. For the \code{"surnew"} criterion, see the help of the \code{max_surnew_robinv} function.} \item{kmcontrol}{Optional list representing the control variables for the re-estimation of the kriging model once new points are sampled. The items are the same as in the \code{km} function of the DiceKriging package.} \item{...}{Other arguments of the objective function fun.} } \value{ A list with the following fields. (i) par: The added observations (iter*batchsize) x d matrix, (ii) value: The value of the function fun at the added observations, (iii) lastmodel: The current (last) kriging model of km class, (iv) lastvalue: The value of the criterion at the last added point, (v) allvalues: If an optimization on a discrete set of points is chosen, the value of the criterion at all these points, for the last iteration, (vi) lastintegration.param: For debug. The last value returned by the integration_design_robinv function, if applicable. } \description{ Sequential design of experiments for robust inversion. } \examples{ library(KrigInv) myfun <- function(x) return(-1 * branin_robinv(x)) d <- 4 set.seed(8) # an example with scaling n0 <- 40 T <- -10 opt.index <- c(3,4) inv.index <- c(1,2) lower <- rep(0,times=d) upper <- rep(1,times=d) design <- matrix(runif(d*n0),nrow=n0) response <- myfun(design) knots.number <- c(2,2,2,2) knots <- generate_knots(knots.number = knots.number , d = d) model <- km(formula = ~1,design = design,response = response,covtype = "matern3_2",scaling = TRUE,knots = knots) integcontrol <- list(distrib = "surnew",n.points = 100,finaldistrib="surnew",n.candidates=300, nsimu=100,n.optpoints = 50,choose_optpoints=TRUE,n.optpoints.candidates=200) optimcontrol <- list(method = "genoud", pop.size = 400, max.generations = 4, wait.generation = 1) \dontrun{ obj <- EGRI(T = T,method="surnew",model = model,fun = myfun,iter = 2, batchsize = 2,opt.index = opt.index,inv.index = inv.index, integcontrol=integcontrol,optimcontrol=optimcontrol) } } \author{ Clement Chevalier \email{clement.chevalier@unine.ch} }
setClass("bnnSurvivalResult", representation( prediction = "matrix", timepoints = "numeric", num_base_learners = "integer", num_features_per_base_learner = "integer", k = "integer", n_train = "integer") ) ## Constructor bnnSurvivalResult <- function(prediction, timepoints, num_base_learners, num_features_per_base_learner, k, n_train) { new("bnnSurvivalResult", prediction = prediction, timepoints = timepoints, num_base_learners = num_base_learners, num_features_per_base_learner = num_features_per_base_learner, k = k, n_train = n_train) } ##' Get Predictions ##' @param object bnnSurvivalResult object to extract predictions from ##' @export setMethod("predictions", signature("bnnSurvivalResult"), function(object) { return(object@prediction) } ) ##' Get timepoints ##' @param object bnnSurvivalResult object to extract timepoints from ##' @export setMethod("timepoints", signature("bnnSurvivalResult"), function(object) { return(object@timepoints) } ) ##' Generic print method for bnnSurvivalResult ##' @param x bnnSurvivalResult object to print ##' @export setMethod("print", signature("bnnSurvivalResult"), function(x) { cat("bnnSurvival results object\n\n") cat("Number of base learners: ", x@num_base_learners, "\n") cat("Number of fatures per base learner ", x@num_features_per_base_learner, "\n") cat("Number of neighbors (k): ", x@k, "\n") cat("Number of timepoints: ", length(x@timepoints), "\n") cat("Number of training observations: ", x@n_train, "\n") cat("Number of test observations: ", nrow(x@prediction), "\n\n") cat("Use predictions() and timepoints() functions to access the results.\n") } ) ##' Generic show method for bnnSurvivalResult ##' @param object bnnSurvivalResult object to show ##' @export setMethod("show", signature("bnnSurvivalResult"), function(object) { print(object) } )
/R/bnnSurvivalResult.R
no_license
mnwright/bnnSurvival
R
false
false
2,000
r
setClass("bnnSurvivalResult", representation( prediction = "matrix", timepoints = "numeric", num_base_learners = "integer", num_features_per_base_learner = "integer", k = "integer", n_train = "integer") ) ## Constructor bnnSurvivalResult <- function(prediction, timepoints, num_base_learners, num_features_per_base_learner, k, n_train) { new("bnnSurvivalResult", prediction = prediction, timepoints = timepoints, num_base_learners = num_base_learners, num_features_per_base_learner = num_features_per_base_learner, k = k, n_train = n_train) } ##' Get Predictions ##' @param object bnnSurvivalResult object to extract predictions from ##' @export setMethod("predictions", signature("bnnSurvivalResult"), function(object) { return(object@prediction) } ) ##' Get timepoints ##' @param object bnnSurvivalResult object to extract timepoints from ##' @export setMethod("timepoints", signature("bnnSurvivalResult"), function(object) { return(object@timepoints) } ) ##' Generic print method for bnnSurvivalResult ##' @param x bnnSurvivalResult object to print ##' @export setMethod("print", signature("bnnSurvivalResult"), function(x) { cat("bnnSurvival results object\n\n") cat("Number of base learners: ", x@num_base_learners, "\n") cat("Number of fatures per base learner ", x@num_features_per_base_learner, "\n") cat("Number of neighbors (k): ", x@k, "\n") cat("Number of timepoints: ", length(x@timepoints), "\n") cat("Number of training observations: ", x@n_train, "\n") cat("Number of test observations: ", nrow(x@prediction), "\n\n") cat("Use predictions() and timepoints() functions to access the results.\n") } ) ##' Generic show method for bnnSurvivalResult ##' @param object bnnSurvivalResult object to show ##' @export setMethod("show", signature("bnnSurvivalResult"), function(object) { print(object) } )
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/equating.R \name{plot.p2pass} \alias{plot.p2pass} \title{A plot method for probability_to_pass} \usage{ \method{plot}{p2pass}(x, ..., booklet_id = NULL, what = c("both", "equating", "sens/spec")) } \arguments{ \item{x}{An object produced by function \code{\link{probability_to_pass}}} \item{...}{Any additional plotting parameters.} \item{booklet_id}{vector of booklet_id's to plot, if NULL all booklets are plotted} \item{what}{information to plot, 'equating', 'sens/spec' or 'both'} } \description{ Plot equating information from probability_to_pass }
/man/plot.p2pass.Rd
no_license
romainfrancois/dexter
R
false
true
637
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/equating.R \name{plot.p2pass} \alias{plot.p2pass} \title{A plot method for probability_to_pass} \usage{ \method{plot}{p2pass}(x, ..., booklet_id = NULL, what = c("both", "equating", "sens/spec")) } \arguments{ \item{x}{An object produced by function \code{\link{probability_to_pass}}} \item{...}{Any additional plotting parameters.} \item{booklet_id}{vector of booklet_id's to plot, if NULL all booklets are plotted} \item{what}{information to plot, 'equating', 'sens/spec' or 'both'} } \description{ Plot equating information from probability_to_pass }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{ltm_cat} \alias{ltm_cat} \title{ltm Cat Object} \format{An object of class \code{Cat}. See \code{\link{Cat-class}} for more details.} \usage{ data(ltm_cat) } \description{ An object of class \code{Cat} created using the \code{ltmCat} function with the \code{npi} dataset. } \examples{ \dontrun{ ## How this Cat object was created data(npi) ltm_cat <- ltmCat(npi, quadraturePoints = 100) } ## How to load this Cat object for usage data(ltm_cat) } \seealso{ \code{\link{Cat-class}}, \code{\link{ltmCat}}, \code{\link{npi}} } \keyword{datasets}
/man/ltm_cat.Rd
no_license
domlockett/catSurv
R
false
true
651
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data.R \docType{data} \name{ltm_cat} \alias{ltm_cat} \title{ltm Cat Object} \format{An object of class \code{Cat}. See \code{\link{Cat-class}} for more details.} \usage{ data(ltm_cat) } \description{ An object of class \code{Cat} created using the \code{ltmCat} function with the \code{npi} dataset. } \examples{ \dontrun{ ## How this Cat object was created data(npi) ltm_cat <- ltmCat(npi, quadraturePoints = 100) } ## How to load this Cat object for usage data(ltm_cat) } \seealso{ \code{\link{Cat-class}}, \code{\link{ltmCat}}, \code{\link{npi}} } \keyword{datasets}
# The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here: # # https://dl.dropbox.com/u/7710864/data/csv_hid/ss06hid.csv or here # https://spark-public.s3.amazonaws.com/dataanalysis/ss06hid.csv # # and load the data into R. You will use this data for the next several questions. The code book, describing the variable names is here: # #https://dl.dropbox.com/u/7710864/data/PUMSDataDict06.pdf or here: # #https://spark-public.s3.amazonaws.com/dataanalysis/PUMSDataDict06.pdf # #How many housing units in this survey were worth more than $1,000,000? # ok #method <- "curl" #download.file("https://dl.dropbox.com/u/7710864/data/csv_hid/ss06hid.csv", "ss06hid.csv", method) #download.file("https://dl.dropbox.com/u/7710864/data/PUMSDataDict06.pdf", "PUMSDataDict06.pdf", method) data <- read.csv("ss06hid.csv") #rich <- data[data$VAL == 24,] print(sum(data$VAL == 24, na.rm=TRUE)) #=> 53
/dataanalysis.jhbsph/quiz_2/question_03.R
no_license
nkrot/my-moocs
R
false
false
1,030
r
# The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here: # # https://dl.dropbox.com/u/7710864/data/csv_hid/ss06hid.csv or here # https://spark-public.s3.amazonaws.com/dataanalysis/ss06hid.csv # # and load the data into R. You will use this data for the next several questions. The code book, describing the variable names is here: # #https://dl.dropbox.com/u/7710864/data/PUMSDataDict06.pdf or here: # #https://spark-public.s3.amazonaws.com/dataanalysis/PUMSDataDict06.pdf # #How many housing units in this survey were worth more than $1,000,000? # ok #method <- "curl" #download.file("https://dl.dropbox.com/u/7710864/data/csv_hid/ss06hid.csv", "ss06hid.csv", method) #download.file("https://dl.dropbox.com/u/7710864/data/PUMSDataDict06.pdf", "PUMSDataDict06.pdf", method) data <- read.csv("ss06hid.csv") #rich <- data[data$VAL == 24,] print(sum(data$VAL == 24, na.rm=TRUE)) #=> 53
#' @title Install rio's \sQuote{Suggests} Dependencies #' @description This function installs various \sQuote{Suggests} dependencies for rio that expand its support to the full range of support import and export formats. These packages are not installed or loaded by default in order to create a slimmer and faster package build, install, and load. #' @param \dots Additional arguments passed to \code{\link[utils]{install.packages}}. #' @return \code{NULL} #' @importFrom utils install.packages #' @export install_formats <- function(...) { to_install <- uninstalled_formats() if (length(to_install)) { utils::install.packages(to_install, ...) } return(TRUE) } #' @importFrom utils packageName uninstalled_formats <- function() { # Suggested packages (robust to changes in DESCRIPTION file) # Instead of flagging *new* suggestions by hand, this method only requires # flagging *non-import* suggestions (such as `devtools`, `knitr`, etc.). # This could be even more robust if the call to `install_formats()` instead # wrapped a call to `<devools|remotes>::install_deps(dependencies = # "Suggests")`, since this retains the package versioning (e.g. `xml2 (>= # 1.2.0)`) suggested in the `DESCRIPTION` file. However, this seems a bit # recursive, as `devtools` or `remotes` are often also in the `Suggests` # field. suggestions <- read.dcf(system.file("DESCRIPTION", package = utils::packageName(), mustWork = TRUE), fields = "Suggests") suggestions <- parse_suggestions(suggestions) common_suggestions <- c("bit64", "datasets", "devtools", "knitr", "magrittr", "testthat") suggestions <- setdiff(suggestions, common_suggestions) # which are not installed unlist(lapply(suggestions, function(x) { if (length(find.package(x, quiet = TRUE))) { NULL } else { x } })) } parse_suggestions <- function(suggestions) { suggestions <- unlist(strsplit(suggestions, split = ",|, |\n")) suggestions <- gsub("\\s*\\(.*\\)", "", suggestions) suggestions <- sort(suggestions[suggestions != ""]) suggestions }
/R/suggestions.R
no_license
cran/rio
R
false
false
2,197
r
#' @title Install rio's \sQuote{Suggests} Dependencies #' @description This function installs various \sQuote{Suggests} dependencies for rio that expand its support to the full range of support import and export formats. These packages are not installed or loaded by default in order to create a slimmer and faster package build, install, and load. #' @param \dots Additional arguments passed to \code{\link[utils]{install.packages}}. #' @return \code{NULL} #' @importFrom utils install.packages #' @export install_formats <- function(...) { to_install <- uninstalled_formats() if (length(to_install)) { utils::install.packages(to_install, ...) } return(TRUE) } #' @importFrom utils packageName uninstalled_formats <- function() { # Suggested packages (robust to changes in DESCRIPTION file) # Instead of flagging *new* suggestions by hand, this method only requires # flagging *non-import* suggestions (such as `devtools`, `knitr`, etc.). # This could be even more robust if the call to `install_formats()` instead # wrapped a call to `<devools|remotes>::install_deps(dependencies = # "Suggests")`, since this retains the package versioning (e.g. `xml2 (>= # 1.2.0)`) suggested in the `DESCRIPTION` file. However, this seems a bit # recursive, as `devtools` or `remotes` are often also in the `Suggests` # field. suggestions <- read.dcf(system.file("DESCRIPTION", package = utils::packageName(), mustWork = TRUE), fields = "Suggests") suggestions <- parse_suggestions(suggestions) common_suggestions <- c("bit64", "datasets", "devtools", "knitr", "magrittr", "testthat") suggestions <- setdiff(suggestions, common_suggestions) # which are not installed unlist(lapply(suggestions, function(x) { if (length(find.package(x, quiet = TRUE))) { NULL } else { x } })) } parse_suggestions <- function(suggestions) { suggestions <- unlist(strsplit(suggestions, split = ",|, |\n")) suggestions <- gsub("\\s*\\(.*\\)", "", suggestions) suggestions <- sort(suggestions[suggestions != ""]) suggestions }
# # fasp.R # # $Revision: 1.36 $ $Date: 2020/11/24 01:38:24 $ # # #----------------------------------------------------------------------------- # # creator fasp <- function(fns, which, formulae=NULL, dataname=NULL, title=NULL, rowNames=NULL, colNames=NULL, checkfv=TRUE) { stopifnot(is.list(fns)) stopifnot(is.matrix(which)) stopifnot(length(fns) == length(which)) n <- length(which) if(checkfv) for(i in seq_len(n)) if(!is.fv(fns[[i]])) stop(paste("fns[[", i, "]] is not an fv object", sep="")) # set row and column labels if(!is.null(rowNames)) rownames(which) <- rowNames if(!is.null(colNames)) colnames(which) <- colNames if(!is.null(formulae)) { # verify format and convert to character vector formulae <- FormatFaspFormulae(formulae, "formulae") # ensure length matches length of "fns" if(length(formulae) == 1L && n > 1L) # single formula - replicate it formulae <- rep.int(formulae, n) else stopifnot(length(formulae) == length(which)) } rslt <- list(fns=fns, which=which, default.formula=formulae, dataname=dataname, title=title) class(rslt) <- "fasp" return(rslt) } # subset extraction operator "[.fasp" <- function(x, I, J, drop=TRUE, ...) { verifyclass(x, "fasp") m <- nrow(x$which) n <- ncol(x$which) if(missing(I)) I <- 1:m if(missing(J)) J <- 1:n if(!is.vector(I) || !is.vector(J)) stop("Subset operator is only implemented for vector indices") # determine index subset for lists 'fns', 'titles' etc included <- rep.int(FALSE, length(x$fns)) w <- as.vector(x$which[I,J]) if(length(w) == 0) stop("result is empty") included[w] <- TRUE # if only one cell selected, and drop=TRUE: if((sum(included) == 1L) && drop) return(x$fns[included][[1L]]) # determine positions in shortened lists whichIJ <- x$which[I,J,drop=FALSE] newk <- cumsum(included) newwhich <- matrix(newk[whichIJ], ncol=ncol(whichIJ), nrow=nrow(whichIJ)) rownames(newwhich) <- rownames(x$which)[I] colnames(newwhich) <- colnames(x$which)[J] # default plotting formulae - could be NULL deform <- x$default.formula # create new fasp object Y <- fasp(fns = x$fns[included], formulae = if(!is.null(deform)) deform[included] else NULL, which = newwhich, dataname = x$dataname, title = x$title) return(Y) } dim.fasp <- function(x) { dim(x$which) } # print method print.fasp <- function(x, ...) { verifyclass(x, "fasp") cat(paste("Function array (class", sQuote("fasp"), ")\n")) dim <- dim(x$which) cat(paste("Dimensions: ", dim[1L], "x", dim[2L], "\n")) cat(paste("Title:", if(is.null(x$title)) "(None)" else x$title, "\n")) invisible(NULL) } # other methods as.fv.fasp <- function(x) do.call(cbind.fv, x$fns) dimnames.fasp <- function(x) { return(dimnames(x$which)) } "dimnames<-.fasp" <- function(x, value) { w <- x$which dimnames(w) <- value x$which <- w return(x) } ## other functions FormatFaspFormulae <- local({ zapit <- function(x, argname) { if(inherits(x, "formula")) deparse(x) else if(is.character(x)) x else stop(paste("The entries of", sQuote(argname), "must be formula objects or strings")) } FormatFaspFormulae <- function(f, argname) { ## f should be a single formula object, a list of formula objects, ## a character vector, or a list containing formulae and strings. ## It will be converted to a character vector. result <- if(is.character(f)) f else if(inherits(f, "formula")) deparse(f) else if(is.list(f)) unlist(lapply(f, zapit, argname=argname)) else stop(paste(sQuote(argname), "should be a formula, a list of formulae,", "or a character vector")) return(result) } FormatFaspFormulae })
/R/fasp.R
no_license
spatstat/spatstat.core
R
false
false
4,241
r
# # fasp.R # # $Revision: 1.36 $ $Date: 2020/11/24 01:38:24 $ # # #----------------------------------------------------------------------------- # # creator fasp <- function(fns, which, formulae=NULL, dataname=NULL, title=NULL, rowNames=NULL, colNames=NULL, checkfv=TRUE) { stopifnot(is.list(fns)) stopifnot(is.matrix(which)) stopifnot(length(fns) == length(which)) n <- length(which) if(checkfv) for(i in seq_len(n)) if(!is.fv(fns[[i]])) stop(paste("fns[[", i, "]] is not an fv object", sep="")) # set row and column labels if(!is.null(rowNames)) rownames(which) <- rowNames if(!is.null(colNames)) colnames(which) <- colNames if(!is.null(formulae)) { # verify format and convert to character vector formulae <- FormatFaspFormulae(formulae, "formulae") # ensure length matches length of "fns" if(length(formulae) == 1L && n > 1L) # single formula - replicate it formulae <- rep.int(formulae, n) else stopifnot(length(formulae) == length(which)) } rslt <- list(fns=fns, which=which, default.formula=formulae, dataname=dataname, title=title) class(rslt) <- "fasp" return(rslt) } # subset extraction operator "[.fasp" <- function(x, I, J, drop=TRUE, ...) { verifyclass(x, "fasp") m <- nrow(x$which) n <- ncol(x$which) if(missing(I)) I <- 1:m if(missing(J)) J <- 1:n if(!is.vector(I) || !is.vector(J)) stop("Subset operator is only implemented for vector indices") # determine index subset for lists 'fns', 'titles' etc included <- rep.int(FALSE, length(x$fns)) w <- as.vector(x$which[I,J]) if(length(w) == 0) stop("result is empty") included[w] <- TRUE # if only one cell selected, and drop=TRUE: if((sum(included) == 1L) && drop) return(x$fns[included][[1L]]) # determine positions in shortened lists whichIJ <- x$which[I,J,drop=FALSE] newk <- cumsum(included) newwhich <- matrix(newk[whichIJ], ncol=ncol(whichIJ), nrow=nrow(whichIJ)) rownames(newwhich) <- rownames(x$which)[I] colnames(newwhich) <- colnames(x$which)[J] # default plotting formulae - could be NULL deform <- x$default.formula # create new fasp object Y <- fasp(fns = x$fns[included], formulae = if(!is.null(deform)) deform[included] else NULL, which = newwhich, dataname = x$dataname, title = x$title) return(Y) } dim.fasp <- function(x) { dim(x$which) } # print method print.fasp <- function(x, ...) { verifyclass(x, "fasp") cat(paste("Function array (class", sQuote("fasp"), ")\n")) dim <- dim(x$which) cat(paste("Dimensions: ", dim[1L], "x", dim[2L], "\n")) cat(paste("Title:", if(is.null(x$title)) "(None)" else x$title, "\n")) invisible(NULL) } # other methods as.fv.fasp <- function(x) do.call(cbind.fv, x$fns) dimnames.fasp <- function(x) { return(dimnames(x$which)) } "dimnames<-.fasp" <- function(x, value) { w <- x$which dimnames(w) <- value x$which <- w return(x) } ## other functions FormatFaspFormulae <- local({ zapit <- function(x, argname) { if(inherits(x, "formula")) deparse(x) else if(is.character(x)) x else stop(paste("The entries of", sQuote(argname), "must be formula objects or strings")) } FormatFaspFormulae <- function(f, argname) { ## f should be a single formula object, a list of formula objects, ## a character vector, or a list containing formulae and strings. ## It will be converted to a character vector. result <- if(is.character(f)) f else if(inherits(f, "formula")) deparse(f) else if(is.list(f)) unlist(lapply(f, zapit, argname=argname)) else stop(paste(sQuote(argname), "should be a formula, a list of formulae,", "or a character vector")) return(result) } FormatFaspFormulae })
#Word Raster diagrams for https://www.musichistorystats.com/song-lyrics-3-repetition-and-compression/ library(tidyverse) library(tidytext) #for unnest_tokens library(extrafont) #optional for formatting chart #read in subset of lyrics data with just songs by main artists lyrics <- readRDS("lyrics_mainArtists.RDS") #add GZIP compression ratios lyrics <- lyrics %>% mutate(compress = map_int(lyrics, ~ length(memCompress(., type = "gzip"))) / nchar(lyrics)) #find an interesting song - modify as appropriate! song <- lyrics %>% filter(str_detect(artist,"Elton"), str_detect(title,"Yellow")) %>% sample_n(1) #split into words words <- song %>% unnest_tokens(word, lyrics) #create word raster diagram outer(words$word, words$word, "==") %>% #create logical matrix of repeated words as_tibble(.name_repair = "unique") %>% #convert to tibble mutate(Y = row_number()) %>% #add y axis data (x is the columns) pivot_longer(-Y, names_to = "X", values_to = "same") %>% #convert to long format for ggplot mutate(X = as.integer(str_remove_all(X, "\\."))) %>% #restore x axis to numeric ggplot(aes(x = X, y = Y, fill = same)) + geom_raster() + theme_minimal(base_family = "Cambria") + #base_family optional scale_x_continuous(name = "word") + scale_y_continuous(name = "word") + scale_fill_manual(values = c("lightyellow", "blue"), guide = FALSE) + coord_equal() + #force to be square ggtitle(paste(song$title[1], "by", song$artist[1]), subtitle = paste("Unique words", length(unique(words$word)), ":", round(100 * length(unique(words$word)) / nrow(words)), "% of total words\nGZIP Compression :", round(100 * song$compress), "%"))
/Word_Raster.R
no_license
andrewgustar/SongLyrics
R
false
false
1,941
r
#Word Raster diagrams for https://www.musichistorystats.com/song-lyrics-3-repetition-and-compression/ library(tidyverse) library(tidytext) #for unnest_tokens library(extrafont) #optional for formatting chart #read in subset of lyrics data with just songs by main artists lyrics <- readRDS("lyrics_mainArtists.RDS") #add GZIP compression ratios lyrics <- lyrics %>% mutate(compress = map_int(lyrics, ~ length(memCompress(., type = "gzip"))) / nchar(lyrics)) #find an interesting song - modify as appropriate! song <- lyrics %>% filter(str_detect(artist,"Elton"), str_detect(title,"Yellow")) %>% sample_n(1) #split into words words <- song %>% unnest_tokens(word, lyrics) #create word raster diagram outer(words$word, words$word, "==") %>% #create logical matrix of repeated words as_tibble(.name_repair = "unique") %>% #convert to tibble mutate(Y = row_number()) %>% #add y axis data (x is the columns) pivot_longer(-Y, names_to = "X", values_to = "same") %>% #convert to long format for ggplot mutate(X = as.integer(str_remove_all(X, "\\."))) %>% #restore x axis to numeric ggplot(aes(x = X, y = Y, fill = same)) + geom_raster() + theme_minimal(base_family = "Cambria") + #base_family optional scale_x_continuous(name = "word") + scale_y_continuous(name = "word") + scale_fill_manual(values = c("lightyellow", "blue"), guide = FALSE) + coord_equal() + #force to be square ggtitle(paste(song$title[1], "by", song$artist[1]), subtitle = paste("Unique words", length(unique(words$word)), ":", round(100 * length(unique(words$word)) / nrow(words)), "% of total words\nGZIP Compression :", round(100 * song$compress), "%"))
library(stringr) normcnt <- readRDS("~/selex2019/kmer_cnt_R_PCRBIAS/Trulig147v1III-Arin2-PCRbias-4DiffCycle-Phusion-2xx16dilu-0cycPCR-IIIc1-E1-ZhuBar96p1-bTAGTGTTG_S49_R1_001.peared_trimmed.fq.gz.RDS", refhook=NULL) aa <- vapply(normcnt$kmer, function(x) str_count(x, "A"), FUN.VALUE=numeric(1)) cc <- vapply(normcnt$kmer, function(x) str_count(x, "C"), FUN.VALUE=numeric(1)) gg <- vapply(normcnt$kmer, function(x) str_count(x, "G"), FUN.VALUE=numeric(1)) tt <- vapply(normcnt$kmer, function(x) str_count(x, "T"), FUN.VALUE=numeric(1)) kmerbasefreqs <- data.frame(aa, cc, gg, tt) saveRDS(kmerbasefreqs, file="~/github/selex2019/analysis/kmerbasefreqs.RDS", refhook=NULL)
/analysis/kmerbasefreqs.R
permissive
arinwongprommoon/selex2019
R
false
false
673
r
library(stringr) normcnt <- readRDS("~/selex2019/kmer_cnt_R_PCRBIAS/Trulig147v1III-Arin2-PCRbias-4DiffCycle-Phusion-2xx16dilu-0cycPCR-IIIc1-E1-ZhuBar96p1-bTAGTGTTG_S49_R1_001.peared_trimmed.fq.gz.RDS", refhook=NULL) aa <- vapply(normcnt$kmer, function(x) str_count(x, "A"), FUN.VALUE=numeric(1)) cc <- vapply(normcnt$kmer, function(x) str_count(x, "C"), FUN.VALUE=numeric(1)) gg <- vapply(normcnt$kmer, function(x) str_count(x, "G"), FUN.VALUE=numeric(1)) tt <- vapply(normcnt$kmer, function(x) str_count(x, "T"), FUN.VALUE=numeric(1)) kmerbasefreqs <- data.frame(aa, cc, gg, tt) saveRDS(kmerbasefreqs, file="~/github/selex2019/analysis/kmerbasefreqs.RDS", refhook=NULL)
# Curso de R - Primeira Parte # Exercício Adicionais # Todos exercícios devem ser escritos em um script salvo em uma pasta pessoal. # 1. Calcule a raiz quadrada de 144 sqrt(144) # 2. Escreva uma função "funcao" da soma de (x, x^2, x^3) # e calcule a função com x=1 e x=2 funcao <- function(x){ x+ x^2 + x^3} funcao(1) funcao(2) # 3. Escreva a função "funcao2" da multiplicação de z po w menos w # e calcule no ponto z=4 e w =2 funcao2 <- function(w, z){ w*z - w} funcao2(2, 4) # 4. Calcule a função anterior para w =2 e para z=1, z=2 e z=3 (Gera três resultados) funcao2(1:3, 4) # 5. Qual a descrição da função "rnorm"? help("rnorm") # Usando a descição acima gere uma normal com ... # 10 observações (n=10), média = 0 e desvio-padrão = 1 n <- 10 rnorm(n, mean = 0, sd = 1)
/Exercícios/Curso de R - Exercicios.R
no_license
ssh352/Curso-de-R
R
false
false
842
r
# Curso de R - Primeira Parte # Exercício Adicionais # Todos exercícios devem ser escritos em um script salvo em uma pasta pessoal. # 1. Calcule a raiz quadrada de 144 sqrt(144) # 2. Escreva uma função "funcao" da soma de (x, x^2, x^3) # e calcule a função com x=1 e x=2 funcao <- function(x){ x+ x^2 + x^3} funcao(1) funcao(2) # 3. Escreva a função "funcao2" da multiplicação de z po w menos w # e calcule no ponto z=4 e w =2 funcao2 <- function(w, z){ w*z - w} funcao2(2, 4) # 4. Calcule a função anterior para w =2 e para z=1, z=2 e z=3 (Gera três resultados) funcao2(1:3, 4) # 5. Qual a descrição da função "rnorm"? help("rnorm") # Usando a descição acima gere uma normal com ... # 10 observações (n=10), média = 0 e desvio-padrão = 1 n <- 10 rnorm(n, mean = 0, sd = 1)
export.dyadic <- function(blauObj){ if (is.null(blauObj$dyadic)){ message("Nothing to export.") } else{ return(blauObj$dyadic) } }
/R/export.dyadic.R
no_license
cran/Blaunet
R
false
false
147
r
export.dyadic <- function(blauObj){ if (is.null(blauObj$dyadic)){ message("Nothing to export.") } else{ return(blauObj$dyadic) } }
#setwd("D:\\USFCA\\6_Spring_Moduel_II\\622_Visualization\\HAG\\3due0410j") library(GGally) library(ggplot2) library(RColorBrewer) library(scales) library(shiny) # Objects defined outside of shinyServer() are visible to # all sessions. Objects defined instead of shinyServer() # are created per session. Place large shared data outside # and modify (filter/sort) local copies inside shinyServer(). # Loads global data to be shared by all sessions. loadData <- function() { df <- data.frame(state.x77, State = state.name, Abbrev = state.abb, Region = state.region, Division = state.division ) # Convert to factors. df$State <- as.factor(df$State) df$Abbrev <- as.factor(df$Abbrev) df$Region <- as.factor(df$Region) df$Division <- as.factor(df$Division) # Add a population density df$Pop.Density <- df$Population / df$Area return(df) } # Label formatter for numbers in millions. million_formatter <- function(x) { return(sprintf("%dk", round(x / 1000000))) } #### Create bubble plot #### getBubblePlot <- function(df, x, y, sizeBy, colorBy, abbrev) { # getBubblePlot(df2, "Population", "Income", "Population", "Region", T) # Get indices for aesthetics in ggplot to be used # xIndex <- which(colnames(df) == x) # yIndex <- which(colnames(df) == y) sizeIndex <- which(colnames(df) == sizeBy) # colorIndex <- which(colnames(df) == colorBy) # Sort in order to have smaller colors displayed on top of the bigger colors df <- df[order(df[,sizeIndex], decreasing = TRUE),] # Create actual bubble plot # p <- ggplot(df, aes_string(x = df[,xIndex], y = df[,yIndex])) + # geom_point(aes_string(size = df[,sizeIndex], color = df[,colorIndex]), alpha = 0.8) p <- ggplot(df, aes_string(x = x, y = y)) + geom_point(aes_string(size = sizeBy, color = colorBy), alpha = 0.8) # Option of having a state abbreviation if(abbrev){ p <- p + geom_text(aes(label = Abbrev), col="#000000", hjust=0.5, vjust=0) } # Default size scale is by radius, force to scale by area instead p <- p + scale_size_area(max_size = 20, guide = "none") # Modify the legend settings p <- p + theme(legend.title = element_blank()) p <- p + theme(legend.direction = "horizontal") p <- p + theme(legend.position = c(1, 0)) p <- p + theme(legend.justification = c(1, 0)) p <- p + theme(legend.background = element_blank()) p <- p + theme(legend.key = element_blank()) p <- p + theme(legend.text = element_text(size = 12)) # p <- p + theme(legend.margin = unit(0, "pt")) # Force the dots to plot larger in legend p <- p + guides(colour = guide_legend(override.aes = list(size = 8))) # Indicate size is bubble size # p <- p + annotate( # # "text", x = 6, y = 4.8, # "text", x = 600, y = 960, # hjust = 0.5, color = "grey40", # label = "Circle area is proportional to the 'Bubble Size'") return(p) } #### Create scatter plot matrix #### getScatterPlotMatrix <- function(df, variables, colorBy1){ # getScatterPlotMatrix(df2, c("Population", "Income"), "Region") # getScatterPlotMatrix(df2, c("Population", "Income", "Murder"), "Division") # Get indices in columns and variables idx <- 1:ncol(df) variableIndex <- idx[colnames(df) %in% variables] if (length(variableIndex) < 1) { df <- data.frame(ex = 0, wy = 0, labels = "Please, choose at least one variable.\n Or, if you know how to generate\n a scatterplot matrix with only one variable,\n please let me know.\n I am willing to learn from you.") p <- ggplot(df) + geom_text(aes(x=ex, y=wy, label = labels), size=15) + theme(axis.title.x = element_blank(), axis.title.y = element_blank()) } else{ p <- ggpairs(df, # Columns to include in the matrix columns = variableIndex, # What to include above diagonal # list(continuous = "points") to mirror # "blank" to turn off upper = "blank", # What to include below diagonal lower = list(continuous = "points"), # What to include in the diagonal diag = list(continuous = "density"), # How to label inner plots # internal, none, show axisLabels = "none", # Other aes() parameters colour = colorBy1, title = "Scatterplot Matrix", legends=T ) # ggpairs # + guides(colour = guide_legend("colorBy1")) # Create a (representative) legend (rather than individual ones) # I got the following code from StackOverFlow # http://stackoverflow.com/questions/22945702/how-to-add-an-external-legend-to-ggpairs for (i in 1:length(variableIndex)) { # Address only the diagonal elements # Get plot out of matrix inner <- getPlot(p, i, i); # Add any ggplot2 settings you want inner <- inner + theme(panel.grid = element_blank()) + theme(axis.text.x = element_blank()) # Put it back into the matrix p <- putPlot(p, inner, i, i) for (j in 1:length(variableIndex)){ if((i==1 & j==1)){ inner <- getPlot(p, i, j) inner <- inner + theme(legend.position=c(length(variableIndex)-0.25,0.50)) p <- putPlot(p, inner, i, j) } else{ inner <- getPlot(p, i, j) inner <- inner + theme(legend.position="none") p <- putPlot(p, inner, i, j) } } } } return(p) } #### Create parallel coordinates plot #### getPCP <- function(df, variables2, colorBy2, colorScheme, opacity, scaling) { # getPCP(df2, c("Population", "Income"), "Region", "Default", 0.8, "robust") # getPCP(df2, c("Population", "Income", "Murder"), "Division", "Set1", 0.8, "std") variableIndex <- (1:ncol(df))[colnames(df) %in% variables2] colorIndex <- (1:ncol(df))[colnames(df) == colorBy2] if (length(variableIndex) <= 1){ df <- data.frame(ex = 0, wy = 0, labels = "Please, choose at least two variables.\n Or, if you know how to generate\n a parallel coordinates plot with only two variables,\n please let me know.\n I am willing to learn from you.") p <- ggplot(df) + geom_text(aes(x=ex, y=wy, label = labels), size=12) + theme(axis.title.x = element_blank(), axis.title.y = element_blank()) } else{ p <- ggparcoord(data = df, # Which columns to use in the plot columns = variableIndex, # Which column to use for coloring data groupColumn = colorIndex, # Allows order of vertical bars to be modified order = "anyClass", # Do not show points showPoints = FALSE, # Turn on alpha blending for dense plots alphaLines = opacity, # Turn off box shading range shadeBox = NULL, # Will normalize each column's values to [0, 1] scale = scaling ) # Start with a basic theme p <- p + theme_minimal() # Decrease amount of margin around x, y values p <- p + scale_y_continuous(expand = c(0.02, 0.02)) p <- p + scale_x_discrete(expand = c(0.02, 0.02)) # Remove axis ticks and labels p <- p + theme(axis.ticks = element_blank()) p <- p + theme(axis.title = element_blank()) p <- p + theme(axis.text.y = element_blank()) # Clear axis lines p <- p + theme(panel.grid.minor = element_blank()) p <- p + theme(panel.grid.major.y = element_blank()) # Darken vertical lines p <- p + theme(panel.grid.major.x = element_line(color = "#bbbbbb")) # Move label to bottom p <- p + theme(legend.position = "bottom") + scale_color_brewer(palette = colorScheme) # # Figure out y-axis range after GGally scales the data # min_y <- min(p$data$value) # max_y <- max(p$data$value) # pad_y <- (max_y - min_y) * 0.1 # # # Calculate label positions for each veritcal bar # lab_x <- rep(colnames(df)[variableIndex], times = 2) # 2 times, 1 for min 1 for max # lab_y <- rep(c(min_y - pad_y, max_y + pad_y), each = 4) # # # Get min and max values from original dataset # lab_z <- c(sapply(df[,variableIndex], min), sapply(df[,variableIndex], max)) # # # Convert to character for use as labels # lab_z <- as.character(lab_z) # # # Add labels to plot # p <- p + annotate("text", x = lab_x, y = lab_y, label = lab_z, size = 3) p <- p + scale_colour_discrete(limits = levels(df[,colorIndex])) } # else return(p) } ##### GLOBAL OBJECTS ##### # Shared data globalData <- loadData() # Color-blind friendly palette from http://jfly.iam.u-tokyo.ac.jp/color/ palette1 <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") # Create labeler function that removes dots and # capitalizes the first letter niceLabels <- function(text) { text <- gsub("\\.", " ", text) text <- paste( toupper(substr(text, 1, 1)), substring(text, 2), sep = "", collapse = "") return(text) } ##### SHINY SERVER ##### # Create shiny server. Input comes from the UI input controls, # and the resulting output will be displayed on the page. shinyServer(function(input, output) { cat("Press \"ESC\" to exit...\n") # Copy the data frame (don't want to change the data # frame for other viewers) df <- globalData filter_color <- reactive({ switch(input$colorScheme, "Default" = "Default", "Accent" = "Accent", "Set1" = "Set1", "Set2" = "Set2", "Set3" = "Set3", "Dark2" = "Dark2", "Pastel1" = "Pastel1", "Pastel2" = "Pastel2") }) #### Render bubble plot #### output$BP <- renderPlot({ # Use our function to generate the plot bubblePlot <- getBubblePlot( df, x=input$x, y=input$y, sizeBy=input$sizeBy, colorBy=input$colorBy, abbrev=input$abbrev ) # getBubblePlot # Output the plot print(bubblePlot)}, height = 800, width = 1200) # renderPlot of "Bubble Plot" #### Render Scatterplot Matrix #### output$SPM <- renderPlot({ # Use our function to generate the plot scatterPlotMatrix <- getScatterPlotMatrix( df, variables=input$variables, colorBy1=input$colorBy1 ) # getScatterPlotMatrix # Output the plot print(scatterPlotMatrix)}, height = 800, width = 1200) # renderPlot of "Scatter Plot Matrix " #### Render Parallel Coordinates Plot #### output$PCP <- renderPlot({ # Use our function to generate the plot parallelcoordinatesPlot <- getPCP( df, variables2=input$variables2, colorBy2=input$colorBy2, colorScheme=input$colorScheme, opacity=input$opacity, scaling=input$scaling ) # getPCP # Output the plot print(parallelcoordinatesPlot)}, height = 750, width = 1000) # renderPlot of "Parallel Coordinates Plot" })
/homework3/server.R
no_license
excelsky/msan622
R
false
false
11,561
r
#setwd("D:\\USFCA\\6_Spring_Moduel_II\\622_Visualization\\HAG\\3due0410j") library(GGally) library(ggplot2) library(RColorBrewer) library(scales) library(shiny) # Objects defined outside of shinyServer() are visible to # all sessions. Objects defined instead of shinyServer() # are created per session. Place large shared data outside # and modify (filter/sort) local copies inside shinyServer(). # Loads global data to be shared by all sessions. loadData <- function() { df <- data.frame(state.x77, State = state.name, Abbrev = state.abb, Region = state.region, Division = state.division ) # Convert to factors. df$State <- as.factor(df$State) df$Abbrev <- as.factor(df$Abbrev) df$Region <- as.factor(df$Region) df$Division <- as.factor(df$Division) # Add a population density df$Pop.Density <- df$Population / df$Area return(df) } # Label formatter for numbers in millions. million_formatter <- function(x) { return(sprintf("%dk", round(x / 1000000))) } #### Create bubble plot #### getBubblePlot <- function(df, x, y, sizeBy, colorBy, abbrev) { # getBubblePlot(df2, "Population", "Income", "Population", "Region", T) # Get indices for aesthetics in ggplot to be used # xIndex <- which(colnames(df) == x) # yIndex <- which(colnames(df) == y) sizeIndex <- which(colnames(df) == sizeBy) # colorIndex <- which(colnames(df) == colorBy) # Sort in order to have smaller colors displayed on top of the bigger colors df <- df[order(df[,sizeIndex], decreasing = TRUE),] # Create actual bubble plot # p <- ggplot(df, aes_string(x = df[,xIndex], y = df[,yIndex])) + # geom_point(aes_string(size = df[,sizeIndex], color = df[,colorIndex]), alpha = 0.8) p <- ggplot(df, aes_string(x = x, y = y)) + geom_point(aes_string(size = sizeBy, color = colorBy), alpha = 0.8) # Option of having a state abbreviation if(abbrev){ p <- p + geom_text(aes(label = Abbrev), col="#000000", hjust=0.5, vjust=0) } # Default size scale is by radius, force to scale by area instead p <- p + scale_size_area(max_size = 20, guide = "none") # Modify the legend settings p <- p + theme(legend.title = element_blank()) p <- p + theme(legend.direction = "horizontal") p <- p + theme(legend.position = c(1, 0)) p <- p + theme(legend.justification = c(1, 0)) p <- p + theme(legend.background = element_blank()) p <- p + theme(legend.key = element_blank()) p <- p + theme(legend.text = element_text(size = 12)) # p <- p + theme(legend.margin = unit(0, "pt")) # Force the dots to plot larger in legend p <- p + guides(colour = guide_legend(override.aes = list(size = 8))) # Indicate size is bubble size # p <- p + annotate( # # "text", x = 6, y = 4.8, # "text", x = 600, y = 960, # hjust = 0.5, color = "grey40", # label = "Circle area is proportional to the 'Bubble Size'") return(p) } #### Create scatter plot matrix #### getScatterPlotMatrix <- function(df, variables, colorBy1){ # getScatterPlotMatrix(df2, c("Population", "Income"), "Region") # getScatterPlotMatrix(df2, c("Population", "Income", "Murder"), "Division") # Get indices in columns and variables idx <- 1:ncol(df) variableIndex <- idx[colnames(df) %in% variables] if (length(variableIndex) < 1) { df <- data.frame(ex = 0, wy = 0, labels = "Please, choose at least one variable.\n Or, if you know how to generate\n a scatterplot matrix with only one variable,\n please let me know.\n I am willing to learn from you.") p <- ggplot(df) + geom_text(aes(x=ex, y=wy, label = labels), size=15) + theme(axis.title.x = element_blank(), axis.title.y = element_blank()) } else{ p <- ggpairs(df, # Columns to include in the matrix columns = variableIndex, # What to include above diagonal # list(continuous = "points") to mirror # "blank" to turn off upper = "blank", # What to include below diagonal lower = list(continuous = "points"), # What to include in the diagonal diag = list(continuous = "density"), # How to label inner plots # internal, none, show axisLabels = "none", # Other aes() parameters colour = colorBy1, title = "Scatterplot Matrix", legends=T ) # ggpairs # + guides(colour = guide_legend("colorBy1")) # Create a (representative) legend (rather than individual ones) # I got the following code from StackOverFlow # http://stackoverflow.com/questions/22945702/how-to-add-an-external-legend-to-ggpairs for (i in 1:length(variableIndex)) { # Address only the diagonal elements # Get plot out of matrix inner <- getPlot(p, i, i); # Add any ggplot2 settings you want inner <- inner + theme(panel.grid = element_blank()) + theme(axis.text.x = element_blank()) # Put it back into the matrix p <- putPlot(p, inner, i, i) for (j in 1:length(variableIndex)){ if((i==1 & j==1)){ inner <- getPlot(p, i, j) inner <- inner + theme(legend.position=c(length(variableIndex)-0.25,0.50)) p <- putPlot(p, inner, i, j) } else{ inner <- getPlot(p, i, j) inner <- inner + theme(legend.position="none") p <- putPlot(p, inner, i, j) } } } } return(p) } #### Create parallel coordinates plot #### getPCP <- function(df, variables2, colorBy2, colorScheme, opacity, scaling) { # getPCP(df2, c("Population", "Income"), "Region", "Default", 0.8, "robust") # getPCP(df2, c("Population", "Income", "Murder"), "Division", "Set1", 0.8, "std") variableIndex <- (1:ncol(df))[colnames(df) %in% variables2] colorIndex <- (1:ncol(df))[colnames(df) == colorBy2] if (length(variableIndex) <= 1){ df <- data.frame(ex = 0, wy = 0, labels = "Please, choose at least two variables.\n Or, if you know how to generate\n a parallel coordinates plot with only two variables,\n please let me know.\n I am willing to learn from you.") p <- ggplot(df) + geom_text(aes(x=ex, y=wy, label = labels), size=12) + theme(axis.title.x = element_blank(), axis.title.y = element_blank()) } else{ p <- ggparcoord(data = df, # Which columns to use in the plot columns = variableIndex, # Which column to use for coloring data groupColumn = colorIndex, # Allows order of vertical bars to be modified order = "anyClass", # Do not show points showPoints = FALSE, # Turn on alpha blending for dense plots alphaLines = opacity, # Turn off box shading range shadeBox = NULL, # Will normalize each column's values to [0, 1] scale = scaling ) # Start with a basic theme p <- p + theme_minimal() # Decrease amount of margin around x, y values p <- p + scale_y_continuous(expand = c(0.02, 0.02)) p <- p + scale_x_discrete(expand = c(0.02, 0.02)) # Remove axis ticks and labels p <- p + theme(axis.ticks = element_blank()) p <- p + theme(axis.title = element_blank()) p <- p + theme(axis.text.y = element_blank()) # Clear axis lines p <- p + theme(panel.grid.minor = element_blank()) p <- p + theme(panel.grid.major.y = element_blank()) # Darken vertical lines p <- p + theme(panel.grid.major.x = element_line(color = "#bbbbbb")) # Move label to bottom p <- p + theme(legend.position = "bottom") + scale_color_brewer(palette = colorScheme) # # Figure out y-axis range after GGally scales the data # min_y <- min(p$data$value) # max_y <- max(p$data$value) # pad_y <- (max_y - min_y) * 0.1 # # # Calculate label positions for each veritcal bar # lab_x <- rep(colnames(df)[variableIndex], times = 2) # 2 times, 1 for min 1 for max # lab_y <- rep(c(min_y - pad_y, max_y + pad_y), each = 4) # # # Get min and max values from original dataset # lab_z <- c(sapply(df[,variableIndex], min), sapply(df[,variableIndex], max)) # # # Convert to character for use as labels # lab_z <- as.character(lab_z) # # # Add labels to plot # p <- p + annotate("text", x = lab_x, y = lab_y, label = lab_z, size = 3) p <- p + scale_colour_discrete(limits = levels(df[,colorIndex])) } # else return(p) } ##### GLOBAL OBJECTS ##### # Shared data globalData <- loadData() # Color-blind friendly palette from http://jfly.iam.u-tokyo.ac.jp/color/ palette1 <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7") # Create labeler function that removes dots and # capitalizes the first letter niceLabels <- function(text) { text <- gsub("\\.", " ", text) text <- paste( toupper(substr(text, 1, 1)), substring(text, 2), sep = "", collapse = "") return(text) } ##### SHINY SERVER ##### # Create shiny server. Input comes from the UI input controls, # and the resulting output will be displayed on the page. shinyServer(function(input, output) { cat("Press \"ESC\" to exit...\n") # Copy the data frame (don't want to change the data # frame for other viewers) df <- globalData filter_color <- reactive({ switch(input$colorScheme, "Default" = "Default", "Accent" = "Accent", "Set1" = "Set1", "Set2" = "Set2", "Set3" = "Set3", "Dark2" = "Dark2", "Pastel1" = "Pastel1", "Pastel2" = "Pastel2") }) #### Render bubble plot #### output$BP <- renderPlot({ # Use our function to generate the plot bubblePlot <- getBubblePlot( df, x=input$x, y=input$y, sizeBy=input$sizeBy, colorBy=input$colorBy, abbrev=input$abbrev ) # getBubblePlot # Output the plot print(bubblePlot)}, height = 800, width = 1200) # renderPlot of "Bubble Plot" #### Render Scatterplot Matrix #### output$SPM <- renderPlot({ # Use our function to generate the plot scatterPlotMatrix <- getScatterPlotMatrix( df, variables=input$variables, colorBy1=input$colorBy1 ) # getScatterPlotMatrix # Output the plot print(scatterPlotMatrix)}, height = 800, width = 1200) # renderPlot of "Scatter Plot Matrix " #### Render Parallel Coordinates Plot #### output$PCP <- renderPlot({ # Use our function to generate the plot parallelcoordinatesPlot <- getPCP( df, variables2=input$variables2, colorBy2=input$colorBy2, colorScheme=input$colorScheme, opacity=input$opacity, scaling=input$scaling ) # getPCP # Output the plot print(parallelcoordinatesPlot)}, height = 750, width = 1000) # renderPlot of "Parallel Coordinates Plot" })
## function to plot probability or trait value by branch ## written by Liam J. Revell 2013, 2014, 2016 plotBranchbyTrait<-function(tree,x,mode=c("edges","tips","nodes"),palette="rainbow",legend=TRUE,xlims=NULL,...){ mode<-mode[1] if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".") if(mode=="tips"){ x<-c(x[tree$tip.label],fastAnc(tree,x)) names(x)[1:length(tree$tip.label)]<-1:length(tree$tip.label) XX<-matrix(x[tree$edge],nrow(tree$edge),2) x<-rowMeans(XX) } else if(mode=="nodes"){ XX<-matrix(x[tree$edge],nrow(tree$edge),2) x<-rowMeans(XX) } # begin optional arguments if(hasArg(tol)) tol<-list(...)$tol else tol<-1e-6 if(hasArg(prompt)) prompt<-list(...)$prompt else prompt<-FALSE if(hasArg(type)) type<-list(...)$type else type<-"phylogram" if(hasArg(show.tip.label)) show.tip.label<-list(...)$show.tip.label else show.tip.label<-TRUE if(hasArg(show.node.label)) show.node.label<-list(...)$show.node.label else show.node.label<-FALSE if(hasArg(edge.width)) edge.width<-list(...)$edge.width else edge.width<-4 if(hasArg(edge.lty)) edge.lty<-list(...)$edge.lty else edge.lty<-1 if(hasArg(font)) font<-list(...)$font else font<-3 if(hasArg(cex)) cex<-list(...)$cex else cex<-par("cex") if(hasArg(adj)) adj<-list(...)$adj else adj<-NULL if(hasArg(srt)) srt<-list(...)$srt else srt<-0 if(hasArg(no.margin)) no.margin<-list(...)$no.margin else no.margin<-TRUE if(hasArg(root.edge)) root.edge<-list(...)$root.edge else root.edge<-FALSE if(hasArg(label.offset)) label.offset<-list(...)$label.offset else label.offset<-0.01*max(nodeHeights(tree)) if(hasArg(underscore)) underscore<-list(...)$underscore else underscore<-FALSE if(hasArg(x.lim)) x.lim<-list(...)$x.lim else x.lim<-NULL if(hasArg(y.lim)) y.lim<-list(...)$y.lim else y.lim<-if(legend&&!prompt&&type%in%c("phylogram","cladogram")) c(1-0.06*length(tree$tip.label),length(tree$tip.label)) else NULL if(hasArg(direction)) direction<-list(...)$direction else direction<-"rightwards" if(hasArg(lab4ut)) lab4ut<-list(...)$lab4ut else lab4ut<-NULL if(hasArg(tip.color)) tip.color<-list(...)$tip.color else tip.color<-"black" if(hasArg(plot)) plot<-list(...)$plot else plot<-TRUE if(hasArg(rotate.tree)) rotate.tree<-list(...)$rotate.tree else rotate.tree<-0 if(hasArg(open.angle)) open.angle<-list(...)$open.angle else open.angle<-0 # end optional arguments if(is.function(palette)) cols<-palette(n=1000) else { if(palette=="heat.colors") cols<-heat.colors(n=1000) if(palette=="gray") cols<-gray(1000:1/1000) if(palette=="rainbow") cols<-rainbow(1000,start=0.7,end=0) # blue->red } if(is.null(xlims)) xlims<-range(x)+c(-tol,tol) breaks<-0:1000/1000*(xlims[2]-xlims[1])+xlims[1] whichColor<-function(p,cols,breaks){ i<-1 while(p>=breaks[i]&&p>breaks[i+1]) i<-i+1 cols[i] } colors<-sapply(x,whichColor,cols=cols,breaks=breaks) par(lend=2) # now plot xx<-plot.phylo(tree,type=type,show.tip.label=show.tip.label,show.node.label=show.node.label,edge.color=colors, edge.width=edge.width,edge.lty=edge.lty,font=font,cex=cex,adj=adj,srt=srt,no.margin=no.margin,root.edge=root.edge, label.offset=label.offset,underscore=underscore,x.lim=x.lim,y.lim=y.lim,direction=direction,lab4ut=lab4ut, tip.color=tip.color,plot=plot,rotate.tree=rotate.tree,open.angle=open.angle,lend=2,new=FALSE) if(legend==TRUE&&is.logical(legend)) legend<-round(0.3*max(nodeHeights(tree)),2) if(legend){ if(hasArg(title)) title<-list(...)$title else title<-"trait value" if(hasArg(digits)) digits<-list(...)$digits else digits<-1 if(prompt) add.color.bar(legend,cols,title,xlims,digits,prompt=TRUE) else add.color.bar(legend,cols,title,xlims,digits,prompt=FALSE,x=par()$usr[1]+0.05*(par()$usr[2]-par()$usr[1]),y=par()$usr[3]+0.05*(par()$usr[4]-par()$usr[3])) } invisible(xx) } # function to add color bar # written by Liam J. Revell 2013, 2015, 2016 add.color.bar<-function(leg,cols,title=NULL,lims=c(0,1),digits=1,prompt=TRUE,lwd=4,outline=TRUE,...){ if(prompt){ cat("Click where you want to draw the bar\n") flush.console() x<-unlist(locator(1)) y<-x[2] x<-x[1] } else { if(hasArg(x)) x<-list(...)$x else x<-0 if(hasArg(y)) y<-list(...)$y else y<-0 } if(hasArg(fsize)) fsize<-list(...)$fsize else fsize<-1.0 if(hasArg(subtitle)) subtitle<-list(...)$subtitle else subtitle<-NULL if(hasArg(direction)) direction<-list(...)$direction else direction<-"rightwards" if(direction%in%c("rightwards","leftwards")){ X<-x+cbind(0:(length(cols)-1)/length(cols),1:length(cols)/length(cols))*(leg) if(direction=="leftwards"){ X<-X[nrow(X):1,] if(!is.null(lims)) lims<-lims[2:1] } Y<-cbind(rep(y,length(cols)),rep(y,length(cols))) } else if(direction%in%c("upwards","downwards")){ Y<-y+cbind(0:(length(cols)-1)/length(cols),1:length(cols)/length(cols))*(leg) if(direction=="downwards"){ X<-X[nrow(X):1,] if(!is.null(lims)) lims<-lims[2:1] } X<-cbind(rep(x,length(cols)),rep(x,length(cols))) } if(outline) lines(c(X[1,1],X[nrow(X),2]),c(Y[1,1],Y[nrow(Y),2]),lwd=lwd+2,lend=2) for(i in 1:length(cols)) lines(X[i,],Y[i,],col=cols[i],lwd=lwd,lend=2) if(direction%in%c("rightwards","leftwards")){ if(!is.null(lims)) text(x=x,y=y, round(lims[1],digits),pos=3,cex=fsize) if(!is.null(lims)) text(x=x+leg,y=y, round(lims[2],digits),pos=3,cex=fsize) if(is.null(title)) title<-"P(state=1)" text(x=(2*x+leg)/2,y=y,title,pos=3,cex=fsize) if(is.null(subtitle)) text(x=(2*x+leg)/2,y=y,paste("length=",round(leg,3),sep=""),pos=1,cex=fsize) else text(x=(2*x+leg)/2,y=y,subtitle,pos=1,cex=fsize) } else if(direction%in%c("upwards","downwards")){ if(!is.null(lims)) text(x=x,y=y-0.02*diff(par()$usr[3:4]),round(lims[1],digits), pos=1,cex=fsize) if(!is.null(lims)) text(x=x,y=y+leg+0.02*diff(par()$usr[3:4]), round(lims[2],digits), pos=3,cex=fsize) if(is.null(title)) title<-"P(state=1)" text(x=x-0.04*diff(par()$usr[1:2]),y=(2*y+leg)/2,title, pos=3,cex=fsize,srt=90) if(is.null(subtitle)) text(x=x+0.04*diff(par()$usr[1:2]),y=(2*y+leg)/2, paste("length=",round(leg,3),sep=""),pos=1, srt=90,cex=fsize) else text(x=x+0.04*diff(par()$usr[1:2]),y=(2*y+leg)/2, subtitle,pos=1,cex=fsize,srt=90) } }
/R/plotBranchbyTrait.R
no_license
olmen/phytools
R
false
false
6,247
r
## function to plot probability or trait value by branch ## written by Liam J. Revell 2013, 2014, 2016 plotBranchbyTrait<-function(tree,x,mode=c("edges","tips","nodes"),palette="rainbow",legend=TRUE,xlims=NULL,...){ mode<-mode[1] if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".") if(mode=="tips"){ x<-c(x[tree$tip.label],fastAnc(tree,x)) names(x)[1:length(tree$tip.label)]<-1:length(tree$tip.label) XX<-matrix(x[tree$edge],nrow(tree$edge),2) x<-rowMeans(XX) } else if(mode=="nodes"){ XX<-matrix(x[tree$edge],nrow(tree$edge),2) x<-rowMeans(XX) } # begin optional arguments if(hasArg(tol)) tol<-list(...)$tol else tol<-1e-6 if(hasArg(prompt)) prompt<-list(...)$prompt else prompt<-FALSE if(hasArg(type)) type<-list(...)$type else type<-"phylogram" if(hasArg(show.tip.label)) show.tip.label<-list(...)$show.tip.label else show.tip.label<-TRUE if(hasArg(show.node.label)) show.node.label<-list(...)$show.node.label else show.node.label<-FALSE if(hasArg(edge.width)) edge.width<-list(...)$edge.width else edge.width<-4 if(hasArg(edge.lty)) edge.lty<-list(...)$edge.lty else edge.lty<-1 if(hasArg(font)) font<-list(...)$font else font<-3 if(hasArg(cex)) cex<-list(...)$cex else cex<-par("cex") if(hasArg(adj)) adj<-list(...)$adj else adj<-NULL if(hasArg(srt)) srt<-list(...)$srt else srt<-0 if(hasArg(no.margin)) no.margin<-list(...)$no.margin else no.margin<-TRUE if(hasArg(root.edge)) root.edge<-list(...)$root.edge else root.edge<-FALSE if(hasArg(label.offset)) label.offset<-list(...)$label.offset else label.offset<-0.01*max(nodeHeights(tree)) if(hasArg(underscore)) underscore<-list(...)$underscore else underscore<-FALSE if(hasArg(x.lim)) x.lim<-list(...)$x.lim else x.lim<-NULL if(hasArg(y.lim)) y.lim<-list(...)$y.lim else y.lim<-if(legend&&!prompt&&type%in%c("phylogram","cladogram")) c(1-0.06*length(tree$tip.label),length(tree$tip.label)) else NULL if(hasArg(direction)) direction<-list(...)$direction else direction<-"rightwards" if(hasArg(lab4ut)) lab4ut<-list(...)$lab4ut else lab4ut<-NULL if(hasArg(tip.color)) tip.color<-list(...)$tip.color else tip.color<-"black" if(hasArg(plot)) plot<-list(...)$plot else plot<-TRUE if(hasArg(rotate.tree)) rotate.tree<-list(...)$rotate.tree else rotate.tree<-0 if(hasArg(open.angle)) open.angle<-list(...)$open.angle else open.angle<-0 # end optional arguments if(is.function(palette)) cols<-palette(n=1000) else { if(palette=="heat.colors") cols<-heat.colors(n=1000) if(palette=="gray") cols<-gray(1000:1/1000) if(palette=="rainbow") cols<-rainbow(1000,start=0.7,end=0) # blue->red } if(is.null(xlims)) xlims<-range(x)+c(-tol,tol) breaks<-0:1000/1000*(xlims[2]-xlims[1])+xlims[1] whichColor<-function(p,cols,breaks){ i<-1 while(p>=breaks[i]&&p>breaks[i+1]) i<-i+1 cols[i] } colors<-sapply(x,whichColor,cols=cols,breaks=breaks) par(lend=2) # now plot xx<-plot.phylo(tree,type=type,show.tip.label=show.tip.label,show.node.label=show.node.label,edge.color=colors, edge.width=edge.width,edge.lty=edge.lty,font=font,cex=cex,adj=adj,srt=srt,no.margin=no.margin,root.edge=root.edge, label.offset=label.offset,underscore=underscore,x.lim=x.lim,y.lim=y.lim,direction=direction,lab4ut=lab4ut, tip.color=tip.color,plot=plot,rotate.tree=rotate.tree,open.angle=open.angle,lend=2,new=FALSE) if(legend==TRUE&&is.logical(legend)) legend<-round(0.3*max(nodeHeights(tree)),2) if(legend){ if(hasArg(title)) title<-list(...)$title else title<-"trait value" if(hasArg(digits)) digits<-list(...)$digits else digits<-1 if(prompt) add.color.bar(legend,cols,title,xlims,digits,prompt=TRUE) else add.color.bar(legend,cols,title,xlims,digits,prompt=FALSE,x=par()$usr[1]+0.05*(par()$usr[2]-par()$usr[1]),y=par()$usr[3]+0.05*(par()$usr[4]-par()$usr[3])) } invisible(xx) } # function to add color bar # written by Liam J. Revell 2013, 2015, 2016 add.color.bar<-function(leg,cols,title=NULL,lims=c(0,1),digits=1,prompt=TRUE,lwd=4,outline=TRUE,...){ if(prompt){ cat("Click where you want to draw the bar\n") flush.console() x<-unlist(locator(1)) y<-x[2] x<-x[1] } else { if(hasArg(x)) x<-list(...)$x else x<-0 if(hasArg(y)) y<-list(...)$y else y<-0 } if(hasArg(fsize)) fsize<-list(...)$fsize else fsize<-1.0 if(hasArg(subtitle)) subtitle<-list(...)$subtitle else subtitle<-NULL if(hasArg(direction)) direction<-list(...)$direction else direction<-"rightwards" if(direction%in%c("rightwards","leftwards")){ X<-x+cbind(0:(length(cols)-1)/length(cols),1:length(cols)/length(cols))*(leg) if(direction=="leftwards"){ X<-X[nrow(X):1,] if(!is.null(lims)) lims<-lims[2:1] } Y<-cbind(rep(y,length(cols)),rep(y,length(cols))) } else if(direction%in%c("upwards","downwards")){ Y<-y+cbind(0:(length(cols)-1)/length(cols),1:length(cols)/length(cols))*(leg) if(direction=="downwards"){ X<-X[nrow(X):1,] if(!is.null(lims)) lims<-lims[2:1] } X<-cbind(rep(x,length(cols)),rep(x,length(cols))) } if(outline) lines(c(X[1,1],X[nrow(X),2]),c(Y[1,1],Y[nrow(Y),2]),lwd=lwd+2,lend=2) for(i in 1:length(cols)) lines(X[i,],Y[i,],col=cols[i],lwd=lwd,lend=2) if(direction%in%c("rightwards","leftwards")){ if(!is.null(lims)) text(x=x,y=y, round(lims[1],digits),pos=3,cex=fsize) if(!is.null(lims)) text(x=x+leg,y=y, round(lims[2],digits),pos=3,cex=fsize) if(is.null(title)) title<-"P(state=1)" text(x=(2*x+leg)/2,y=y,title,pos=3,cex=fsize) if(is.null(subtitle)) text(x=(2*x+leg)/2,y=y,paste("length=",round(leg,3),sep=""),pos=1,cex=fsize) else text(x=(2*x+leg)/2,y=y,subtitle,pos=1,cex=fsize) } else if(direction%in%c("upwards","downwards")){ if(!is.null(lims)) text(x=x,y=y-0.02*diff(par()$usr[3:4]),round(lims[1],digits), pos=1,cex=fsize) if(!is.null(lims)) text(x=x,y=y+leg+0.02*diff(par()$usr[3:4]), round(lims[2],digits), pos=3,cex=fsize) if(is.null(title)) title<-"P(state=1)" text(x=x-0.04*diff(par()$usr[1:2]),y=(2*y+leg)/2,title, pos=3,cex=fsize,srt=90) if(is.null(subtitle)) text(x=x+0.04*diff(par()$usr[1:2]),y=(2*y+leg)/2, paste("length=",round(leg,3),sep=""),pos=1, srt=90,cex=fsize) else text(x=x+0.04*diff(par()$usr[1:2]),y=(2*y+leg)/2, subtitle,pos=1,cex=fsize,srt=90) } }
#' Title #' #' @param yourdf #' @param var_name #' @param var_value #' #' @return #' @export #' #' @examples ggpetalplot <- function(yourdf, var_name, var_value) { varnum <- nrow(yourdf) x <- 1:(180 * varnum) y <- sin(x * pi / 180) mydf <- data.frame( var.x = x, var.y = abs(y), var = gl(varnum, 180, labels = yourdf %>% pull(var_name) ) ) %>% merge(yourdf, by.x = "var", by.y = var_name) %>% mutate(new_y = pull(., var.y) * pull(., var_value)) p1 <- ggplot(data = mydf, aes(x = var.x, y = new_y)) + geom_area(aes(fill = var), show.legend = F) + coord_polar() + theme_bw() + theme( axis.text.y = element_blank(), axis.title = element_blank(), panel.border = element_blank(), axis.ticks = element_blank() ) + scale_x_continuous( breaks = seq(90, 180 * varnum, 180), labels = yourdf %>% pull(var_name) ) + geom_text(data = yourdf, aes( x = seq(90, 180 * varnum, 180), y = (yourdf %>% pull(var_value)) + 1, label = yourdf %>% pull(var_value) )) + scale_fill_material_d() return(p1) }
/R/petalplot.R
no_license
NotebookOFXiaoMing/ggPetalPlot
R
false
false
1,179
r
#' Title #' #' @param yourdf #' @param var_name #' @param var_value #' #' @return #' @export #' #' @examples ggpetalplot <- function(yourdf, var_name, var_value) { varnum <- nrow(yourdf) x <- 1:(180 * varnum) y <- sin(x * pi / 180) mydf <- data.frame( var.x = x, var.y = abs(y), var = gl(varnum, 180, labels = yourdf %>% pull(var_name) ) ) %>% merge(yourdf, by.x = "var", by.y = var_name) %>% mutate(new_y = pull(., var.y) * pull(., var_value)) p1 <- ggplot(data = mydf, aes(x = var.x, y = new_y)) + geom_area(aes(fill = var), show.legend = F) + coord_polar() + theme_bw() + theme( axis.text.y = element_blank(), axis.title = element_blank(), panel.border = element_blank(), axis.ticks = element_blank() ) + scale_x_continuous( breaks = seq(90, 180 * varnum, 180), labels = yourdf %>% pull(var_name) ) + geom_text(data = yourdf, aes( x = seq(90, 180 * varnum, 180), y = (yourdf %>% pull(var_value)) + 1, label = yourdf %>% pull(var_value) )) + scale_fill_material_d() return(p1) }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fitR-package.r \name{sirStoch} \alias{sirStoch} \title{A simple stochastic SIR model with constant population size} \format{ A \code{\link{fitmodel}} object, that is a list with the following elements: } \description{ A simple stochastic SIR model with constant population size, uniform prior and Poisson observation. } \details{ \itemize{ \item \code{name} character. \item \code{stateNames} character vector. \item \code{thetaNames} character vector. \item \code{simulate} \R-function. \item \code{rPointObs} \R-function. \item \code{dprior} \R-function. \item \code{dPointObs} \R-function. } Look at the documentation of \code{\link{fitmodel}} for more details about each of these elements. You can look at the code of the \R-functions by typing \code{sirStoch$simulate} for instance. There are some comments included. } \keyword{internal}
/man/sirStoch.Rd
permissive
sbfnk/fitR
R
false
true
938
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fitR-package.r \name{sirStoch} \alias{sirStoch} \title{A simple stochastic SIR model with constant population size} \format{ A \code{\link{fitmodel}} object, that is a list with the following elements: } \description{ A simple stochastic SIR model with constant population size, uniform prior and Poisson observation. } \details{ \itemize{ \item \code{name} character. \item \code{stateNames} character vector. \item \code{thetaNames} character vector. \item \code{simulate} \R-function. \item \code{rPointObs} \R-function. \item \code{dprior} \R-function. \item \code{dPointObs} \R-function. } Look at the documentation of \code{\link{fitmodel}} for more details about each of these elements. You can look at the code of the \R-functions by typing \code{sirStoch$simulate} for instance. There are some comments included. } \keyword{internal}
#' Get RAVE version #' @export rave_version <- function(){ as.character(utils::packageVersion('rave')) } .onLoad <- function(libname, pkgname){ try({ # get rave_version old_ver = rave_options('rave_ver') old_ver %?<-% rave_hist()$get_or_save('..rave_ver..', '0.0.0.0000') new_ver = rave_version() is_newer = tryCatch({ is_newer = utils::compareVersion(old_ver, new_ver) < 0 if(!length(is_newer) || !is.logical(is_newer)){ is_newer = TRUE } is_newer }, error = function(e){ return(TRUE) }) if(is_newer){ rave_hist()$save( '..rave_startup_msg..' = sprintf('RAVE %s ==> %s. Module information has been updated.', old_ver, new_ver) ) # New RAVE installed! update # 3. Data files has_data = arrange_data_dir(TRUE) rave_hist()$save('..rave_ver..' = new_ver) # 1. additional settings rave_options( delay_input = 20, max_worker = future::availableCores() - 1, # crayon_enabled = TRUE, rave_ver = new_ver ) }else{ has_data = arrange_data_dir(F) } save_options() }) template_subcode = rave_options('threeBrain_template_subject') template_rootdir = rave_options('threeBrain_template_dir') if( length(template_subcode) && template_subcode != '' && dir.exists(template_rootdir) ){ options( `threeBrain.template_subject` = template_subcode, `threeBrain.template_dir` = template_rootdir ) } } .onUnload <- function(libpath){ clear_env(data_repository) } restart_r <- function(){ f <- get0(".rs.restartR") if (is.function(f)) { message("Restarting RStudio rsession. Might take a while. Please wait...") f() return(invisible()) } message("Using startup::restart()") startup::restart() return(invisible()) } #' @title Check and Install RAVE Dependencies #' @param update_rave logical, whether to update RAVE #' @param restart logical, whether to restart `RStudio` after installation #' @param nightly logical, whether to install develop version #' @param demo_data logical, whether to check demo data #' @param ... for compatibility purpose, ignored #' @export check_dependencies <- function(update_rave = TRUE, restart = TRUE, nightly = FALSE, demo_data = TRUE, ...){ # Check N27 brain dipsaus::cat2('Checking N27 brain', level = 'DEFAULT', end = '\n') threeBrain::merge_brain() dipsaus::cat2(' - Done', level = 'INFO', end = '\n') # Check demo subjects if( demo_data ){ dipsaus::cat2('Checking RAVE data repository', level = 'DEFAULT', end = '\n') p = get_projects() if(!length(p)){ has_demo = FALSE if('demo' %in% p){ subs = get_subjects('demo') if(length(subs)){ has_demo = TRUE } } if(!has_demo){ if(interactive()){ ans <- dipsaus::ask_yesno("There is no project found in data repository. Install demo subjects?") } else { ans <- TRUE } if(isTRUE(ans)){ # install demo subjects download_sample_data('_group_data', replace_if_exists = TRUE) download_sample_data('KC') download_sample_data('YAB') } } dipsaus::cat2(' - Done', level = 'INFO', end = '\n') } } lazy_install <- NULL lazy_github <- NULL # check if Rcpp version is 1.0.4 and os is macosx if(stringr::str_detect(R.version$os, "^darwin")){ rcpp_version <- utils::packageVersion('Rcpp') if(utils::compareVersion(as.character(rcpp_version), '1.0.4') == 0){ # you need to install lazy_install <- c(lazy_install, 'Rcpp') } } # Case 1: nightly is false, then use prebuilt version if(!nightly){ if(update_rave){ lazy_install <- c(lazy_install, 'rave') } dipsaus::prepare_install( unique(c(lazy_install, 'ravebuiltins', 'dipsaus', 'threeBrain', 'rutabaga')), restart = FALSE ) profile <- startup::find_rprofile() if (!length(profile)) { startup::install() } profile <- startup::find_rprofile() s <- readLines(profile) # find line sel <- s == "# --- dipsaus temporary startup (END)---" if(any(sel)){ idx <- which(sel) idx <- idx[[length(idx)]] - 1 # insert arrangement ss <- c( "try({", " userlib <- Sys.getenv('R_LIBS_USER')", " if(!dir.exists(userlib)){ try({ dir.create(userlib, recursive = TRUE) }) }", " dipsaus::cat2('Arranging all existing RAVE modules', level = 'DEFAULT', end = '\\n')", " rave::arrange_modules(refresh = TRUE, reset = FALSE, quiet = TRUE)", " message(' - Done.')", "})" ) s = c(s[seq_len(idx)], ss, s[-seq_len(idx)]) writeLines(s, profile) } if(restart){ restart_r() } return(invisible()) } # Case 2: nighly version deps <- list( list( name = 'rutabaga', note = 'Plot Helpers', repo = 'dipterix/rutabaga@develop' ), list( name = 'threeBrain', note = '3D Viewer', repo = 'dipterix/threeBrain' ), list( name = 'ravebuiltins', note = 'Default RAVE modules', repo = 'beauchamplab/ravebuiltins@migrate2' ) ) for(pinfo in deps){ catgl('Checking {pinfo$name} - {pinfo$note} (github: {pinfo$repo})', level = 'DEFAULT', end = '\n') tryCatch({ if(pinfo$name %in% loadedNamespaces()){ devtools::unload(pinfo$name, quiet = TRUE) } devtools::install_github(pinfo$repo, upgrade = FALSE, force = FALSE, quiet = TRUE) message(' - Done', end = '\n') }, error = function(e){ lazy_github <<- c(lazy_github, pinfo$repo) }) } # Now it's critical as dipsaus and rave cannot be updated here, register startup code lazy_install <- c(lazy_install, 'dipsaus') dipsaus::prepare_install(unique(lazy_install), restart = FALSE) profile <- startup::find_rprofile() if (!length(profile)) { startup::install() } profile <- startup::find_rprofile() s <- readLines(profile) # find line sel <- s == "# --- dipsaus temporary startup (END)---" if(any(sel)){ idx <- which(sel) idx <- idx[[length(idx)]] - 1 # insert arrangement update_txt = NULL if(update_rave){ update_txt <- c( " devtools::install_github('beauchamplab/rave@dev-1.0', upgrade = FALSE, force = FALSE, quiet = TRUE)" ) } update_txt = c( "try({devtools::install_github('dipterix/dipsaus', upgrade = FALSE, force = FALSE, quiet = TRUE)})", update_txt) ss <- c( "try({", " userlib <- Sys.getenv('R_LIBS_USER')", " if(!dir.exists(userlib)){ try({ dir.create(userlib, recursive = TRUE) }) }", update_txt, " dipsaus::cat2('Arranging all existing RAVE modules', level = 'DEFAULT', end = '\\n')", " rave::arrange_modules(refresh = TRUE, reset = FALSE, quiet = TRUE)", "})" ) s = c(s[seq_len(idx)], ss, s[-seq_len(idx)]) writeLines(s, profile) } if(restart){ restart_r() } return(invisible()) } check_dependencies2 <- function(){ # dipsaus::cat2('Arranging all existing RAVE modules', level = 'INFO', end = '\n') arrange_modules(refresh = TRUE, reset = FALSE, quiet = TRUE) # check if any demo data exists dipsaus::cat2('Checking RAVE data repository', level = 'INFO', end = '\n') p = get_projects() if('demo' %in% p){ subs = get_subjects('demo') if(length(subs)){ return(invisible()) } } # install demo subjects download_sample_data('_group_data', replace_if_exists = TRUE) download_sample_data('KC') download_sample_data('YAB') return(invisible()) } .onAttach <- function(libname, pkgname){ try({ if( arrange_data_dir(FALSE) ){ packageStartupMessage(sprintf(paste( "RAVE is loaded! - %s", "Data Repository: \t%s", "Raw-data Repository: \t%s", "\nTo set option, type %s.", sep = '\n' ), rave_version(), rave_options('data_dir'), rave_options('raw_data_dir'), sQuote('rave_options(launch_gui=TRUE)') )) }else{ packageStartupMessage('[WARNING]: Cannot find RAVE repository! Please run the following command set them.\n\trave::rave_options()') } }, silent = TRUE) try({ startup_msg = rave_hist()$get_or_save('..rave_startup_msg..') if(interactive() && !is.null(startup_msg)){ rave_hist()$save('..rave_startup_msg..' = NULL) packageStartupMessage(startup_msg) packageStartupMessage('Please run ', sQuote("rave::check_dependencies()"), " to check dependencies.") } }, silent = TRUE) }
/R/zzz.R
no_license
libertyh/rave
R
false
false
8,890
r
#' Get RAVE version #' @export rave_version <- function(){ as.character(utils::packageVersion('rave')) } .onLoad <- function(libname, pkgname){ try({ # get rave_version old_ver = rave_options('rave_ver') old_ver %?<-% rave_hist()$get_or_save('..rave_ver..', '0.0.0.0000') new_ver = rave_version() is_newer = tryCatch({ is_newer = utils::compareVersion(old_ver, new_ver) < 0 if(!length(is_newer) || !is.logical(is_newer)){ is_newer = TRUE } is_newer }, error = function(e){ return(TRUE) }) if(is_newer){ rave_hist()$save( '..rave_startup_msg..' = sprintf('RAVE %s ==> %s. Module information has been updated.', old_ver, new_ver) ) # New RAVE installed! update # 3. Data files has_data = arrange_data_dir(TRUE) rave_hist()$save('..rave_ver..' = new_ver) # 1. additional settings rave_options( delay_input = 20, max_worker = future::availableCores() - 1, # crayon_enabled = TRUE, rave_ver = new_ver ) }else{ has_data = arrange_data_dir(F) } save_options() }) template_subcode = rave_options('threeBrain_template_subject') template_rootdir = rave_options('threeBrain_template_dir') if( length(template_subcode) && template_subcode != '' && dir.exists(template_rootdir) ){ options( `threeBrain.template_subject` = template_subcode, `threeBrain.template_dir` = template_rootdir ) } } .onUnload <- function(libpath){ clear_env(data_repository) } restart_r <- function(){ f <- get0(".rs.restartR") if (is.function(f)) { message("Restarting RStudio rsession. Might take a while. Please wait...") f() return(invisible()) } message("Using startup::restart()") startup::restart() return(invisible()) } #' @title Check and Install RAVE Dependencies #' @param update_rave logical, whether to update RAVE #' @param restart logical, whether to restart `RStudio` after installation #' @param nightly logical, whether to install develop version #' @param demo_data logical, whether to check demo data #' @param ... for compatibility purpose, ignored #' @export check_dependencies <- function(update_rave = TRUE, restart = TRUE, nightly = FALSE, demo_data = TRUE, ...){ # Check N27 brain dipsaus::cat2('Checking N27 brain', level = 'DEFAULT', end = '\n') threeBrain::merge_brain() dipsaus::cat2(' - Done', level = 'INFO', end = '\n') # Check demo subjects if( demo_data ){ dipsaus::cat2('Checking RAVE data repository', level = 'DEFAULT', end = '\n') p = get_projects() if(!length(p)){ has_demo = FALSE if('demo' %in% p){ subs = get_subjects('demo') if(length(subs)){ has_demo = TRUE } } if(!has_demo){ if(interactive()){ ans <- dipsaus::ask_yesno("There is no project found in data repository. Install demo subjects?") } else { ans <- TRUE } if(isTRUE(ans)){ # install demo subjects download_sample_data('_group_data', replace_if_exists = TRUE) download_sample_data('KC') download_sample_data('YAB') } } dipsaus::cat2(' - Done', level = 'INFO', end = '\n') } } lazy_install <- NULL lazy_github <- NULL # check if Rcpp version is 1.0.4 and os is macosx if(stringr::str_detect(R.version$os, "^darwin")){ rcpp_version <- utils::packageVersion('Rcpp') if(utils::compareVersion(as.character(rcpp_version), '1.0.4') == 0){ # you need to install lazy_install <- c(lazy_install, 'Rcpp') } } # Case 1: nightly is false, then use prebuilt version if(!nightly){ if(update_rave){ lazy_install <- c(lazy_install, 'rave') } dipsaus::prepare_install( unique(c(lazy_install, 'ravebuiltins', 'dipsaus', 'threeBrain', 'rutabaga')), restart = FALSE ) profile <- startup::find_rprofile() if (!length(profile)) { startup::install() } profile <- startup::find_rprofile() s <- readLines(profile) # find line sel <- s == "# --- dipsaus temporary startup (END)---" if(any(sel)){ idx <- which(sel) idx <- idx[[length(idx)]] - 1 # insert arrangement ss <- c( "try({", " userlib <- Sys.getenv('R_LIBS_USER')", " if(!dir.exists(userlib)){ try({ dir.create(userlib, recursive = TRUE) }) }", " dipsaus::cat2('Arranging all existing RAVE modules', level = 'DEFAULT', end = '\\n')", " rave::arrange_modules(refresh = TRUE, reset = FALSE, quiet = TRUE)", " message(' - Done.')", "})" ) s = c(s[seq_len(idx)], ss, s[-seq_len(idx)]) writeLines(s, profile) } if(restart){ restart_r() } return(invisible()) } # Case 2: nighly version deps <- list( list( name = 'rutabaga', note = 'Plot Helpers', repo = 'dipterix/rutabaga@develop' ), list( name = 'threeBrain', note = '3D Viewer', repo = 'dipterix/threeBrain' ), list( name = 'ravebuiltins', note = 'Default RAVE modules', repo = 'beauchamplab/ravebuiltins@migrate2' ) ) for(pinfo in deps){ catgl('Checking {pinfo$name} - {pinfo$note} (github: {pinfo$repo})', level = 'DEFAULT', end = '\n') tryCatch({ if(pinfo$name %in% loadedNamespaces()){ devtools::unload(pinfo$name, quiet = TRUE) } devtools::install_github(pinfo$repo, upgrade = FALSE, force = FALSE, quiet = TRUE) message(' - Done', end = '\n') }, error = function(e){ lazy_github <<- c(lazy_github, pinfo$repo) }) } # Now it's critical as dipsaus and rave cannot be updated here, register startup code lazy_install <- c(lazy_install, 'dipsaus') dipsaus::prepare_install(unique(lazy_install), restart = FALSE) profile <- startup::find_rprofile() if (!length(profile)) { startup::install() } profile <- startup::find_rprofile() s <- readLines(profile) # find line sel <- s == "# --- dipsaus temporary startup (END)---" if(any(sel)){ idx <- which(sel) idx <- idx[[length(idx)]] - 1 # insert arrangement update_txt = NULL if(update_rave){ update_txt <- c( " devtools::install_github('beauchamplab/rave@dev-1.0', upgrade = FALSE, force = FALSE, quiet = TRUE)" ) } update_txt = c( "try({devtools::install_github('dipterix/dipsaus', upgrade = FALSE, force = FALSE, quiet = TRUE)})", update_txt) ss <- c( "try({", " userlib <- Sys.getenv('R_LIBS_USER')", " if(!dir.exists(userlib)){ try({ dir.create(userlib, recursive = TRUE) }) }", update_txt, " dipsaus::cat2('Arranging all existing RAVE modules', level = 'DEFAULT', end = '\\n')", " rave::arrange_modules(refresh = TRUE, reset = FALSE, quiet = TRUE)", "})" ) s = c(s[seq_len(idx)], ss, s[-seq_len(idx)]) writeLines(s, profile) } if(restart){ restart_r() } return(invisible()) } check_dependencies2 <- function(){ # dipsaus::cat2('Arranging all existing RAVE modules', level = 'INFO', end = '\n') arrange_modules(refresh = TRUE, reset = FALSE, quiet = TRUE) # check if any demo data exists dipsaus::cat2('Checking RAVE data repository', level = 'INFO', end = '\n') p = get_projects() if('demo' %in% p){ subs = get_subjects('demo') if(length(subs)){ return(invisible()) } } # install demo subjects download_sample_data('_group_data', replace_if_exists = TRUE) download_sample_data('KC') download_sample_data('YAB') return(invisible()) } .onAttach <- function(libname, pkgname){ try({ if( arrange_data_dir(FALSE) ){ packageStartupMessage(sprintf(paste( "RAVE is loaded! - %s", "Data Repository: \t%s", "Raw-data Repository: \t%s", "\nTo set option, type %s.", sep = '\n' ), rave_version(), rave_options('data_dir'), rave_options('raw_data_dir'), sQuote('rave_options(launch_gui=TRUE)') )) }else{ packageStartupMessage('[WARNING]: Cannot find RAVE repository! Please run the following command set them.\n\trave::rave_options()') } }, silent = TRUE) try({ startup_msg = rave_hist()$get_or_save('..rave_startup_msg..') if(interactive() && !is.null(startup_msg)){ rave_hist()$save('..rave_startup_msg..' = NULL) packageStartupMessage(startup_msg) packageStartupMessage('Please run ', sQuote("rave::check_dependencies()"), " to check dependencies.") } }, silent = TRUE) }
\name{viewseis} \alias{viewseis} \title{View Continuous Data } \description{ Scroll through continuous data recorded in the field. Uses a database describing the locations and content of each file stored on disk. } \usage{ viewseis(DBnov , gstas, gcomps,sched, stas, buts='GPIX', replot=TRUE , kind=0, Iendian=1, BIGLONG=FALSE) } \arguments{ \item{DBnov}{RSEIS Data Base } \item{gstas}{stations to extract } \item{gcomps}{components to extract } \item{sched}{schedule of start times for extraction } \item{stas}{station list } \item{buts}{ buttons for swig } \item{replot}{ logical, TRUE=rerun swig after done click } \item{kind}{ kind of data, 0=nativeR, 1=segy, 2=sac } \item{Iendian}{endian } \item{BIGLONG}{big long or short long } } \details{ These are set up for the seis dataset } \value{Graphics, and Side effects } \author{ Jonathan M. Lees<jonathan.lees@unc.edu> } \seealso{makeDB, Mine.seis } \examples{ \dontrun{ sched =seq(from=325, to=335, by=1/24) viewseis( DBnov , gstas, gcomps , sched, kind=2, Iendian=1, BIGLONG=FALSE) } } \keyword{misc}
/man/viewseis.Rd
no_license
cran/Rquake
R
false
false
1,083
rd
\name{viewseis} \alias{viewseis} \title{View Continuous Data } \description{ Scroll through continuous data recorded in the field. Uses a database describing the locations and content of each file stored on disk. } \usage{ viewseis(DBnov , gstas, gcomps,sched, stas, buts='GPIX', replot=TRUE , kind=0, Iendian=1, BIGLONG=FALSE) } \arguments{ \item{DBnov}{RSEIS Data Base } \item{gstas}{stations to extract } \item{gcomps}{components to extract } \item{sched}{schedule of start times for extraction } \item{stas}{station list } \item{buts}{ buttons for swig } \item{replot}{ logical, TRUE=rerun swig after done click } \item{kind}{ kind of data, 0=nativeR, 1=segy, 2=sac } \item{Iendian}{endian } \item{BIGLONG}{big long or short long } } \details{ These are set up for the seis dataset } \value{Graphics, and Side effects } \author{ Jonathan M. Lees<jonathan.lees@unc.edu> } \seealso{makeDB, Mine.seis } \examples{ \dontrun{ sched =seq(from=325, to=335, by=1/24) viewseis( DBnov , gstas, gcomps , sched, kind=2, Iendian=1, BIGLONG=FALSE) } } \keyword{misc}
##################################################################### # # mqmcircleplot.R # # Copyright (c) 2009-2010, Danny Arends # # Modified by Pjotr Prins and Karl Broman # # # first written Februari 2009 # last modified March 2010 # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License, # version 3, as published by the Free Software Foundation. # # 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, version 3, for more details. # # A copy of the GNU General Public License, version 3, is available # at http://www.r-project.org/Licenses/GPL-3 # # Part of the R/qtl package # Contains: mqmplot_c # mqmplotcircle # mqmplot_circle # circlelocations # drawspline # getchromosomelength # getgenomelength # locationtocircle # drawcirculargenome # loopthroughmulti # # ##################################################################### mqmplot.circle <- function(cross, result, highlight=0, spacing=25, interactstrength=2,legend=FALSE, verbose=FALSE, transparency=FALSE){ if(is.null(cross)){ stop("No cross object. Please supply a valid cross object.") } retresults <- NULL lod<-FALSE if(any(class(result)=="mqmmulti")){ if(highlight > 0){ templateresult <- mqmextractmarkers(result[[highlight]]) lod<-TRUE }else{ templateresult <- mqmextractmarkers(result[[1]]) lod<-FALSE } }else{ templateresult <- mqmextractmarkers(result) lod<-TRUE } if(!("scanone" %in% class(templateresult))){ stop("Wrong type of result file, please supply a valid scanone object.") } if(transparency){ colorz <- rainbow(length(result),alpha=0.8) }else{ colorz <- rainbow(length(result)) } if(!legend){ totallength <- getgenomelength(templateresult) nchr <- length(unique(templateresult[,1])) cvalues <- circlelocations(totallength+(nchr*spacing)) drawcirculargenome(templateresult,spacing=spacing,lod=lod) if(any(class(result)=="mqmmulti")){ #multiple scan results, so plot em all todo <- 1:length(result) if(highlight!=0){ #Unless we highlight only one of them todo <- highlight } for(x in todo){ model <- mqmgetmodel(result[[x]]) if(!is.null(model)){ if(verbose) cat("Model found for trait ",x,"\n") if(!is.null(cross$locations)){ if(verbose) cat("Locations of traits available\n") location <- as.numeric(cross$locations[[x]]) traitl <- locationtocircle(templateresult,location[1],location[2],spacing=spacing) }else{ if(verbose) cat("Locations of traits not available\n") traitl <- t(c(0,0+0.25*(0.5-(x/length(result))))) } if(highlight==0){ col=colorz[x] }else{ col=rgb(0.1, 0.1, 0.1, 0.1) if(highlight==x) title(sub = paste("Highlight of:",colnames(cross$pheno)[x])) } for(y in 1:length(model[[4]])){ qtll <- locationtocircle(templateresult,model[[4]][y],model[[5]][y],spacing=spacing) if(highlight==x){ for(z in y:length(model[[4]])){ if(!z==y){ cross <- sim.geno(cross) eff <- effectplot(cross,pheno.col=x,mname1=model$name[y],mname2=model$name[z],draw=FALSE) changeA <- (eff$Means[1,2]-eff$Means[1,1]) changeB <- (eff$Means[2,2]-eff$Means[2,1]) #interaction qtl2 <- locationtocircle(templateresult,model[[4]][z],model[[5]][z],spacing=spacing) if(!is.na(changeA) && !is.na(changeB) && !any(is.na(eff$SEs))){ col <- "blue" if(changeA/abs(changeA) < changeB/abs(changeB)) col <- "green" if(abs(abs(changeA)-abs(changeB)) > interactstrength*mean(eff$SEs)){ retresults <- rbind(retresults,c(model$name[y],model$name[z],changeA,changeB,mean(eff$SEs))) drawspline(qtll,qtl2,lwd=2,col=col) } } } } } if(highlight==0){ points(traitl,col=col,pch=24,cex=1) drawspline(traitl,qtll,col=col) points(qtll*(1+0.1*((x/length(result)))),col=col,pch=19,cex=1) } } }else{ if(verbose) cat("Trait ",x," has no model\n") } } legend("topleft",c("Trait","QTL"),col=c("black","black"),pch=c(24,19),cex=1) } if(any(class(result)=="scanone") || highlight > 0){ #single scan result or highlighting one of the multiple if(!any(class(result)=="scanone")){ #Just highlight the template result result <- templateresult } model <- mqmgetmodel(result) if(!is.null(model)){ for(y in 1:length(model[[4]])){ qtll <- locationtocircle(templateresult,model[[4]][y],model[[5]][y],spacing=spacing) points(qtll,col="red",pch=19,cex=1) text(qtll*1.15,model[[2]][y],col="red",cex=0.7) if(!is.null(cross$locations)){ location <- as.numeric(cross$locations[[highlight]]) traitl <- locationtocircle(templateresult,location[1],location[2],spacing=spacing) points(traitl,col="red",lwd=2,pch=24,cex=1.5) }else{ traitl <- c(0,0) } if(!(highlight>0))drawspline(traitl,qtll,col="red") } } legend("bottomright",c("Significant Cofactor","Interaction Increase","Interaction Decrease"),col=c("red","blue","green"),pch=19,lwd=c(0,1,2),cex=0.75) if(highlight==0) title(sub = "Single trait") } }else{ plot(c(-1,1), c(-1, 1), type = "n", axes = FALSE, xlab = "", ylab = "") title(main = "Legend to circular genome plot") legend("center",paste(colnames(cross$pheno)),col=colorz,pch=19,cex=0.75) } if(!is.null(retresults)){ colnames(retresults) <- c("Marker","Marker","Change","Change","SEs") retresults <- as.data.frame(retresults) return(invisible(retresults)) } } circlelocations <- function(nt){ medpoints <- matrix(nrow = nt, ncol = 2) phi <- seq(0, 2 * pi, length = (nt + 1)) complex.circle <- complex(modulus = 1, argument = phi) for (j in 1:nt) { medpoints[j, ] <- c(Im(complex.circle[j]), Re(complex.circle[j])) } medpoints } drawspline <- function (cn1, cn2, lwd = 1,col="blue",...){ x <- cbind(cn1[1],0,cn2[1]) y <- cbind(cn1[2],0,cn2[2]) r <- xspline(x, y, lty=1, shape=1, lwd=lwd, border=col,...) } getchromosomelength <- function(result, chr){ l <- ceiling(max(result[which(result[,1]==chr),2])) l } getgenomelength <- function(result){ l <- 1 for(x in unique(result[,1])){ l <- l + getchromosomelength(result,x) } l } locationtocircle <- function(result, chr, loc, spacing=50, fixoutofbounds=TRUE, verbose=FALSE){ templateresult <- result totallength <- getgenomelength(result) nchr <- length(unique(templateresult[,1])) cvalues <- circlelocations(totallength+(nchr*spacing)) l <- 1 for(x in unique(templateresult[,1])){ if(x==chr){ if(loc < getchromosomelength(result,x)){ return(t(cvalues[(l+loc),])) }else{ if(verbose) cat("Location out of chromosome bounds",loc," ",getchromosomelength(result,x),"\n") if(fixoutofbounds) return(t(cvalues[(l+getchromosomelength(result,x)),])) stop(paste("Location out of chromosome bounds",loc," ",getchromosomelength(result,x),"\n")) } } l <- l + getchromosomelength(result,x) + spacing } stop("No such chromosome") } drawcirculargenome <- function(result,lodmarkers=FALSE,spacing=50){ result <- mqmextractmarkers(result) plot(c(-1.1, 1.1), c(-1.1, 1.1), type = "n", axes = FALSE, xlab = "", ylab = "") title(main = "Circular genome plot") totallength <- getgenomelength(result) nchr <- length(unique(result[,1])) cvalues <- circlelocations(totallength+(nchr*spacing)) l <- 1 for(x in unique(result[,1])){ #Draw chromosomes nl <- l+getchromosomelength(result,x) lines(cvalues[l:nl,],cex=0.01) l <- nl + spacing } for(x in 1:nrow(result)){ #Draw markers if(lodmarkers){ size <- min(c((result[x,3]/2+1),4)) c <- gray(0.5-(0.4*(result[x,3]/max(result[,3])))) points(locationtocircle(result,result[x,1],result[x,2],spacing=spacing),pch=20,col=c,cex=size) }else{ points(locationtocircle(result,result[x,1],result[x,2],spacing=spacing),pch=20) } } for(x in 1:nchr){ chrnumberloc <- locationtocircle(result,x,getchromosomelength(result,x)/2,spacing=spacing) points(t(c(-1.1, -1.15))) points(t(c(-0.9, -1.15))) points(t(c(-0.7, -1.15))) text(t(c(-0.9, -1.0)),paste("Distances in cM"),cex=0.6) text(t(c(-1.1, -1.1)),paste("0 cM"),cex=0.6) text(t(c(-0.9, -1.1)),paste(round((totallength+(nchr*spacing))*(0.2/(2*pi)),dig=1),"cM"),cex=0.6) text(t(c(-0.7, -1.1)),paste(round((totallength+(nchr*spacing))*(0.4/(2*pi)),dig=1),"cM"),cex=0.6) text(0.9*chrnumberloc,paste("Chr",x),cex=0.6) } } loopthroughmulti <- function(cross,result,save=FALSE,spacing=100){ n <- 1 while(n <= length(result)){ if(save) png(file=paste("circleplotT",n,".png",sep=""),w=1024,h=768) mqmplot.circle(cross,result,spacing=spacing,highlight=n) if(save) dev.off() n <- n+1 } }
/R/mqmcircleplot.R
no_license
pjotrp/rqtl-mqm
R
false
false
9,763
r
##################################################################### # # mqmcircleplot.R # # Copyright (c) 2009-2010, Danny Arends # # Modified by Pjotr Prins and Karl Broman # # # first written Februari 2009 # last modified March 2010 # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License, # version 3, as published by the Free Software Foundation. # # 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, version 3, for more details. # # A copy of the GNU General Public License, version 3, is available # at http://www.r-project.org/Licenses/GPL-3 # # Part of the R/qtl package # Contains: mqmplot_c # mqmplotcircle # mqmplot_circle # circlelocations # drawspline # getchromosomelength # getgenomelength # locationtocircle # drawcirculargenome # loopthroughmulti # # ##################################################################### mqmplot.circle <- function(cross, result, highlight=0, spacing=25, interactstrength=2,legend=FALSE, verbose=FALSE, transparency=FALSE){ if(is.null(cross)){ stop("No cross object. Please supply a valid cross object.") } retresults <- NULL lod<-FALSE if(any(class(result)=="mqmmulti")){ if(highlight > 0){ templateresult <- mqmextractmarkers(result[[highlight]]) lod<-TRUE }else{ templateresult <- mqmextractmarkers(result[[1]]) lod<-FALSE } }else{ templateresult <- mqmextractmarkers(result) lod<-TRUE } if(!("scanone" %in% class(templateresult))){ stop("Wrong type of result file, please supply a valid scanone object.") } if(transparency){ colorz <- rainbow(length(result),alpha=0.8) }else{ colorz <- rainbow(length(result)) } if(!legend){ totallength <- getgenomelength(templateresult) nchr <- length(unique(templateresult[,1])) cvalues <- circlelocations(totallength+(nchr*spacing)) drawcirculargenome(templateresult,spacing=spacing,lod=lod) if(any(class(result)=="mqmmulti")){ #multiple scan results, so plot em all todo <- 1:length(result) if(highlight!=0){ #Unless we highlight only one of them todo <- highlight } for(x in todo){ model <- mqmgetmodel(result[[x]]) if(!is.null(model)){ if(verbose) cat("Model found for trait ",x,"\n") if(!is.null(cross$locations)){ if(verbose) cat("Locations of traits available\n") location <- as.numeric(cross$locations[[x]]) traitl <- locationtocircle(templateresult,location[1],location[2],spacing=spacing) }else{ if(verbose) cat("Locations of traits not available\n") traitl <- t(c(0,0+0.25*(0.5-(x/length(result))))) } if(highlight==0){ col=colorz[x] }else{ col=rgb(0.1, 0.1, 0.1, 0.1) if(highlight==x) title(sub = paste("Highlight of:",colnames(cross$pheno)[x])) } for(y in 1:length(model[[4]])){ qtll <- locationtocircle(templateresult,model[[4]][y],model[[5]][y],spacing=spacing) if(highlight==x){ for(z in y:length(model[[4]])){ if(!z==y){ cross <- sim.geno(cross) eff <- effectplot(cross,pheno.col=x,mname1=model$name[y],mname2=model$name[z],draw=FALSE) changeA <- (eff$Means[1,2]-eff$Means[1,1]) changeB <- (eff$Means[2,2]-eff$Means[2,1]) #interaction qtl2 <- locationtocircle(templateresult,model[[4]][z],model[[5]][z],spacing=spacing) if(!is.na(changeA) && !is.na(changeB) && !any(is.na(eff$SEs))){ col <- "blue" if(changeA/abs(changeA) < changeB/abs(changeB)) col <- "green" if(abs(abs(changeA)-abs(changeB)) > interactstrength*mean(eff$SEs)){ retresults <- rbind(retresults,c(model$name[y],model$name[z],changeA,changeB,mean(eff$SEs))) drawspline(qtll,qtl2,lwd=2,col=col) } } } } } if(highlight==0){ points(traitl,col=col,pch=24,cex=1) drawspline(traitl,qtll,col=col) points(qtll*(1+0.1*((x/length(result)))),col=col,pch=19,cex=1) } } }else{ if(verbose) cat("Trait ",x," has no model\n") } } legend("topleft",c("Trait","QTL"),col=c("black","black"),pch=c(24,19),cex=1) } if(any(class(result)=="scanone") || highlight > 0){ #single scan result or highlighting one of the multiple if(!any(class(result)=="scanone")){ #Just highlight the template result result <- templateresult } model <- mqmgetmodel(result) if(!is.null(model)){ for(y in 1:length(model[[4]])){ qtll <- locationtocircle(templateresult,model[[4]][y],model[[5]][y],spacing=spacing) points(qtll,col="red",pch=19,cex=1) text(qtll*1.15,model[[2]][y],col="red",cex=0.7) if(!is.null(cross$locations)){ location <- as.numeric(cross$locations[[highlight]]) traitl <- locationtocircle(templateresult,location[1],location[2],spacing=spacing) points(traitl,col="red",lwd=2,pch=24,cex=1.5) }else{ traitl <- c(0,0) } if(!(highlight>0))drawspline(traitl,qtll,col="red") } } legend("bottomright",c("Significant Cofactor","Interaction Increase","Interaction Decrease"),col=c("red","blue","green"),pch=19,lwd=c(0,1,2),cex=0.75) if(highlight==0) title(sub = "Single trait") } }else{ plot(c(-1,1), c(-1, 1), type = "n", axes = FALSE, xlab = "", ylab = "") title(main = "Legend to circular genome plot") legend("center",paste(colnames(cross$pheno)),col=colorz,pch=19,cex=0.75) } if(!is.null(retresults)){ colnames(retresults) <- c("Marker","Marker","Change","Change","SEs") retresults <- as.data.frame(retresults) return(invisible(retresults)) } } circlelocations <- function(nt){ medpoints <- matrix(nrow = nt, ncol = 2) phi <- seq(0, 2 * pi, length = (nt + 1)) complex.circle <- complex(modulus = 1, argument = phi) for (j in 1:nt) { medpoints[j, ] <- c(Im(complex.circle[j]), Re(complex.circle[j])) } medpoints } drawspline <- function (cn1, cn2, lwd = 1,col="blue",...){ x <- cbind(cn1[1],0,cn2[1]) y <- cbind(cn1[2],0,cn2[2]) r <- xspline(x, y, lty=1, shape=1, lwd=lwd, border=col,...) } getchromosomelength <- function(result, chr){ l <- ceiling(max(result[which(result[,1]==chr),2])) l } getgenomelength <- function(result){ l <- 1 for(x in unique(result[,1])){ l <- l + getchromosomelength(result,x) } l } locationtocircle <- function(result, chr, loc, spacing=50, fixoutofbounds=TRUE, verbose=FALSE){ templateresult <- result totallength <- getgenomelength(result) nchr <- length(unique(templateresult[,1])) cvalues <- circlelocations(totallength+(nchr*spacing)) l <- 1 for(x in unique(templateresult[,1])){ if(x==chr){ if(loc < getchromosomelength(result,x)){ return(t(cvalues[(l+loc),])) }else{ if(verbose) cat("Location out of chromosome bounds",loc," ",getchromosomelength(result,x),"\n") if(fixoutofbounds) return(t(cvalues[(l+getchromosomelength(result,x)),])) stop(paste("Location out of chromosome bounds",loc," ",getchromosomelength(result,x),"\n")) } } l <- l + getchromosomelength(result,x) + spacing } stop("No such chromosome") } drawcirculargenome <- function(result,lodmarkers=FALSE,spacing=50){ result <- mqmextractmarkers(result) plot(c(-1.1, 1.1), c(-1.1, 1.1), type = "n", axes = FALSE, xlab = "", ylab = "") title(main = "Circular genome plot") totallength <- getgenomelength(result) nchr <- length(unique(result[,1])) cvalues <- circlelocations(totallength+(nchr*spacing)) l <- 1 for(x in unique(result[,1])){ #Draw chromosomes nl <- l+getchromosomelength(result,x) lines(cvalues[l:nl,],cex=0.01) l <- nl + spacing } for(x in 1:nrow(result)){ #Draw markers if(lodmarkers){ size <- min(c((result[x,3]/2+1),4)) c <- gray(0.5-(0.4*(result[x,3]/max(result[,3])))) points(locationtocircle(result,result[x,1],result[x,2],spacing=spacing),pch=20,col=c,cex=size) }else{ points(locationtocircle(result,result[x,1],result[x,2],spacing=spacing),pch=20) } } for(x in 1:nchr){ chrnumberloc <- locationtocircle(result,x,getchromosomelength(result,x)/2,spacing=spacing) points(t(c(-1.1, -1.15))) points(t(c(-0.9, -1.15))) points(t(c(-0.7, -1.15))) text(t(c(-0.9, -1.0)),paste("Distances in cM"),cex=0.6) text(t(c(-1.1, -1.1)),paste("0 cM"),cex=0.6) text(t(c(-0.9, -1.1)),paste(round((totallength+(nchr*spacing))*(0.2/(2*pi)),dig=1),"cM"),cex=0.6) text(t(c(-0.7, -1.1)),paste(round((totallength+(nchr*spacing))*(0.4/(2*pi)),dig=1),"cM"),cex=0.6) text(0.9*chrnumberloc,paste("Chr",x),cex=0.6) } } loopthroughmulti <- function(cross,result,save=FALSE,spacing=100){ n <- 1 while(n <= length(result)){ if(save) png(file=paste("circleplotT",n,".png",sep=""),w=1024,h=768) mqmplot.circle(cross,result,spacing=spacing,highlight=n) if(save) dev.off() n <- n+1 } }
################################################################################################################################ #################################FUNCION 1: SIMULACION DE ESTUDIOS CON DATOS INDIVIDUALES####################################### ################################################################################################################################ # PARAMTEROS IMPORTANTES EN LA SIMULACION: # 1. Numero de estudios # 2. Numero de variables # 3. Tamaño de la muestra # 4. Media grupo tratamiento # 5. SD grupo tratamiento # 6. Media grupo control # 7. SD grupo control. # 8. Correlacion entre outcomes. # VALORES DE LOS PARAMETROS # Numero de estudios: 5, 10, 15, 25, 50. # Numero de variables: 2, 4, 6. # Tamano de la muestra: 20, 40, 60, 80, 100 (la mitad en cada rama) # Media grupo tratamiento distribuciones normales N(media,sd^2) # Var 1 (PANSS Total): N(60.56,16.97^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(13.65,5.90^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(17.82,6.92^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(29.01,8.15^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(17.3,5.5) # Psychiatry Research 144 (2006) 57-63 Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(17,15.3^2) # Banco de instrumentos para la psiquiatria clinica Punt min = 0; Punt max= 27. # Media grupo control distribuciones normales N(media,sd^2) # Parametros basados en las muestras de las publicaciones correspondientes necesarios para que no haya # solapamiento entre los intervalos de confianza al 95% de los dos grupos. # Var 1 (PANSS Total): N(50.5,20.3^2) Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(9,9.3^2) Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(11.5,7^2) Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(20,9.15^2) Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(8.4,4.6^2) Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(3,4.2^2) Punt min = 0; Punt max= 27. # Correlacion entre outcomes: 0, 0.1, 0.3, 0.5, 0.7, 0.9. # Libreri???as necesarias para la simulacion library(truncdist) # De esta manera se truncaran los valores de las diferentes puntuaciones, para que no se simulen puntuaciones # fuera de rango. # Semilla para poder replicar los datos set.seed(18052013) # Funcion que va a simular los datos en el escenario que queramos simulacion_datos <- function(n.estudios,n.vars,tamano.muestra,semilla,replicaciones){ # Control de los paramtero de la funcion if(n.estudios > 50 || n.estudios < 5){ stop("Numero de estudios incorrecto") } if((n.vars > 12 || n.vars < 4) && is.integer(n.vars/2)!= TRUE){ stop("Numero de variables por estudio incorrecto") } if(tamano.muestra > 100 || tamano.muestra < 20){ stop("Tamano de muestra incorrecto") } if(replicaciones < 5 || replicaciones > 150){ stop("El numero de replicaciones es incorrecto") } # Funcion propiamente dicha database <- vector("list",replicaciones) # Lista donde se almacenaran las replicaciones del escenario deseado for(i in 1:replicaciones){ database[[i]] <- vector("list",n.estudios) # Lista donde se almacenaran el número de estudios determinado set.seed(semilla) for(j in 1:n.estudios){ Var1.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=60.56,sd=16.97),0) # Puntuaciones PANSS total en tratamiento Var1.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=50.5,sd=20.3),0) # Puntuaciones PANSS total en control Var2.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=13.65,sd=5.9),0) # Puntuaciones PANSS positiva tratamiento Var2.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=9,sd=9.3),0) # Puntuaciones PANSS positiva control Var3.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=17.82,sd=6.92),0) # Puntuaciones PANSS negativa tratamiento Var3.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=11,sd=5.7),0) # Puntuaciones PANSS negativa control Var4.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=29.01,sd=8.15),0) # Puntuaciones PANSS general tratamiento Var4.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=20.9,sd=9.15),0) # Puntuaciones PANSS general control Var5.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=17.3,sd=5.5),0) # Puntuaciones HAMD tratamiento Var5.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=8.4,sd=4.6),0) # Puntuaciones HAMD control Var6.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=17.15,sd=15.3),0) # Puntuaciones Calgary tratamiento Var6.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=3,sd=4.2),0) # Puntuaciones Calgary control database[[i]][[j]] <- as.data.frame(cbind(Var1.Trat,Var1.Ctrl,Var2.Trat,Var2.Ctrl,Var3.Trat,Var3.Ctrl,Var4.Trat, Var4.Ctrl,Var5.Trat,Var5.Ctrl,Var6.Trat,Var6.Ctrl)) semilla <- semilla + 1 } } # Para dimensionar en funcion del numero de variables requeridas for(i in 1:replicaciones){ for(j in 1:n.estudios){ if(n.vars == 4 || n.vars == 6 || n.vars == 8 || n.vars == 10 || n.vars == 12){ database[[i]][[j]] <- database[[i]][[j]][,c(1:n.vars)] } else { stop("Numero de variables incorrecto") } } } return(database) } ############################################################################################################################### ###################FUNCION 2: SIMULACION DE ESTUDIOS CON DATOS INDIVIDUALES (SIMPLIFICADA)##################################### ############################################################################################################################### # COMPARACION DE LOS MÉTODOS DE METAANALISIS DESARROLLADOS FRENTE A LOS PROPUESTOS EN LA TESIS. # LA COMPARACION SE HARA MEDIANTE SIMULACION BAJO DIFERENTES CONDICIONES. # FECHA INICIO: 4 / MARZO / 2014 # FECHA FIN: 10/ MARZO / 2014 # PARAMTEROS IMPORTANTES EN LA SIMULACION: # 1. Numero de estudios # 2. Numero de variables # 3. Tamaño de la muestra # 4. Media grupo tratamiento # 5. SD grupo tratamiento # 6. Media grupo control # 7. SD grupo control. # 8. Correlacion entre outcomes. # VALORES DE LOS PARAMETROS # Numero de estudios: 5, 10, 15, 25, 50. # Numero de variables: 2, 4, 6. # Tamano de la muestra: 20, 40, 60, 80, 100 (la mitad en cada rama) # Media grupo tratamiento distribuciones normales N(media,sd^2) # Var 1 (PANSS Total): N(60.56,16.97^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(13.65,5.90^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(17.82,6.92^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(29.01,8.15^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(17.3,5.5) # Psychiatry Research 144 (2006) 57-63 Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(17,15.3^2) # Banco de instrumentos para la psiquiatria clinica Punt min = 0; Punt max= 27. # Media grupo control distribuciones normales N(media,sd^2) # Parametros basados en las muestras de las publicaciones correspondientes necesarios para que no haya # solapamiento entre los intervalos de confianza al 95% de los dos grupos. # Var 1 (PANSS Total): N(50.5,20.3^2) Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(9,9.3^2) Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(11.5,7^2) Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(20,9.15^2) Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(8.4,4.6^2) Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(3,4.2^2) Punt min = 0; Punt max= 27. # Correlacion entre outcomes: 0, 0.1, 0.3, 0.5, 0.7, 0.9. # Librerias necesarias para la simulacion library(truncdist) # De esta manera se truncaran los valores de las diferentes puntuaciones, para que no se simulen puntuaciones # fuera de rango. # Semilla para poder replicar los datos set.seed(18052013) # Función que va a simular los datos en el escenario que queramos simulacion_datos2 <- function(n.estudios,n.vars,tamano.muestra,semilla,replicaciones){ # Control de los paramtero de la funcion if(n.estudios > 50 || n.estudios < 5){ stop("Numero de estudios incorrecto") } if((n.vars > 12 || n.vars < 4) && is.integer(n.vars/2)!= TRUE){ stop("Numero de variables por estudio incorrecto") } if(tamano.muestra > 100 || tamano.muestra < 20){ stop("Tamano de muestra incorrecto") } if(replicaciones < 5 || replicaciones > 150){ stop("El numero de replicaciones es incorrecto") } # Funcion propiamente dicha database <- vector("list",replicaciones) # Lista donde se almacenaran las replicaciones del escenario deseado for(i in 1:replicaciones){ database[[i]] <- vector("list",n.estudios) # Lista donde se almacenaran el número de estudios determinado set.seed(semilla) Var1.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=60.56,sd=16.97),0) # Puntuaciones PANSS total en tratamiento Var1.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=50.5,sd=20.3),0) # Puntuaciones PANSS total en control Var2.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=13.65,sd=5.9),0) # Puntuaciones PANSS positiva tratamiento Var2.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=9,sd=9.3),0) # Puntuaciones PANSS positiva control Var3.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=17.82,sd=6.92),0) # Puntuaciones PANSS negativa tratamiento Var3.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=11,sd=5.7),0) # Puntuaciones PANSS negativa control Var4.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=29.01,sd=8.15),0) # Puntuaciones PANSS general tratamiento Var4.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=20.9,sd=9.15),0) # Puntuaciones PANSS general control Var5.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=17.3,sd=5.5),0) # Puntuaciones HAMD tratamiento Var5.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=8.4,sd=4.6),0) # Puntuaciones HAMD control Var6.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=17.15,sd=15.3),0) # Puntuaciones Calgary tratamiento Var6.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=3,sd=4.2),0) # Puntuaciones Calgary control database[[i]] <- as.data.frame(cbind(Var1.Trat,Var1.Ctrl,Var2.Trat,Var2.Ctrl,Var3.Trat,Var3.Ctrl,Var4.Trat, Var4.Ctrl,Var5.Trat,Var5.Ctrl,Var6.Trat,Var6.Ctrl)) semilla <- semilla + (n.estudios) } for(i in 1:replicaciones){ if(n.vars == 4 || n.vars == 6 || n.vars == 8 || n.vars == 10 || n.vars == 12){ database[[i]] <- database[[i]][,c(1:n.vars)] } else { stop("Numero de variables incorrecto") } } return(database) } ############################################################################################################################## ####################FUNCION 3: g DE HEDGES' DE UNA SIMULACION CON REPLICACIONES (SIMPLIFICADA)################################ ############################################################################################################################## g_hedges_simulacion2_6vars <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0){ library(compute.es) n.vars <- 12 datos <- simulacion_datos2(n.estudios,n.vars,tamano.muestra,semilla,replicaciones) datos_meta <- diag(0,replicaciones,n.vars+15) for(i in 1:replicaciones){ g1 <- mes(mean(datos[[i]][,1]),sd(datos[[i]][,1]),tamano.muestra,mean(datos[[i]][,2]),sd(datos[[i]][,2]),tamano.muestra)[12][,1] g2 <- mes(mean(datos[[i]][,3]),sd(datos[[i]][,3]),tamano.muestra,mean(datos[[i]][,4]),sd(datos[[i]][,4]),tamano.muestra)[12][,1] g3 <- mes(mean(datos[[i]][,5]),sd(datos[[i]][,5]),tamano.muestra,mean(datos[[i]][,6]),sd(datos[[i]][,6]),tamano.muestra)[12][,1] g4 <- mes(mean(datos[[i]][,7]),sd(datos[[i]][,7]),tamano.muestra,mean(datos[[i]][,8]),sd(datos[[i]][,8]),tamano.muestra)[12][,1] g5 <- mes(mean(datos[[i]][,9]),sd(datos[[i]][,9]),tamano.muestra,mean(datos[[i]][,10]),sd(datos[[i]][,10]),tamano.muestra)[12][,1] g6 <- mes(mean(datos[[i]][,11]),sd(datos[[i]][,11]),tamano.muestra,mean(datos[[i]][,12]),sd(datos[[i]][,12]),tamano.muestra)[12][,1] var.g1 <- mes(mean(datos[[i]][,1]),sd(datos[[i]][,1]),tamano.muestra,mean(datos[[i]][,2]),sd(datos[[i]][,2]),tamano.muestra)[13][,1] var.g2 <- mes(mean(datos[[i]][,3]),sd(datos[[i]][,3]),tamano.muestra,mean(datos[[i]][,4]),sd(datos[[i]][,4]),tamano.muestra)[13][,1] var.g3 <- mes(mean(datos[[i]][,5]),sd(datos[[i]][,5]),tamano.muestra,mean(datos[[i]][,6]),sd(datos[[i]][,6]),tamano.muestra)[13][,1] var.g4 <- mes(mean(datos[[i]][,7]),sd(datos[[i]][,7]),tamano.muestra,mean(datos[[i]][,8]),sd(datos[[i]][,8]),tamano.muestra)[13][,1] var.g5 <- mes(mean(datos[[i]][,9]),sd(datos[[i]][,9]),tamano.muestra,mean(datos[[i]][,10]),sd(datos[[i]][,10]),tamano.muestra)[13][,1] var.g6 <- mes(mean(datos[[i]][,11]),sd(datos[[i]][,11]),tamano.muestra,mean(datos[[i]][,12]),sd(datos[[i]][,12]),tamano.muestra)[13][,1] covar.g1g2 <- correlacion12*sqrt(var.g1)*sqrt(var.g2) covar.g1g3 <- correlacion13*sqrt(var.g1)*sqrt(var.g3) covar.g1g4 <- correlacion14*sqrt(var.g1)*sqrt(var.g4) covar.g1g5 <- correlacion15*sqrt(var.g1)*sqrt(var.g5) covar.g1g6 <- correlacion16*sqrt(var.g1)*sqrt(var.g6) covar.g2g3 <- correlacion23*sqrt(var.g2)*sqrt(var.g3) covar.g2g4 <- correlacion24*sqrt(var.g2)*sqrt(var.g4) covar.g2g5 <- correlacion25*sqrt(var.g2)*sqrt(var.g5) covar.g2g6 <- correlacion26*sqrt(var.g2)*sqrt(var.g6) covar.g3g4 <- correlacion34*sqrt(var.g3)*sqrt(var.g4) covar.g3g5 <- correlacion35*sqrt(var.g3)*sqrt(var.g5) covar.g3g6 <- correlacion36*sqrt(var.g3)*sqrt(var.g6) covar.g4g5 <- correlacion45*sqrt(var.g4)*sqrt(var.g5) covar.g4g6 <- correlacion46*sqrt(var.g4)*sqrt(var.g6) covar.g5g6 <- correlacion56*sqrt(var.g5)*sqrt(var.g6) input <- c(g1,g2,g3,g4,g5,g6,var.g1,covar.g1g2,covar.g1g3,covar.g1g4,covar.g1g5,covar.g1g6,var.g2,covar.g2g3,covar.g2g4, covar.g2g5,covar.g2g6,var.g3,covar.g3g4,covar.g3g5,covar.g3g6,var.g4,covar.g4g5,covar.g4g6,var.g5,covar.g5g6, var.g6) datos_meta[i,] <- input } colnames(datos_meta) <- c("g1","g2","g3","g4","g5","g6","var.g1","covar.g1g2","covar.g1g3","covar.g1g4","covar.g1g5", "covar.g1g6","var.g2","covar.g2g3","covar.g2g4","covar.g2g5","covar.g2g6","var.g3","covar.g3g4", "covar.g3g5","covar.g3g6","var.g4","covar.g4g5","covar.g4g6","var.g5","covar.g5g6","var.g6") return(as.data.frame(datos_meta)) } ############################################################################################################################## ##########################FUNCION 4: g DE HEDGES' DE UNA SIMULACION CON REPLICACIONES######################################### ############################################################################################################################## g_hedges_simulacion_6vars <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0){ library(compute.es) n.vars <- 12 datos <- simulacion_datos(n.estudios,n.vars,tamano.muestra,semilla,replicaciones) datos_meta <- vector("list",replicaciones) g1 <- vector(mode="numeric",length=n.estudios) g2 <- vector(mode="numeric",length=n.estudios) g3 <- vector(mode="numeric",length=n.estudios) g4 <- vector(mode="numeric",length=n.estudios) g5 <- vector(mode="numeric",length=n.estudios) g6 <- vector(mode="numeric",length=n.estudios) var.g1 <- vector(mode="numeric",length=n.estudios) var.g2 <- vector(mode="numeric",length=n.estudios) var.g3 <- vector(mode="numeric",length=n.estudios) var.g4 <- vector(mode="numeric",length=n.estudios) var.g5 <- vector(mode="numeric",length=n.estudios) var.g6 <- vector(mode="numeric",length=n.estudios) covar.g1g2 <- vector(mode="numeric",length=n.estudios) covar.g1g3 <- vector(mode="numeric",length=n.estudios) covar.g1g4 <- vector(mode="numeric",length=n.estudios) covar.g1g5 <- vector(mode="numeric",length=n.estudios) covar.g1g6 <- vector(mode="numeric",length=n.estudios) covar.g2g3 <- vector(mode="numeric",length=n.estudios) covar.g2g4 <- vector(mode="numeric",length=n.estudios) covar.g2g5 <- vector(mode="numeric",length=n.estudios) covar.g2g6 <- vector(mode="numeric",length=n.estudios) covar.g3g4 <- vector(mode="numeric",length=n.estudios) covar.g3g5 <- vector(mode="numeric",length=n.estudios) covar.g3g6 <- vector(mode="numeric",length=n.estudios) covar.g4g5 <- vector(mode="numeric",length=n.estudios) covar.g4g6 <- vector(mode="numeric",length=n.estudios) covar.g5g6 <- vector(mode="numeric",length=n.estudios) for(i in 1:replicaciones){ for(j in 1:n.estudios){ g1[j] <- mes(mean(datos[[i]][[j]][,1]),sd(datos[[i]][[j]][,1]),tamano.muestra,mean(datos[[i]][[j]][,2]),sd(datos[[i]][[j]][,2]),tamano.muestra)[12][,1] g2[j] <- mes(mean(datos[[i]][[j]][,3]),sd(datos[[i]][[j]][,3]),tamano.muestra,mean(datos[[i]][[j]][,4]),sd(datos[[i]][[j]][,4]),tamano.muestra)[12][,1] g3[j] <- mes(mean(datos[[i]][[j]][,5]),sd(datos[[i]][[j]][,5]),tamano.muestra,mean(datos[[i]][[j]][,6]),sd(datos[[i]][[j]][,6]),tamano.muestra)[12][,1] g4[j] <- mes(mean(datos[[i]][[j]][,7]),sd(datos[[i]][[j]][,7]),tamano.muestra,mean(datos[[i]][[j]][,8]),sd(datos[[i]][[j]][,8]),tamano.muestra)[12][,1] g5[j] <- mes(mean(datos[[i]][[j]][,9]),sd(datos[[i]][[j]][,9]),tamano.muestra,mean(datos[[i]][[j]][,10]),sd(datos[[i]][[j]][,10]),tamano.muestra)[12][,1] g6[j] <- mes(mean(datos[[i]][[j]][,11]),sd(datos[[i]][[j]][,11]),tamano.muestra,mean(datos[[i]][[j]][,12]),sd(datos[[i]][[j]][,12]),tamano.muestra)[12][,1] var.g1[j] <- mes(mean(datos[[i]][[j]][,1]),sd(datos[[i]][[j]][,1]),tamano.muestra,mean(datos[[i]][[j]][,2]),sd(datos[[i]][[j]][,2]),tamano.muestra)[13][,1] var.g2[j] <- mes(mean(datos[[i]][[j]][,3]),sd(datos[[i]][[j]][,3]),tamano.muestra,mean(datos[[i]][[j]][,4]),sd(datos[[i]][[j]][,4]),tamano.muestra)[13][,1] var.g3[j] <- mes(mean(datos[[i]][[j]][,5]),sd(datos[[i]][[j]][,5]),tamano.muestra,mean(datos[[i]][[j]][,6]),sd(datos[[i]][[j]][,6]),tamano.muestra)[13][,1] var.g4[j] <- mes(mean(datos[[i]][[j]][,7]),sd(datos[[i]][[j]][,7]),tamano.muestra,mean(datos[[i]][[j]][,8]),sd(datos[[i]][[j]][,8]),tamano.muestra)[13][,1] var.g5[j] <- mes(mean(datos[[i]][[j]][,9]),sd(datos[[i]][[j]][,9]),tamano.muestra,mean(datos[[i]][[j]][,10]),sd(datos[[i]][[j]][,10]),tamano.muestra)[13][,1] var.g6[j] <- mes(mean(datos[[i]][[j]][,11]),sd(datos[[i]][[j]][,11]),tamano.muestra,mean(datos[[i]][[j]][,12]),sd(datos[[i]][[j]][,12]),tamano.muestra)[13][,1] covar.g1g2[j] <- correlacion12*sqrt(var.g1[j])*sqrt(var.g2[j]) covar.g1g3[j] <- correlacion13*sqrt(var.g1[j])*sqrt(var.g3[j]) covar.g1g4[j] <- correlacion14*sqrt(var.g1[j])*sqrt(var.g4[j]) covar.g1g5[j] <- correlacion15*sqrt(var.g1[j])*sqrt(var.g5[j]) covar.g1g6[j] <- correlacion16*sqrt(var.g1[j])*sqrt(var.g6[j]) covar.g2g3[j] <- correlacion23*sqrt(var.g2[j])*sqrt(var.g3[j]) covar.g2g4[j] <- correlacion24*sqrt(var.g2[j])*sqrt(var.g4[j]) covar.g2g5[j] <- correlacion25*sqrt(var.g2[j])*sqrt(var.g5[j]) covar.g2g6[j] <- correlacion26*sqrt(var.g2[j])*sqrt(var.g6[j]) covar.g3g4[j] <- correlacion34*sqrt(var.g3[j])*sqrt(var.g4[j]) covar.g3g5[j] <- correlacion35*sqrt(var.g3[j])*sqrt(var.g5[j]) covar.g3g6[j] <- correlacion36*sqrt(var.g3[j])*sqrt(var.g6[j]) covar.g4g5[j] <- correlacion45*sqrt(var.g4[j])*sqrt(var.g5[j]) covar.g4g6[j] <- correlacion46*sqrt(var.g4[j])*sqrt(var.g6[j]) covar.g5g6[j] <- correlacion56*sqrt(var.g5[j])*sqrt(var.g6[j]) input <- cbind(g1,g2,g3,g4,g5,g6,var.g1,covar.g1g2,covar.g1g3,covar.g1g4,covar.g1g5,covar.g1g6,var.g2,covar.g2g3, covar.g2g4,covar.g2g5,covar.g2g6,var.g3,covar.g3g4,covar.g3g5,covar.g3g6,var.g4,covar.g4g5,covar.g4g6, var.g5,covar.g5g6,var.g6) } datos_meta[[i]] <- as.data.frame(input) } return(datos_meta) } ############################################################################################################################## ##########################FUNCION 5: METAANALISIS MULTIVARIADO DE SIMULACION (MODIFICADA)##################################### ############################################################################################################################## ############### # FUNCION 5.1 # ############### # datos <- g_hedges_simulacion2_6vars(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, # correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, # correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, # correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0) meta_multi_simulacion2_6vars <- function(data,metodo="reml"){ library(mvmeta) meta_multi <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),as.data.frame(data)[7:27],data=data,method=metodo) coeficientes <- meta_multi$coefficients coeficientes_inferencia <- summary(meta_multi)$coefficients coeficientes_var_cov <- summary(meta_multi)$corRandom output <- list(coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) return(output) } ############### # FUNCION 5.2 # ############### meta_multi_simulacion2_6vars_bis <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0,metodo="reml"){ library(mvmeta) datos <- g_hedges_simulacion2_6vars(n.estudios,tamano.muestra,semilla,replicaciones,correlacion12,correlacion13, correlacion14,correlacion15,correlacion16,correlacion23,correlacion24,correlacion25, correlacion26,correlacion34,correlacion35,correlacion36,correlacion45,correlacion46, correlacion56) data <- as.data.frame(datos) meta_multi <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),as.data.frame(data)[7:27],data=data,method=metodo) coeficientes <- meta_multi$coefficients coeficientes_inferencia <- summary(meta_multi)$coefficients coeficientes_var_cov <- summary(meta_multi)$corRandom output <- list(coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) return(output) } ############################################################################################################################## ##########################FUNCION 6: METAANALISIS MULTIVARIADO DE SIMULACION (UNO POR REPLICACION)############################ ############################################################################################################################## ############### # FUNCION 6.1 # ############### # datos <- g_hedges_simulacion_6vars(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, # correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, # correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, # correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0) meta_multi_simulacion_6vars <- function(data,metodo="reml",replicaciones=5){ library(mvmeta) meta_multi <- vector(mode="list",length=replicaciones) for(i in 1:length(data)){ datos <- data[[i]] meta_resultados <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),S=as.data.frame(data)[7:27],data=datos,method=metodo) coeficientes <- meta_resultados$coefficients coeficientes_inferencia <- summary(meta_resultados)$coefficients coeficientes_var_cov <- summary(meta_resultados)$corRandom meta_multi[[i]] <- list(dat=data[[i]],coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) } return(meta_multi) } ############### # FUNCION 6.2 # ############### meta_multi_simulacion_6_vars_bis <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0,metodo="reml"){ library(mvmeta) datos <- g_hedges_simulacion_6vars(n.estudios,tamano.muestra,semilla,replicaciones,correlacion12,correlacion13, correlacion14,correlacion15,correlacion16,correlacion23,correlacion24,correlacion25, correlacion26,correlacion34,correlacion35,correlacion36,correlacion45,correlacion46, correlacion56) meta_multi <- vector(mode="list",length=replicaciones) for(i in 1:replicaciones){ data <- as.data.frame(datos[[i]]) meta_resultados <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),S=as.data.frame(data)[7:27],data=data,method=metodo) coeficientes <- meta_resultados$coefficients coeficientes_inferencia <- summary(meta_resultados)$coefficients coeficientes_var_cov <- summary(meta_resultados)$corRandom meta_multi[[i]] <- list(dat=datos[[i]],coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) } return(meta_multi) }
/Borrador_29_Oct_2014/funciones_maestra_6_variables.R
no_license
BorjaSantos/TesisDoctoral
R
false
false
27,284
r
################################################################################################################################ #################################FUNCION 1: SIMULACION DE ESTUDIOS CON DATOS INDIVIDUALES####################################### ################################################################################################################################ # PARAMTEROS IMPORTANTES EN LA SIMULACION: # 1. Numero de estudios # 2. Numero de variables # 3. Tamaño de la muestra # 4. Media grupo tratamiento # 5. SD grupo tratamiento # 6. Media grupo control # 7. SD grupo control. # 8. Correlacion entre outcomes. # VALORES DE LOS PARAMETROS # Numero de estudios: 5, 10, 15, 25, 50. # Numero de variables: 2, 4, 6. # Tamano de la muestra: 20, 40, 60, 80, 100 (la mitad en cada rama) # Media grupo tratamiento distribuciones normales N(media,sd^2) # Var 1 (PANSS Total): N(60.56,16.97^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(13.65,5.90^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(17.82,6.92^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(29.01,8.15^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(17.3,5.5) # Psychiatry Research 144 (2006) 57-63 Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(17,15.3^2) # Banco de instrumentos para la psiquiatria clinica Punt min = 0; Punt max= 27. # Media grupo control distribuciones normales N(media,sd^2) # Parametros basados en las muestras de las publicaciones correspondientes necesarios para que no haya # solapamiento entre los intervalos de confianza al 95% de los dos grupos. # Var 1 (PANSS Total): N(50.5,20.3^2) Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(9,9.3^2) Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(11.5,7^2) Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(20,9.15^2) Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(8.4,4.6^2) Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(3,4.2^2) Punt min = 0; Punt max= 27. # Correlacion entre outcomes: 0, 0.1, 0.3, 0.5, 0.7, 0.9. # Libreri???as necesarias para la simulacion library(truncdist) # De esta manera se truncaran los valores de las diferentes puntuaciones, para que no se simulen puntuaciones # fuera de rango. # Semilla para poder replicar los datos set.seed(18052013) # Funcion que va a simular los datos en el escenario que queramos simulacion_datos <- function(n.estudios,n.vars,tamano.muestra,semilla,replicaciones){ # Control de los paramtero de la funcion if(n.estudios > 50 || n.estudios < 5){ stop("Numero de estudios incorrecto") } if((n.vars > 12 || n.vars < 4) && is.integer(n.vars/2)!= TRUE){ stop("Numero de variables por estudio incorrecto") } if(tamano.muestra > 100 || tamano.muestra < 20){ stop("Tamano de muestra incorrecto") } if(replicaciones < 5 || replicaciones > 150){ stop("El numero de replicaciones es incorrecto") } # Funcion propiamente dicha database <- vector("list",replicaciones) # Lista donde se almacenaran las replicaciones del escenario deseado for(i in 1:replicaciones){ database[[i]] <- vector("list",n.estudios) # Lista donde se almacenaran el número de estudios determinado set.seed(semilla) for(j in 1:n.estudios){ Var1.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=60.56,sd=16.97),0) # Puntuaciones PANSS total en tratamiento Var1.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=50.5,sd=20.3),0) # Puntuaciones PANSS total en control Var2.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=13.65,sd=5.9),0) # Puntuaciones PANSS positiva tratamiento Var2.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=9,sd=9.3),0) # Puntuaciones PANSS positiva control Var3.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=17.82,sd=6.92),0) # Puntuaciones PANSS negativa tratamiento Var3.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=11,sd=5.7),0) # Puntuaciones PANSS negativa control Var4.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=29.01,sd=8.15),0) # Puntuaciones PANSS general tratamiento Var4.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=20.9,sd=9.15),0) # Puntuaciones PANSS general control Var5.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=17.3,sd=5.5),0) # Puntuaciones HAMD tratamiento Var5.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=8.4,sd=4.6),0) # Puntuaciones HAMD control Var6.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=17.15,sd=15.3),0) # Puntuaciones Calgary tratamiento Var6.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=3,sd=4.2),0) # Puntuaciones Calgary control database[[i]][[j]] <- as.data.frame(cbind(Var1.Trat,Var1.Ctrl,Var2.Trat,Var2.Ctrl,Var3.Trat,Var3.Ctrl,Var4.Trat, Var4.Ctrl,Var5.Trat,Var5.Ctrl,Var6.Trat,Var6.Ctrl)) semilla <- semilla + 1 } } # Para dimensionar en funcion del numero de variables requeridas for(i in 1:replicaciones){ for(j in 1:n.estudios){ if(n.vars == 4 || n.vars == 6 || n.vars == 8 || n.vars == 10 || n.vars == 12){ database[[i]][[j]] <- database[[i]][[j]][,c(1:n.vars)] } else { stop("Numero de variables incorrecto") } } } return(database) } ############################################################################################################################### ###################FUNCION 2: SIMULACION DE ESTUDIOS CON DATOS INDIVIDUALES (SIMPLIFICADA)##################################### ############################################################################################################################### # COMPARACION DE LOS MÉTODOS DE METAANALISIS DESARROLLADOS FRENTE A LOS PROPUESTOS EN LA TESIS. # LA COMPARACION SE HARA MEDIANTE SIMULACION BAJO DIFERENTES CONDICIONES. # FECHA INICIO: 4 / MARZO / 2014 # FECHA FIN: 10/ MARZO / 2014 # PARAMTEROS IMPORTANTES EN LA SIMULACION: # 1. Numero de estudios # 2. Numero de variables # 3. Tamaño de la muestra # 4. Media grupo tratamiento # 5. SD grupo tratamiento # 6. Media grupo control # 7. SD grupo control. # 8. Correlacion entre outcomes. # VALORES DE LOS PARAMETROS # Numero de estudios: 5, 10, 15, 25, 50. # Numero de variables: 2, 4, 6. # Tamano de la muestra: 20, 40, 60, 80, 100 (la mitad en cada rama) # Media grupo tratamiento distribuciones normales N(media,sd^2) # Var 1 (PANSS Total): N(60.56,16.97^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(13.65,5.90^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(17.82,6.92^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(29.01,8.15^2) # Rev Psiquiatr Salud Ment (Barc.) 2009;2(4):160-168 Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(17.3,5.5) # Psychiatry Research 144 (2006) 57-63 Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(17,15.3^2) # Banco de instrumentos para la psiquiatria clinica Punt min = 0; Punt max= 27. # Media grupo control distribuciones normales N(media,sd^2) # Parametros basados en las muestras de las publicaciones correspondientes necesarios para que no haya # solapamiento entre los intervalos de confianza al 95% de los dos grupos. # Var 1 (PANSS Total): N(50.5,20.3^2) Punt min = 30; Punt max = 210. # Var 2 (PANSS Positiva): N(9,9.3^2) Punt min = 7; Punt max= 49. # Var 3 (PANSS Negativa): N(11.5,7^2) Punt min = 7; Punt max= 49. # Var 4 (PANSS General): N(20,9.15^2) Punt min = 16; Punt max= 112. # Var 5 (HAMD): N(8.4,4.6^2) Punt min = 0;Punt max= 52. # Var 6 (Calgary): N(3,4.2^2) Punt min = 0; Punt max= 27. # Correlacion entre outcomes: 0, 0.1, 0.3, 0.5, 0.7, 0.9. # Librerias necesarias para la simulacion library(truncdist) # De esta manera se truncaran los valores de las diferentes puntuaciones, para que no se simulen puntuaciones # fuera de rango. # Semilla para poder replicar los datos set.seed(18052013) # Función que va a simular los datos en el escenario que queramos simulacion_datos2 <- function(n.estudios,n.vars,tamano.muestra,semilla,replicaciones){ # Control de los paramtero de la funcion if(n.estudios > 50 || n.estudios < 5){ stop("Numero de estudios incorrecto") } if((n.vars > 12 || n.vars < 4) && is.integer(n.vars/2)!= TRUE){ stop("Numero de variables por estudio incorrecto") } if(tamano.muestra > 100 || tamano.muestra < 20){ stop("Tamano de muestra incorrecto") } if(replicaciones < 5 || replicaciones > 150){ stop("El numero de replicaciones es incorrecto") } # Funcion propiamente dicha database <- vector("list",replicaciones) # Lista donde se almacenaran las replicaciones del escenario deseado for(i in 1:replicaciones){ database[[i]] <- vector("list",n.estudios) # Lista donde se almacenaran el número de estudios determinado set.seed(semilla) Var1.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=60.56,sd=16.97),0) # Puntuaciones PANSS total en tratamiento Var1.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=30,b=210,mean=50.5,sd=20.3),0) # Puntuaciones PANSS total en control Var2.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=13.65,sd=5.9),0) # Puntuaciones PANSS positiva tratamiento Var2.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=9,sd=9.3),0) # Puntuaciones PANSS positiva control Var3.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=17.82,sd=6.92),0) # Puntuaciones PANSS negativa tratamiento Var3.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=7,b=49,mean=11,sd=5.7),0) # Puntuaciones PANSS negativa control Var4.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=29.01,sd=8.15),0) # Puntuaciones PANSS general tratamiento Var4.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=16,b=112,mean=20.9,sd=9.15),0) # Puntuaciones PANSS general control Var5.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=17.3,sd=5.5),0) # Puntuaciones HAMD tratamiento Var5.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=52,mean=8.4,sd=4.6),0) # Puntuaciones HAMD control Var6.Trat <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=17.15,sd=15.3),0) # Puntuaciones Calgary tratamiento Var6.Ctrl <- round(rtrunc(tamano.muestra,spec="norm",a=0,b=27,mean=3,sd=4.2),0) # Puntuaciones Calgary control database[[i]] <- as.data.frame(cbind(Var1.Trat,Var1.Ctrl,Var2.Trat,Var2.Ctrl,Var3.Trat,Var3.Ctrl,Var4.Trat, Var4.Ctrl,Var5.Trat,Var5.Ctrl,Var6.Trat,Var6.Ctrl)) semilla <- semilla + (n.estudios) } for(i in 1:replicaciones){ if(n.vars == 4 || n.vars == 6 || n.vars == 8 || n.vars == 10 || n.vars == 12){ database[[i]] <- database[[i]][,c(1:n.vars)] } else { stop("Numero de variables incorrecto") } } return(database) } ############################################################################################################################## ####################FUNCION 3: g DE HEDGES' DE UNA SIMULACION CON REPLICACIONES (SIMPLIFICADA)################################ ############################################################################################################################## g_hedges_simulacion2_6vars <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0){ library(compute.es) n.vars <- 12 datos <- simulacion_datos2(n.estudios,n.vars,tamano.muestra,semilla,replicaciones) datos_meta <- diag(0,replicaciones,n.vars+15) for(i in 1:replicaciones){ g1 <- mes(mean(datos[[i]][,1]),sd(datos[[i]][,1]),tamano.muestra,mean(datos[[i]][,2]),sd(datos[[i]][,2]),tamano.muestra)[12][,1] g2 <- mes(mean(datos[[i]][,3]),sd(datos[[i]][,3]),tamano.muestra,mean(datos[[i]][,4]),sd(datos[[i]][,4]),tamano.muestra)[12][,1] g3 <- mes(mean(datos[[i]][,5]),sd(datos[[i]][,5]),tamano.muestra,mean(datos[[i]][,6]),sd(datos[[i]][,6]),tamano.muestra)[12][,1] g4 <- mes(mean(datos[[i]][,7]),sd(datos[[i]][,7]),tamano.muestra,mean(datos[[i]][,8]),sd(datos[[i]][,8]),tamano.muestra)[12][,1] g5 <- mes(mean(datos[[i]][,9]),sd(datos[[i]][,9]),tamano.muestra,mean(datos[[i]][,10]),sd(datos[[i]][,10]),tamano.muestra)[12][,1] g6 <- mes(mean(datos[[i]][,11]),sd(datos[[i]][,11]),tamano.muestra,mean(datos[[i]][,12]),sd(datos[[i]][,12]),tamano.muestra)[12][,1] var.g1 <- mes(mean(datos[[i]][,1]),sd(datos[[i]][,1]),tamano.muestra,mean(datos[[i]][,2]),sd(datos[[i]][,2]),tamano.muestra)[13][,1] var.g2 <- mes(mean(datos[[i]][,3]),sd(datos[[i]][,3]),tamano.muestra,mean(datos[[i]][,4]),sd(datos[[i]][,4]),tamano.muestra)[13][,1] var.g3 <- mes(mean(datos[[i]][,5]),sd(datos[[i]][,5]),tamano.muestra,mean(datos[[i]][,6]),sd(datos[[i]][,6]),tamano.muestra)[13][,1] var.g4 <- mes(mean(datos[[i]][,7]),sd(datos[[i]][,7]),tamano.muestra,mean(datos[[i]][,8]),sd(datos[[i]][,8]),tamano.muestra)[13][,1] var.g5 <- mes(mean(datos[[i]][,9]),sd(datos[[i]][,9]),tamano.muestra,mean(datos[[i]][,10]),sd(datos[[i]][,10]),tamano.muestra)[13][,1] var.g6 <- mes(mean(datos[[i]][,11]),sd(datos[[i]][,11]),tamano.muestra,mean(datos[[i]][,12]),sd(datos[[i]][,12]),tamano.muestra)[13][,1] covar.g1g2 <- correlacion12*sqrt(var.g1)*sqrt(var.g2) covar.g1g3 <- correlacion13*sqrt(var.g1)*sqrt(var.g3) covar.g1g4 <- correlacion14*sqrt(var.g1)*sqrt(var.g4) covar.g1g5 <- correlacion15*sqrt(var.g1)*sqrt(var.g5) covar.g1g6 <- correlacion16*sqrt(var.g1)*sqrt(var.g6) covar.g2g3 <- correlacion23*sqrt(var.g2)*sqrt(var.g3) covar.g2g4 <- correlacion24*sqrt(var.g2)*sqrt(var.g4) covar.g2g5 <- correlacion25*sqrt(var.g2)*sqrt(var.g5) covar.g2g6 <- correlacion26*sqrt(var.g2)*sqrt(var.g6) covar.g3g4 <- correlacion34*sqrt(var.g3)*sqrt(var.g4) covar.g3g5 <- correlacion35*sqrt(var.g3)*sqrt(var.g5) covar.g3g6 <- correlacion36*sqrt(var.g3)*sqrt(var.g6) covar.g4g5 <- correlacion45*sqrt(var.g4)*sqrt(var.g5) covar.g4g6 <- correlacion46*sqrt(var.g4)*sqrt(var.g6) covar.g5g6 <- correlacion56*sqrt(var.g5)*sqrt(var.g6) input <- c(g1,g2,g3,g4,g5,g6,var.g1,covar.g1g2,covar.g1g3,covar.g1g4,covar.g1g5,covar.g1g6,var.g2,covar.g2g3,covar.g2g4, covar.g2g5,covar.g2g6,var.g3,covar.g3g4,covar.g3g5,covar.g3g6,var.g4,covar.g4g5,covar.g4g6,var.g5,covar.g5g6, var.g6) datos_meta[i,] <- input } colnames(datos_meta) <- c("g1","g2","g3","g4","g5","g6","var.g1","covar.g1g2","covar.g1g3","covar.g1g4","covar.g1g5", "covar.g1g6","var.g2","covar.g2g3","covar.g2g4","covar.g2g5","covar.g2g6","var.g3","covar.g3g4", "covar.g3g5","covar.g3g6","var.g4","covar.g4g5","covar.g4g6","var.g5","covar.g5g6","var.g6") return(as.data.frame(datos_meta)) } ############################################################################################################################## ##########################FUNCION 4: g DE HEDGES' DE UNA SIMULACION CON REPLICACIONES######################################### ############################################################################################################################## g_hedges_simulacion_6vars <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0){ library(compute.es) n.vars <- 12 datos <- simulacion_datos(n.estudios,n.vars,tamano.muestra,semilla,replicaciones) datos_meta <- vector("list",replicaciones) g1 <- vector(mode="numeric",length=n.estudios) g2 <- vector(mode="numeric",length=n.estudios) g3 <- vector(mode="numeric",length=n.estudios) g4 <- vector(mode="numeric",length=n.estudios) g5 <- vector(mode="numeric",length=n.estudios) g6 <- vector(mode="numeric",length=n.estudios) var.g1 <- vector(mode="numeric",length=n.estudios) var.g2 <- vector(mode="numeric",length=n.estudios) var.g3 <- vector(mode="numeric",length=n.estudios) var.g4 <- vector(mode="numeric",length=n.estudios) var.g5 <- vector(mode="numeric",length=n.estudios) var.g6 <- vector(mode="numeric",length=n.estudios) covar.g1g2 <- vector(mode="numeric",length=n.estudios) covar.g1g3 <- vector(mode="numeric",length=n.estudios) covar.g1g4 <- vector(mode="numeric",length=n.estudios) covar.g1g5 <- vector(mode="numeric",length=n.estudios) covar.g1g6 <- vector(mode="numeric",length=n.estudios) covar.g2g3 <- vector(mode="numeric",length=n.estudios) covar.g2g4 <- vector(mode="numeric",length=n.estudios) covar.g2g5 <- vector(mode="numeric",length=n.estudios) covar.g2g6 <- vector(mode="numeric",length=n.estudios) covar.g3g4 <- vector(mode="numeric",length=n.estudios) covar.g3g5 <- vector(mode="numeric",length=n.estudios) covar.g3g6 <- vector(mode="numeric",length=n.estudios) covar.g4g5 <- vector(mode="numeric",length=n.estudios) covar.g4g6 <- vector(mode="numeric",length=n.estudios) covar.g5g6 <- vector(mode="numeric",length=n.estudios) for(i in 1:replicaciones){ for(j in 1:n.estudios){ g1[j] <- mes(mean(datos[[i]][[j]][,1]),sd(datos[[i]][[j]][,1]),tamano.muestra,mean(datos[[i]][[j]][,2]),sd(datos[[i]][[j]][,2]),tamano.muestra)[12][,1] g2[j] <- mes(mean(datos[[i]][[j]][,3]),sd(datos[[i]][[j]][,3]),tamano.muestra,mean(datos[[i]][[j]][,4]),sd(datos[[i]][[j]][,4]),tamano.muestra)[12][,1] g3[j] <- mes(mean(datos[[i]][[j]][,5]),sd(datos[[i]][[j]][,5]),tamano.muestra,mean(datos[[i]][[j]][,6]),sd(datos[[i]][[j]][,6]),tamano.muestra)[12][,1] g4[j] <- mes(mean(datos[[i]][[j]][,7]),sd(datos[[i]][[j]][,7]),tamano.muestra,mean(datos[[i]][[j]][,8]),sd(datos[[i]][[j]][,8]),tamano.muestra)[12][,1] g5[j] <- mes(mean(datos[[i]][[j]][,9]),sd(datos[[i]][[j]][,9]),tamano.muestra,mean(datos[[i]][[j]][,10]),sd(datos[[i]][[j]][,10]),tamano.muestra)[12][,1] g6[j] <- mes(mean(datos[[i]][[j]][,11]),sd(datos[[i]][[j]][,11]),tamano.muestra,mean(datos[[i]][[j]][,12]),sd(datos[[i]][[j]][,12]),tamano.muestra)[12][,1] var.g1[j] <- mes(mean(datos[[i]][[j]][,1]),sd(datos[[i]][[j]][,1]),tamano.muestra,mean(datos[[i]][[j]][,2]),sd(datos[[i]][[j]][,2]),tamano.muestra)[13][,1] var.g2[j] <- mes(mean(datos[[i]][[j]][,3]),sd(datos[[i]][[j]][,3]),tamano.muestra,mean(datos[[i]][[j]][,4]),sd(datos[[i]][[j]][,4]),tamano.muestra)[13][,1] var.g3[j] <- mes(mean(datos[[i]][[j]][,5]),sd(datos[[i]][[j]][,5]),tamano.muestra,mean(datos[[i]][[j]][,6]),sd(datos[[i]][[j]][,6]),tamano.muestra)[13][,1] var.g4[j] <- mes(mean(datos[[i]][[j]][,7]),sd(datos[[i]][[j]][,7]),tamano.muestra,mean(datos[[i]][[j]][,8]),sd(datos[[i]][[j]][,8]),tamano.muestra)[13][,1] var.g5[j] <- mes(mean(datos[[i]][[j]][,9]),sd(datos[[i]][[j]][,9]),tamano.muestra,mean(datos[[i]][[j]][,10]),sd(datos[[i]][[j]][,10]),tamano.muestra)[13][,1] var.g6[j] <- mes(mean(datos[[i]][[j]][,11]),sd(datos[[i]][[j]][,11]),tamano.muestra,mean(datos[[i]][[j]][,12]),sd(datos[[i]][[j]][,12]),tamano.muestra)[13][,1] covar.g1g2[j] <- correlacion12*sqrt(var.g1[j])*sqrt(var.g2[j]) covar.g1g3[j] <- correlacion13*sqrt(var.g1[j])*sqrt(var.g3[j]) covar.g1g4[j] <- correlacion14*sqrt(var.g1[j])*sqrt(var.g4[j]) covar.g1g5[j] <- correlacion15*sqrt(var.g1[j])*sqrt(var.g5[j]) covar.g1g6[j] <- correlacion16*sqrt(var.g1[j])*sqrt(var.g6[j]) covar.g2g3[j] <- correlacion23*sqrt(var.g2[j])*sqrt(var.g3[j]) covar.g2g4[j] <- correlacion24*sqrt(var.g2[j])*sqrt(var.g4[j]) covar.g2g5[j] <- correlacion25*sqrt(var.g2[j])*sqrt(var.g5[j]) covar.g2g6[j] <- correlacion26*sqrt(var.g2[j])*sqrt(var.g6[j]) covar.g3g4[j] <- correlacion34*sqrt(var.g3[j])*sqrt(var.g4[j]) covar.g3g5[j] <- correlacion35*sqrt(var.g3[j])*sqrt(var.g5[j]) covar.g3g6[j] <- correlacion36*sqrt(var.g3[j])*sqrt(var.g6[j]) covar.g4g5[j] <- correlacion45*sqrt(var.g4[j])*sqrt(var.g5[j]) covar.g4g6[j] <- correlacion46*sqrt(var.g4[j])*sqrt(var.g6[j]) covar.g5g6[j] <- correlacion56*sqrt(var.g5[j])*sqrt(var.g6[j]) input <- cbind(g1,g2,g3,g4,g5,g6,var.g1,covar.g1g2,covar.g1g3,covar.g1g4,covar.g1g5,covar.g1g6,var.g2,covar.g2g3, covar.g2g4,covar.g2g5,covar.g2g6,var.g3,covar.g3g4,covar.g3g5,covar.g3g6,var.g4,covar.g4g5,covar.g4g6, var.g5,covar.g5g6,var.g6) } datos_meta[[i]] <- as.data.frame(input) } return(datos_meta) } ############################################################################################################################## ##########################FUNCION 5: METAANALISIS MULTIVARIADO DE SIMULACION (MODIFICADA)##################################### ############################################################################################################################## ############### # FUNCION 5.1 # ############### # datos <- g_hedges_simulacion2_6vars(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, # correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, # correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, # correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0) meta_multi_simulacion2_6vars <- function(data,metodo="reml"){ library(mvmeta) meta_multi <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),as.data.frame(data)[7:27],data=data,method=metodo) coeficientes <- meta_multi$coefficients coeficientes_inferencia <- summary(meta_multi)$coefficients coeficientes_var_cov <- summary(meta_multi)$corRandom output <- list(coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) return(output) } ############### # FUNCION 5.2 # ############### meta_multi_simulacion2_6vars_bis <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0,metodo="reml"){ library(mvmeta) datos <- g_hedges_simulacion2_6vars(n.estudios,tamano.muestra,semilla,replicaciones,correlacion12,correlacion13, correlacion14,correlacion15,correlacion16,correlacion23,correlacion24,correlacion25, correlacion26,correlacion34,correlacion35,correlacion36,correlacion45,correlacion46, correlacion56) data <- as.data.frame(datos) meta_multi <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),as.data.frame(data)[7:27],data=data,method=metodo) coeficientes <- meta_multi$coefficients coeficientes_inferencia <- summary(meta_multi)$coefficients coeficientes_var_cov <- summary(meta_multi)$corRandom output <- list(coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) return(output) } ############################################################################################################################## ##########################FUNCION 6: METAANALISIS MULTIVARIADO DE SIMULACION (UNO POR REPLICACION)############################ ############################################################################################################################## ############### # FUNCION 6.1 # ############### # datos <- g_hedges_simulacion_6vars(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, # correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, # correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, # correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0) meta_multi_simulacion_6vars <- function(data,metodo="reml",replicaciones=5){ library(mvmeta) meta_multi <- vector(mode="list",length=replicaciones) for(i in 1:length(data)){ datos <- data[[i]] meta_resultados <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),S=as.data.frame(data)[7:27],data=datos,method=metodo) coeficientes <- meta_resultados$coefficients coeficientes_inferencia <- summary(meta_resultados)$coefficients coeficientes_var_cov <- summary(meta_resultados)$corRandom meta_multi[[i]] <- list(dat=data[[i]],coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) } return(meta_multi) } ############### # FUNCION 6.2 # ############### meta_multi_simulacion_6_vars_bis <- function(n.estudios=5,tamano.muestra=20,semilla=18052013,replicaciones=5,correlacion12=0, correlacion13=0,correlacion14=0,correlacion15=0,correlacion16=0,correlacion23=0, correlacion24=0,correlacion25=0,correlacion26=0,correlacion34=0,correlacion35=0, correlacion36=0,correlacion45=0,correlacion46=0,correlacion56=0,metodo="reml"){ library(mvmeta) datos <- g_hedges_simulacion_6vars(n.estudios,tamano.muestra,semilla,replicaciones,correlacion12,correlacion13, correlacion14,correlacion15,correlacion16,correlacion23,correlacion24,correlacion25, correlacion26,correlacion34,correlacion35,correlacion36,correlacion45,correlacion46, correlacion56) meta_multi <- vector(mode="list",length=replicaciones) for(i in 1:replicaciones){ data <- as.data.frame(datos[[i]]) meta_resultados <- mvmeta(cbind(g1,g2,g3,g4,g5,g6),S=as.data.frame(data)[7:27],data=data,method=metodo) coeficientes <- meta_resultados$coefficients coeficientes_inferencia <- summary(meta_resultados)$coefficients coeficientes_var_cov <- summary(meta_resultados)$corRandom meta_multi[[i]] <- list(dat=datos[[i]],coefs=coeficientes,inferencia=coeficientes_inferencia,var_cov=coeficientes_var_cov) } return(meta_multi) }
--- title: "Assignment1" author: "Kirram" date: "October 17, 2015" output: html_document --- This report was produced to represent answers to the questions in the Peer Assessment 1 of Reproducible Research Class. Libraries required: ```{r, echo=TRUE} library(ggplot2) library(plyr) library(Hmisc) ``` 1. Loading and preprocessing the data Show any code that is needed to Load the data (i.e. read.csv()) ```{r, echo=TRUE} data1<-read.csv("activity.csv") ``` Process/transform the data (if necessary) into a format suitable for your analysis For question 1, we need to sum up numbers of steps for each day: ```{r, echo=TRUE} data_q1<-ddply(data1, .(date),summarise, SumSteps=sum(steps)) ``` For question 2, we need to average numbers of steps for each interval: ```{r, echo=TRUE} data_q2<-ddply(data1, .(interval), summarise, Mean=mean(steps, na.rm = TRUE)) ``` For question 3, we need to replace the NAs with the means: ```{r echo=TRUE} data_q3<-data1 data_q3$steps<-impute(data_q3$steps, fun=mean) data_q3$steps<-as.numeric(data_q3$steps) ``` For question 4: ```{r, echo=TRUE} data_q4<-data_q3 data_q4$dateType<- ifelse(as.POSIXlt(data_q4$date)$wday %in% c(0,6), "weekend", "weekday") ``` Q1. What is mean total number of steps taken per day? For this part of the assignment, you can ignore the missing values in the dataset. Make a histogram of the total number of steps taken each day ```{r, echo=TRUE} q1<-ggplot(data_q1, aes(x=date, y=SumSteps))+geom_histogram(stat = "identity") q1 ``` Calculate and report the mean and median total number of steps taken per day Mean: ```{r, echo=TRUE} mean_q1<-mean(data_q1$SumSteps, na.rm = TRUE) mean_q1 ``` Median: ```{r,echo=TRUE} median_q1<-median(data_q1$SumSteps, na.rm=TRUE) median_q1 ``` Q2. What is the average daily activity pattern? Make a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis) ```{r, echo=TRUE} q2<-ggplot(data_q2)+geom_freqpoly(aes(x=interval,y=Mean), stat="identity") q2 ``` Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps? ```{r, echo=TRUE} data_q2_sorted<-arrange(data_q2, by=Mean, decreasing=TRUE) data_q2_max<-data_q2_sorted[1:1,] data_q2_max ``` Q3. 1.Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs) ```{r, echo=TRUE} na_sum<-sum(is.na(data1$steps)) na_sum ``` 2.Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc. For this task we'll compute averages of steps and replace the NAs with the means 3.Create a new dataset that is equal to the original dataset but with the missing data filled in. ```{r echo=TRUE} data_q3<-data1 data_q3$steps<-impute(data_q3$steps, fun=mean) data_q3$steps<-as.numeric(data_q3$steps) ``` 4. Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day. Do these values differ from the estimates from the first part of the assignment? What is the impact of imputing missing data on the estimates of the total daily number of steps? ```{r, echo=TRUE} q3<-ggplot(data_q3, aes(x=date, y=steps))+geom_histogram(stat = "identity") q3 ``` ```{r, echo=TRUE} data_q3_4<-ddply(data_q3, .(date),summarise, SumSteps=sum(steps)) mean_q3_4<-mean(data_q3_4$SumSteps, na.rm=TRUE) mean_q3_4 ``` ```{r,echo=TRUE} median_q3_4<-median(data_q3_4$SumSteps, na.rm=TRUE) median_q3_4 ``` As can be seen, the median value is different to what it was in q1 and now equals the mean. To conclude, replacing the NAs with the means has a smoothing effect and decreases/eliminates the difference between the mean and median. Q5. Are there differences in activity patterns between weekdays and weekends? For this part the weekdays() function may be of some help here. Use the dataset with the filled-in missing values for this part. 1. Create a new factor variable in the dataset with two levels - "weekday" and "weekend" indicating whether a given date is a weekday or weekend day. ```{r, echo=TRUE} data_q4<-data_q3 data_q4$dateType<- ifelse(as.POSIXlt(data_q4$date)$wday %in% c(0,6), "weekend", "weekday") ``` 2. Make a panel plot containing a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis). See the README file in the GitHub repository to see an example of what this plot should look like using simulated data. ```{r,echo=TRUE} data_q4<- aggregate(steps ~ interval + dateType, data=data_q4, mean) ggplot(data_q4, aes(interval, steps)) + geom_line() + facet_grid(dateType ~ .) + xlab("5-minute interval") + ylab("avarage number of steps") ```
/PA1_template.R
no_license
kirram/Reproducible_Research_Peer_Assessment_1
R
false
false
5,475
r
--- title: "Assignment1" author: "Kirram" date: "October 17, 2015" output: html_document --- This report was produced to represent answers to the questions in the Peer Assessment 1 of Reproducible Research Class. Libraries required: ```{r, echo=TRUE} library(ggplot2) library(plyr) library(Hmisc) ``` 1. Loading and preprocessing the data Show any code that is needed to Load the data (i.e. read.csv()) ```{r, echo=TRUE} data1<-read.csv("activity.csv") ``` Process/transform the data (if necessary) into a format suitable for your analysis For question 1, we need to sum up numbers of steps for each day: ```{r, echo=TRUE} data_q1<-ddply(data1, .(date),summarise, SumSteps=sum(steps)) ``` For question 2, we need to average numbers of steps for each interval: ```{r, echo=TRUE} data_q2<-ddply(data1, .(interval), summarise, Mean=mean(steps, na.rm = TRUE)) ``` For question 3, we need to replace the NAs with the means: ```{r echo=TRUE} data_q3<-data1 data_q3$steps<-impute(data_q3$steps, fun=mean) data_q3$steps<-as.numeric(data_q3$steps) ``` For question 4: ```{r, echo=TRUE} data_q4<-data_q3 data_q4$dateType<- ifelse(as.POSIXlt(data_q4$date)$wday %in% c(0,6), "weekend", "weekday") ``` Q1. What is mean total number of steps taken per day? For this part of the assignment, you can ignore the missing values in the dataset. Make a histogram of the total number of steps taken each day ```{r, echo=TRUE} q1<-ggplot(data_q1, aes(x=date, y=SumSteps))+geom_histogram(stat = "identity") q1 ``` Calculate and report the mean and median total number of steps taken per day Mean: ```{r, echo=TRUE} mean_q1<-mean(data_q1$SumSteps, na.rm = TRUE) mean_q1 ``` Median: ```{r,echo=TRUE} median_q1<-median(data_q1$SumSteps, na.rm=TRUE) median_q1 ``` Q2. What is the average daily activity pattern? Make a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis) ```{r, echo=TRUE} q2<-ggplot(data_q2)+geom_freqpoly(aes(x=interval,y=Mean), stat="identity") q2 ``` Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps? ```{r, echo=TRUE} data_q2_sorted<-arrange(data_q2, by=Mean, decreasing=TRUE) data_q2_max<-data_q2_sorted[1:1,] data_q2_max ``` Q3. 1.Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs) ```{r, echo=TRUE} na_sum<-sum(is.na(data1$steps)) na_sum ``` 2.Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc. For this task we'll compute averages of steps and replace the NAs with the means 3.Create a new dataset that is equal to the original dataset but with the missing data filled in. ```{r echo=TRUE} data_q3<-data1 data_q3$steps<-impute(data_q3$steps, fun=mean) data_q3$steps<-as.numeric(data_q3$steps) ``` 4. Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day. Do these values differ from the estimates from the first part of the assignment? What is the impact of imputing missing data on the estimates of the total daily number of steps? ```{r, echo=TRUE} q3<-ggplot(data_q3, aes(x=date, y=steps))+geom_histogram(stat = "identity") q3 ``` ```{r, echo=TRUE} data_q3_4<-ddply(data_q3, .(date),summarise, SumSteps=sum(steps)) mean_q3_4<-mean(data_q3_4$SumSteps, na.rm=TRUE) mean_q3_4 ``` ```{r,echo=TRUE} median_q3_4<-median(data_q3_4$SumSteps, na.rm=TRUE) median_q3_4 ``` As can be seen, the median value is different to what it was in q1 and now equals the mean. To conclude, replacing the NAs with the means has a smoothing effect and decreases/eliminates the difference between the mean and median. Q5. Are there differences in activity patterns between weekdays and weekends? For this part the weekdays() function may be of some help here. Use the dataset with the filled-in missing values for this part. 1. Create a new factor variable in the dataset with two levels - "weekday" and "weekend" indicating whether a given date is a weekday or weekend day. ```{r, echo=TRUE} data_q4<-data_q3 data_q4$dateType<- ifelse(as.POSIXlt(data_q4$date)$wday %in% c(0,6), "weekend", "weekday") ``` 2. Make a panel plot containing a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis). See the README file in the GitHub repository to see an example of what this plot should look like using simulated data. ```{r,echo=TRUE} data_q4<- aggregate(steps ~ interval + dateType, data=data_q4, mean) ggplot(data_q4, aes(interval, steps)) + geom_line() + facet_grid(dateType ~ .) + xlab("5-minute interval") + ylab("avarage number of steps") ```
library(ggplot2) #Import the data and add the values that are important data <- read.csv("~/Documents/Github/Rstat/kaggle/Baseball/Data/SQLExtractTopPlayers.csv") data$obp<-(data$h+data$bb)/data$ab data$age<-data$yearID-data$birth_yearID data$avg<-data$h/data$ab basemen<-subset(data,pos %in% c('1B','2B','3B')) plot<-ggplot(basemen) plot+geom_boxplot(aes(factor(age), obp)) +facet_grid(.~pos) plot+geom_boxplot(aes(factor(age), obp, fill = pos, col = pos, position = 'identity', alpha = .5)) basemen.prolific<-subset(basemen,g>=40) plot2<-ggplot(basemen.prolific) plot2+geom_boxplot(aes(factor(age),obp))+facet_grid(.~pos) outfield<-subset(data,pos %in% c('RF','LF','CF')) plot3<-ggplot(outfield) plot3+geom_boxplot(aes(factor(age), sb, col = 2)) +facet_grid(.~pos) plot3+geom_boxplot(aes(factor(age), sb, fill = pos, col = pos, position = 'identity', alpha = .5))
/PeakAllStars.R
no_license
wouldntyaliktono/Kaggle_Baseball
R
false
false
1,179
r
library(ggplot2) #Import the data and add the values that are important data <- read.csv("~/Documents/Github/Rstat/kaggle/Baseball/Data/SQLExtractTopPlayers.csv") data$obp<-(data$h+data$bb)/data$ab data$age<-data$yearID-data$birth_yearID data$avg<-data$h/data$ab basemen<-subset(data,pos %in% c('1B','2B','3B')) plot<-ggplot(basemen) plot+geom_boxplot(aes(factor(age), obp)) +facet_grid(.~pos) plot+geom_boxplot(aes(factor(age), obp, fill = pos, col = pos, position = 'identity', alpha = .5)) basemen.prolific<-subset(basemen,g>=40) plot2<-ggplot(basemen.prolific) plot2+geom_boxplot(aes(factor(age),obp))+facet_grid(.~pos) outfield<-subset(data,pos %in% c('RF','LF','CF')) plot3<-ggplot(outfield) plot3+geom_boxplot(aes(factor(age), sb, col = 2)) +facet_grid(.~pos) plot3+geom_boxplot(aes(factor(age), sb, fill = pos, col = pos, position = 'identity', alpha = .5))
## ----setup, include=FALSE------------------------------------------------ library(knitr) library(Cairo) opts_chunk$set(out.extra='style="display:block; margin: auto"', fig.align="center", dev='CairoPNG') options(warn=-1) ## ----e1, fig.height = 6, fig.width = 10---------------------------------- library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "vegetables.csv", package="patternplot")) #Example 1 pattern.type<-c('hdashes', 'vdashes', 'bricks') pie1<-patternpie(group=data$group,pct=data$pct,label=data$label, label.size=4, label.color='black',label.distance=1.3,pattern.type=pattern.type, pattern.line.size=c(10, 10, 2), frame.color='black',frame.size=1.5, pixel=12, density=c(8, 8, 10)) pie1<-pie1+ggtitle('(A) Black and White with Patterns') #Example 2 pattern.color<-c('red3','green3', 'white' ) background.color<-c('dodgerblue', 'lightpink', 'orange') pie2<-patternpie(group=data$group,pct=data$pct,label=data$label, label.distance=1.3, pattern.type=pattern.type, pattern.color=pattern.color,background.color=background.color, pattern.line.size=c(10, 10, 2), frame.color='grey40',frame.size=1.5, pixel=12, density=c(8, 8, 10)) pie2<-pie2+ggtitle('(B) Colors with Patterns') library(gridExtra) grid.arrange(pie1,pie2, nrow = 1) ## ----e2, fig.height = 6, fig.width = 6----------------------------------- library(patternplot) library(ggplot2) library(jpeg) Tomatoes <- readJPEG(system.file("img", "tomatoes.jpg", package="patternplot")) Peas <- readJPEG(system.file("img", "peas.jpg", package="patternplot")) Potatoes <- readJPEG(system.file("img", "potatoes.jpg", package="patternplot")) #Example 1 data <- read.csv(system.file("extdata", "vegetables.csv", package="patternplot")) pattern.type<-list(Tomatoes,Peas,Potatoes) imagepie(group=data$group,pct=data$pct,label=data$label,pattern.type=pattern.type, label.distance=1.3,frame.color='burlywood4', frame.size=0.8, label.size=6, label.color='forestgreen')+ggtitle('Pie Chart with Images') ## ----e3, fig.height = 6.5, fig.width = 6.5------------------------------- library(patternplot) library(png) library(ggplot2) group1<-c('New_England', 'Great_Lakes','Plains', 'Rocky_Mountain', 'Far_West','Southwest', 'Southeast', 'Mideast') pct1<-c( 12, 11, 17, 15, 8, 11, 16, 10) label1<-paste(group1, " \n ", pct1, "%", sep="") pattern.type1<-c("hdashes", "blank", "grid", "blank", "hlines", "blank", "waves", "blank") pattern.type.inner<-"blank" pattern.color1<-rep("white", 8) background.color1<-c("darkgreen", "darkcyan", "chocolate", "cadetblue1", "darkorchid", "yellowgreen", "hotpink", "lightslateblue") density1<-rep(11.5, length(group1)) pattern.line.size1=c(10, 1, 6, 1, 10, 1, 6, 1) g<-patternring1(group1, pct1, label1, label.size1=4,label.color1='black', label.distance1=1.36, pattern.type1, pattern.color1, pattern.line.size1,background.color1, frame.color='black',frame.size=1.2, density1, pixel=13, pattern.type.inner="blank",pattern.color.inner="white", pattern.line.size.inner=1, background.color.inner="white", pixel.inner=10, density.inner=1, r1=2.7, r2=4) g<-g+annotate(geom="text", x=0, y=0, label="2019 Number of Cases \n N=1000",color="black", size=4)+scale_x_continuous(limits=c(-7, 7))+scale_y_continuous(limits=c(-7, 7)) g ## ----e4, fig.height = 6, fig.width = 6----------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) location<-gsub('\\','/',tempdir(), fixed=T) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkgreen", pixel=8, res=8) FarWest<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkcyan", pixel=8, res=8) GreatLakes<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="chocolate", pixel=8, res=8) Mideast<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="cadetblue1", pixel=8, res=8) NewEngland<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkorchid", pixel=8, res=8) Plains<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="yellowgreen", pixel=8, res=8) RockyMountain<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="hotpink", pixel=8, res=8) Southeast<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="lightslateblue", pixel=8, res=8) Southwest <-readPNG(paste(location,'/',"blank",".png", sep='')) group1<-c('New_England', 'Great_Lakes','Plains', 'Rocky_Mountain', 'Far_West','Southwest', 'Southeast', 'Mideast') pct1<-c( 12, 11, 17, 15, 8, 11, 16, 10) label1<-paste(group1, " \n ", pct1, "%", sep="") pattern.type1<-list(NewEngland, GreatLakes,Plains, RockyMountain, FarWest,Southwest, Southeast, Mideast) pattern.type.inner<-readPNG(system.file("img", "USmap.png", package="patternplot")) g<-imagering1(group1, pct1, pattern.type1, pattern.type.inner, frame.color='black',frame.size=1.5, r1=3, r2=4,label1, label.size1=4,label.color1='black', label.distance1=1.3) g<-g+annotate(geom="text", x=0, y=-2, label="2019 Number of Cases \n N=1000",color="black", size=4)+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6)) g ## ----e5, fig.height = 6, fig.width = 10---------------------------------- library(patternplot) library(png) library(ggplot2) group1<-c("Wind", "Hydro", "Solar", "Coal", "Natural Gas", "Oil") pct1<-c(12, 15, 8, 22, 18, 25) label1<-paste(group1, " \n ", pct1 , "%", sep="") group2<-c("Renewable", "Non-Renewable") pct2<-c(35, 65) label2<-paste(group2, " \n ", pct2 , "%", sep="") pattern.type1<-rep(c( "blank"), times=6) pattern.type2<-c('grid', 'blank') pattern.type.inner<-"blank" pattern.color1<-rep('white', length(group1)) pattern.color2<-rep('white', length(group2)) background.color1<-c("darkolivegreen1", "white", "indianred", "gray81", "white", "sandybrown" ) background.color2<-c("seagreen", "deepskyblue") density1<-rep(10, length(group1)) density2<-rep(10, length(group2)) pattern.line.size1=rep(5, length(group1)) pattern.line.size2=rep(2, length(group2)) pattern.line.size.inner=1 #Example 1: Two rings g<-patternrings2(group1, group2, pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.75, label.distance2=1.4, pattern.type1, pattern.type2, pattern.color1,pattern.color2, pattern.line.size1, pattern.line.size2, background.color1, background.color2,density1=rep(10, length(group1)), density2=rep(15, length(group2)),pixel=10, pattern.type.inner, pattern.color.inner="black",pattern.line.size.inner, background.color.inner="white", pixel.inner=6, density.inner=5, frame.color='black',frame.size=1.5,r1=2.45, r2=4.25, r3=5) g1<-g+annotate(geom="text", x=0, y=0, label="Earth's Energy",color="black", size=5)+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6))+ggtitle("(A) Two Rings") #Example 2: Pie in a ring g<-patternrings2(group1, group2, pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.7, label.distance2=1.4, pattern.type1, pattern.type2, pattern.color1,pattern.color2, pattern.line.size1, pattern.line.size2, background.color1, background.color2,density1=rep(10, length(group1)), density2=rep(15, length(group2)),pixel=10, pattern.type.inner, pattern.color.inner="black",pattern.line.size.inner, background.color.inner="white", pixel.inner=2, density.inner=5, frame.color='black',frame.size=1.5, r1=0.005, r2=4, r3=4.75) g2<-g+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6))+ggtitle("(B) Pie in a Ring") library(gridExtra) grid.arrange(g1,g2, nrow = 1) ## ----e6, fig.height = 6, fig.width = 6----------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) group1<-c("Wind", "Hydro", "Solar", "Coal", "Natural Gas", "Oil") pct1<-c(12, 15, 8, 22, 18, 25) label1<-paste(group1, " \n ", pct1 , "%", sep="") location<-gsub('\\','/',tempdir(), fixed=T) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkolivegreen1", pixel=20, res=15) Wind<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="white", pixel=20, res=15) Hydro<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="indianred", pixel=20, res=15) Solar<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="gray81", pixel=20, res=15) Coal<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="white", pixel=20, res=15) NaturalGas<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="sandybrown", pixel=20, res=15) Oil<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern.type1<-list(Wind, Hydro, Solar, Coal, NaturalGas, Oil) group2<-c("Renewable", "Non-Renewable") pct2<-c(35, 65) label2<-paste(group2, " \n ", pct2 , "%", sep="") pattern(type="grid", density=12, color='white', pattern.line.size=5, background.color="seagreen", pixel=20, res=15) Renewable<-readPNG(paste(location,'/',"grid",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="deepskyblue", pixel=20, res=15) NonRenewable<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern.type2<-list(Renewable, NonRenewable) pattern.type.inner<-readPNG(system.file("img", "earth.png", package="patternplot")) g<-imagerings2(group1, group2,pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.7, label.distance2=1.3, pattern.type1, pattern.type2, pattern.type.inner, frame.color='skyblue',frame.size=1.5, r1=2.2, r2=4.2, r3=5) g<-g+scale_x_continuous(limits=c(-7, 7))+scale_y_continuous(limits=c(-7, 7)) g ## ----e7, fig.width=6, fig.height=6--------------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-c('hdashes', 'blank', 'crosshatch') pattern.color=c('black','black', 'black') background.color=c('white','white', 'white') density<-c(20, 20, 10) barp1<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type, hjust=0.5, pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4), frame.color=c('black', 'black', 'black'), density=density)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(A) Black and White with Patterns') #Example 2 pattern.color=c('black','white', 'grey20') background.color=c('lightgreen','lightgreen', 'lightgreen') barp2<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,hjust=0.5, pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4), frame.color=c('black', 'black', 'black'), density=density)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(B) Colors with Patterns') library(gridExtra) grid.arrange(barp1,barp2, nrow = 1) #Example 3 data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) group<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount x<-factor(data$Location, c('City 1', ' City 1')) pattern.type<-c( 'Rsymbol_16', 'blank','hdashes') pattern.color=c('yellow', 'chartreuse4', 'pink') background.color=c('grey', 'chartreuse3', 'bisque') barp3<-patternbar(data,x, y,group,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type, pattern.color=pattern.color,background.color=background.color, pattern.line.size=c(6, 10,6), frame.size=1,frame.color='black',pixel=16, density=c(18, 10, 14), legend.type='h', legend.h=12, legend.y.pos=0.49, vjust=-1, hjust=0.5,legend.pixel=6, legend.w=0.275,legend.x.pos=1.1) +scale_y_continuous(limits = c(0, 3100))+ggtitle('(C) Bar Chart with Two Grouping Variables') barp3 ## ----e8, fig.width=6, fig.height=6--------------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) x<-data$Location y<-data$Amount group<-data$Type patternbar_s(data,x, y, group,xlab='', ylab='Monthly Expenses, Dollar', label.size=3,pattern.type=c( 'Rsymbol_16', 'blank','hdashes'), pattern.line.size=c(5, 10, 10),frame.size=1,pattern.color=c('yellow', 'chartreuse4', 'pink'),background.color=c('grey', 'chartreuse3', 'bisque'), pixel=16, density=c(18, 10, 10),frame.color='black', legend.type='h', legend.h=12, legend.y.pos=0.49, legend.pixel=6, legend.w=0.275, legend.x.pos=1.05, bar.width=0.8)+scale_y_continuous(limits = c(0, 6800))+ggtitle('Stacked Bar Chart') ## ----e9, fig.width=6, fig.height=6--------------------------------------- library(patternplot) library(jpeg) library(ggplot2) childcare<-readJPEG(system.file("img", "childcare.jpg", package="patternplot")) food<-readJPEG(system.file("img", "food.jpg", package="patternplot")) housing <-readJPEG(system.file("img", "housing.jpg", package="patternplot")) #Example 1 data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-list(housing, food, childcare) imagebar(data,x, y,group=NULL,pattern.type=pattern.type,vjust=-1, hjust=0.5, frame.color='black', ylab='Monthly Expenses, Dollars')+ggtitle('(A) Bar Chart with Images') #Example 2 data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) group<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount x<-factor(data$Location, c('City 1', ' City 1')) pattern.type<-list(housing, food, childcare) imagebar(data,x, y,group,pattern.type=pattern.type,vjust=-1, hjust=0.5, frame.color='black', ylab='Monthly Expenses, Dollars')+ggtitle('(B) Image Bar Chart with Two Grouping Variables') ## ----e10, fig.width=6, fig.height=6-------------------------------------- library(patternplot) library(jpeg) library(ggplot2) childcare<-readJPEG(system.file("img", "childcare.jpg", package="patternplot")) food<-readJPEG(system.file("img", "food.jpg", package="patternplot")) housing <-readJPEG(system.file("img", "housing.jpg", package="patternplot")) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) x<-data$Location y<-data$Amount group<-data$Type pattern.type<-list(childcare, food, housing) imagebar_s(data,x, y, group, xlab='', ylab='Monthly Expenses, Dollar', pattern.type=pattern.type, label.size=3.5, frame.size=1.25, frame.color='black',legend.type='h', legend.h=6, legend.y.pos=0.49, legend.pixel=20, legend.w=0.2,legend.x.pos=1.1)+ scale_y_continuous(limits = c(0, 6800))+ggtitle('Stacked Bar Chart with Images') ## ----e11, fig.height = 6, fig.width = 12--------------------------------- #Example 1 data <- read.csv(system.file("extdata", "fruits.csv", package="patternplot")) group<-data$Fruit y<-data$Weight x<-data$Store pattern.type<-c('nwlines', 'blank', 'waves') pattern.color=c('black','black', 'black') background.color=c('white','gray80', 'white') frame.color=c('black', 'black', 'black') pattern.line.size<-c(6, 1,6) density<-c(6, 1, 8) box1<-patternboxplot(data,x, y,group,pattern.type=pattern.type,pattern.line.size=pattern.line.size, label.size=3, pattern.color=pattern.color, background.color=background.color,frame.color=frame.color, density=density, legend.h=2, legend.x.pos=1.075, legend.y.pos=0.499, legend.pixel=10, legend.w=0.18)+ggtitle('(A) Boxplot with Black and White Patterns') #Example 2 pattern.color=c('black','white', 'grey20') background.color=c('gold','lightpink', 'lightgreen') box2<-patternboxplot(data,x, y,group=group,pattern.type=pattern.type,pattern.line.size=pattern.line.size, label.size=3, pattern.color=pattern.color, background.color=background.color, frame.color=frame.color, density=density, legend.h=2, legend.x.pos=1.075, legend.y.pos=0.499, legend.pixel=10, legend.w=0.18)+ggtitle('(B) Boxplot with Colors and Patterns') library(gridExtra) grid.arrange(box1,box2, nrow = 1) ## ----e12, fig.height = 6, fig.width = 12--------------------------------- library(patternplot) library(jpeg) library(ggplot2) Orange<-readJPEG(system.file("img", "oranges.jpg", package="patternplot")) Strawberry <-readJPEG(system.file("img", "strawberries.jpg", package="patternplot")) Watermelon<-readJPEG(system.file("img", "watermelons.jpg", package="patternplot")) #Example 1 data <- read.csv(system.file("extdata", "fruits.csv", package="patternplot")) x<-data$Fruit y<-data$Weight group<-data$Store pattern.type<-list(Orange, Strawberry, Watermelon) box1<-imageboxplot(data,x, y,group=NULL,pattern.type=pattern.type,frame.color=c('orange', 'darkred', 'darkgreen'),ylab='Weight, Pounds')+ggtitle('(A) Image Boxplot with One Grouping Variable') #Example 2 x<-data$Store y<-data$Weight group<-data$Fruit pattern.type<-list(Orange, Strawberry, Watermelon) box2<-imageboxplot(data,x, y,group=group, pattern.type=pattern.type, frame.color=c('orange', 'darkred', 'darkgreen'), linetype=c('solid', 'dashed', 'dotted'),frame.size=0.8, xlab='', ylab='Weights, pounds', legend.h=2, legend.x.pos=1.1, legend.y.pos=0.499, legend.w=0.2)+ggtitle('(B) Image Boxplot with Two Grouping Variables') library(gridExtra) grid.arrange(box1,box2, nrow = 1) ## ----e13, fig.height = 6, fig.width = 12--------------------------------- library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-c('hdashes', 'blank', 'crosshatch') pattern.color=c('black','black', 'black') background.color=c('white','white', 'white') density<-c(20, 20, 10) g1<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=-1, hjust=0.5, bar.width=0.75)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(A) Vertical Bar Chart') g2<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=0.5, hjust=-0.25, bar.width=0.5)+scale_y_continuous(limits = c(0,2800))+ggtitle('(B) Horizontal Bar Chart')+coord_flip() g3<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=2, hjust=0.5, bar.width=0.75)+ggtitle('(C) Reverse Bar Chart')+ scale_y_reverse(limits = c(2800,0)) library(gridExtra) grid.arrange(g1,g2,g3, nrow = 1) ## ----e14, fig.height = 6, fig.width = 10--------------------------------- library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-c('hdashes', 'blank', 'crosshatch') pattern.color=c('black','black', 'black') background.color=c('white','white', 'white') density<-c(20, 20, 10) g1<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=-1, hjust=0.5)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(A) Bar Chart with Default Theme') g2<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=-1, hjust=0.5)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(B) Bar Chart with Classic Theme')+ theme_classic() library(gridExtra) grid.arrange(g1,g2, nrow = 1) ## ----e15, fig.height = 6, fig.width = 10--------------------------------- library(patternplot) library(png) library(ggplot2) #http://www.alanwood.net/demos/wgl4.html data <- data.frame(Type=c('Sunny', 'Cloudy', 'Rainy', 'Snowy'), Amount=c(5, 2, 3, 4)) x<-factor(data$Type, c('Sunny', 'Cloudy', 'Rainy', 'Snowy')) y<-data$Amount pattern.type<-c('Unicode_\u2600', 'Unicode_\u2601', 'Unicode_\u2602', 'Unicode_\u2603') pattern.color<-c('yellow','white','red', 'white') background.color=c('deepskyblue','deepskyblue','deepskyblue', 'deepskyblue') density<-c(16, 20, 16, 16) g1<-patternbar(data,x, y,group=NULL,ylab='Number of Days', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(10, 7, 10, 10), density=density, vjust=-1, hjust=0.5, bar.width =0.5)+scale_y_continuous(limits = c(0, 6))+ggtitle('(A) Bar Chart with Weather Symbols') data <- data.frame(Type=c('Female', 'Male'), Amount=c(50, 40)) x<-data$Type y<-data$Amount pattern.type<-c('Unicode_\u2640', 'Unicode_\u2642') pattern.color<-c('violet','deepskyblue') background.color=c('seashell','seashell') density<-c(10, 10) g2<-patternbar(data,x, y,group=NULL,ylab='Number of People', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(14, 14), density=density, pixel=18, vjust=-1, hjust=0.5, bar.width =0.5)+scale_y_continuous(limits = c(0, 60))+ggtitle('(B) Bar Chart with Gender Symbols') library(gridExtra) grid.arrange(g1,g2, nrow = 1)
/inst/doc/patternplot-intro.R
no_license
chunqiaoluo/patternplot_0.3.2
R
false
false
23,291
r
## ----setup, include=FALSE------------------------------------------------ library(knitr) library(Cairo) opts_chunk$set(out.extra='style="display:block; margin: auto"', fig.align="center", dev='CairoPNG') options(warn=-1) ## ----e1, fig.height = 6, fig.width = 10---------------------------------- library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "vegetables.csv", package="patternplot")) #Example 1 pattern.type<-c('hdashes', 'vdashes', 'bricks') pie1<-patternpie(group=data$group,pct=data$pct,label=data$label, label.size=4, label.color='black',label.distance=1.3,pattern.type=pattern.type, pattern.line.size=c(10, 10, 2), frame.color='black',frame.size=1.5, pixel=12, density=c(8, 8, 10)) pie1<-pie1+ggtitle('(A) Black and White with Patterns') #Example 2 pattern.color<-c('red3','green3', 'white' ) background.color<-c('dodgerblue', 'lightpink', 'orange') pie2<-patternpie(group=data$group,pct=data$pct,label=data$label, label.distance=1.3, pattern.type=pattern.type, pattern.color=pattern.color,background.color=background.color, pattern.line.size=c(10, 10, 2), frame.color='grey40',frame.size=1.5, pixel=12, density=c(8, 8, 10)) pie2<-pie2+ggtitle('(B) Colors with Patterns') library(gridExtra) grid.arrange(pie1,pie2, nrow = 1) ## ----e2, fig.height = 6, fig.width = 6----------------------------------- library(patternplot) library(ggplot2) library(jpeg) Tomatoes <- readJPEG(system.file("img", "tomatoes.jpg", package="patternplot")) Peas <- readJPEG(system.file("img", "peas.jpg", package="patternplot")) Potatoes <- readJPEG(system.file("img", "potatoes.jpg", package="patternplot")) #Example 1 data <- read.csv(system.file("extdata", "vegetables.csv", package="patternplot")) pattern.type<-list(Tomatoes,Peas,Potatoes) imagepie(group=data$group,pct=data$pct,label=data$label,pattern.type=pattern.type, label.distance=1.3,frame.color='burlywood4', frame.size=0.8, label.size=6, label.color='forestgreen')+ggtitle('Pie Chart with Images') ## ----e3, fig.height = 6.5, fig.width = 6.5------------------------------- library(patternplot) library(png) library(ggplot2) group1<-c('New_England', 'Great_Lakes','Plains', 'Rocky_Mountain', 'Far_West','Southwest', 'Southeast', 'Mideast') pct1<-c( 12, 11, 17, 15, 8, 11, 16, 10) label1<-paste(group1, " \n ", pct1, "%", sep="") pattern.type1<-c("hdashes", "blank", "grid", "blank", "hlines", "blank", "waves", "blank") pattern.type.inner<-"blank" pattern.color1<-rep("white", 8) background.color1<-c("darkgreen", "darkcyan", "chocolate", "cadetblue1", "darkorchid", "yellowgreen", "hotpink", "lightslateblue") density1<-rep(11.5, length(group1)) pattern.line.size1=c(10, 1, 6, 1, 10, 1, 6, 1) g<-patternring1(group1, pct1, label1, label.size1=4,label.color1='black', label.distance1=1.36, pattern.type1, pattern.color1, pattern.line.size1,background.color1, frame.color='black',frame.size=1.2, density1, pixel=13, pattern.type.inner="blank",pattern.color.inner="white", pattern.line.size.inner=1, background.color.inner="white", pixel.inner=10, density.inner=1, r1=2.7, r2=4) g<-g+annotate(geom="text", x=0, y=0, label="2019 Number of Cases \n N=1000",color="black", size=4)+scale_x_continuous(limits=c(-7, 7))+scale_y_continuous(limits=c(-7, 7)) g ## ----e4, fig.height = 6, fig.width = 6----------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) location<-gsub('\\','/',tempdir(), fixed=T) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkgreen", pixel=8, res=8) FarWest<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkcyan", pixel=8, res=8) GreatLakes<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="chocolate", pixel=8, res=8) Mideast<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="cadetblue1", pixel=8, res=8) NewEngland<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkorchid", pixel=8, res=8) Plains<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="yellowgreen", pixel=8, res=8) RockyMountain<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="hotpink", pixel=8, res=8) Southeast<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="lightslateblue", pixel=8, res=8) Southwest <-readPNG(paste(location,'/',"blank",".png", sep='')) group1<-c('New_England', 'Great_Lakes','Plains', 'Rocky_Mountain', 'Far_West','Southwest', 'Southeast', 'Mideast') pct1<-c( 12, 11, 17, 15, 8, 11, 16, 10) label1<-paste(group1, " \n ", pct1, "%", sep="") pattern.type1<-list(NewEngland, GreatLakes,Plains, RockyMountain, FarWest,Southwest, Southeast, Mideast) pattern.type.inner<-readPNG(system.file("img", "USmap.png", package="patternplot")) g<-imagering1(group1, pct1, pattern.type1, pattern.type.inner, frame.color='black',frame.size=1.5, r1=3, r2=4,label1, label.size1=4,label.color1='black', label.distance1=1.3) g<-g+annotate(geom="text", x=0, y=-2, label="2019 Number of Cases \n N=1000",color="black", size=4)+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6)) g ## ----e5, fig.height = 6, fig.width = 10---------------------------------- library(patternplot) library(png) library(ggplot2) group1<-c("Wind", "Hydro", "Solar", "Coal", "Natural Gas", "Oil") pct1<-c(12, 15, 8, 22, 18, 25) label1<-paste(group1, " \n ", pct1 , "%", sep="") group2<-c("Renewable", "Non-Renewable") pct2<-c(35, 65) label2<-paste(group2, " \n ", pct2 , "%", sep="") pattern.type1<-rep(c( "blank"), times=6) pattern.type2<-c('grid', 'blank') pattern.type.inner<-"blank" pattern.color1<-rep('white', length(group1)) pattern.color2<-rep('white', length(group2)) background.color1<-c("darkolivegreen1", "white", "indianred", "gray81", "white", "sandybrown" ) background.color2<-c("seagreen", "deepskyblue") density1<-rep(10, length(group1)) density2<-rep(10, length(group2)) pattern.line.size1=rep(5, length(group1)) pattern.line.size2=rep(2, length(group2)) pattern.line.size.inner=1 #Example 1: Two rings g<-patternrings2(group1, group2, pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.75, label.distance2=1.4, pattern.type1, pattern.type2, pattern.color1,pattern.color2, pattern.line.size1, pattern.line.size2, background.color1, background.color2,density1=rep(10, length(group1)), density2=rep(15, length(group2)),pixel=10, pattern.type.inner, pattern.color.inner="black",pattern.line.size.inner, background.color.inner="white", pixel.inner=6, density.inner=5, frame.color='black',frame.size=1.5,r1=2.45, r2=4.25, r3=5) g1<-g+annotate(geom="text", x=0, y=0, label="Earth's Energy",color="black", size=5)+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6))+ggtitle("(A) Two Rings") #Example 2: Pie in a ring g<-patternrings2(group1, group2, pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.7, label.distance2=1.4, pattern.type1, pattern.type2, pattern.color1,pattern.color2, pattern.line.size1, pattern.line.size2, background.color1, background.color2,density1=rep(10, length(group1)), density2=rep(15, length(group2)),pixel=10, pattern.type.inner, pattern.color.inner="black",pattern.line.size.inner, background.color.inner="white", pixel.inner=2, density.inner=5, frame.color='black',frame.size=1.5, r1=0.005, r2=4, r3=4.75) g2<-g+scale_x_continuous(limits=c(-6, 6))+scale_y_continuous(limits=c(-6, 6))+ggtitle("(B) Pie in a Ring") library(gridExtra) grid.arrange(g1,g2, nrow = 1) ## ----e6, fig.height = 6, fig.width = 6----------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) group1<-c("Wind", "Hydro", "Solar", "Coal", "Natural Gas", "Oil") pct1<-c(12, 15, 8, 22, 18, 25) label1<-paste(group1, " \n ", pct1 , "%", sep="") location<-gsub('\\','/',tempdir(), fixed=T) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="darkolivegreen1", pixel=20, res=15) Wind<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="white", pixel=20, res=15) Hydro<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="indianred", pixel=20, res=15) Solar<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="gray81", pixel=20, res=15) Coal<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="white", pixel=20, res=15) NaturalGas<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="sandybrown", pixel=20, res=15) Oil<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern.type1<-list(Wind, Hydro, Solar, Coal, NaturalGas, Oil) group2<-c("Renewable", "Non-Renewable") pct2<-c(35, 65) label2<-paste(group2, " \n ", pct2 , "%", sep="") pattern(type="grid", density=12, color='white', pattern.line.size=5, background.color="seagreen", pixel=20, res=15) Renewable<-readPNG(paste(location,'/',"grid",".png", sep='')) pattern(type="blank", density=1, color='white', pattern.line.size=1, background.color="deepskyblue", pixel=20, res=15) NonRenewable<-readPNG(paste(location,'/',"blank",".png", sep='')) pattern.type2<-list(Renewable, NonRenewable) pattern.type.inner<-readPNG(system.file("img", "earth.png", package="patternplot")) g<-imagerings2(group1, group2,pct1,pct2, label1, label2, label.size1=3, label.size2=3.5, label.color1='black', label.color2='black', label.distance1=0.7, label.distance2=1.3, pattern.type1, pattern.type2, pattern.type.inner, frame.color='skyblue',frame.size=1.5, r1=2.2, r2=4.2, r3=5) g<-g+scale_x_continuous(limits=c(-7, 7))+scale_y_continuous(limits=c(-7, 7)) g ## ----e7, fig.width=6, fig.height=6--------------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-c('hdashes', 'blank', 'crosshatch') pattern.color=c('black','black', 'black') background.color=c('white','white', 'white') density<-c(20, 20, 10) barp1<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type, hjust=0.5, pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4), frame.color=c('black', 'black', 'black'), density=density)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(A) Black and White with Patterns') #Example 2 pattern.color=c('black','white', 'grey20') background.color=c('lightgreen','lightgreen', 'lightgreen') barp2<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,hjust=0.5, pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4), frame.color=c('black', 'black', 'black'), density=density)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(B) Colors with Patterns') library(gridExtra) grid.arrange(barp1,barp2, nrow = 1) #Example 3 data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) group<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount x<-factor(data$Location, c('City 1', ' City 1')) pattern.type<-c( 'Rsymbol_16', 'blank','hdashes') pattern.color=c('yellow', 'chartreuse4', 'pink') background.color=c('grey', 'chartreuse3', 'bisque') barp3<-patternbar(data,x, y,group,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type, pattern.color=pattern.color,background.color=background.color, pattern.line.size=c(6, 10,6), frame.size=1,frame.color='black',pixel=16, density=c(18, 10, 14), legend.type='h', legend.h=12, legend.y.pos=0.49, vjust=-1, hjust=0.5,legend.pixel=6, legend.w=0.275,legend.x.pos=1.1) +scale_y_continuous(limits = c(0, 3100))+ggtitle('(C) Bar Chart with Two Grouping Variables') barp3 ## ----e8, fig.width=6, fig.height=6--------------------------------------- #Example 1 library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) x<-data$Location y<-data$Amount group<-data$Type patternbar_s(data,x, y, group,xlab='', ylab='Monthly Expenses, Dollar', label.size=3,pattern.type=c( 'Rsymbol_16', 'blank','hdashes'), pattern.line.size=c(5, 10, 10),frame.size=1,pattern.color=c('yellow', 'chartreuse4', 'pink'),background.color=c('grey', 'chartreuse3', 'bisque'), pixel=16, density=c(18, 10, 10),frame.color='black', legend.type='h', legend.h=12, legend.y.pos=0.49, legend.pixel=6, legend.w=0.275, legend.x.pos=1.05, bar.width=0.8)+scale_y_continuous(limits = c(0, 6800))+ggtitle('Stacked Bar Chart') ## ----e9, fig.width=6, fig.height=6--------------------------------------- library(patternplot) library(jpeg) library(ggplot2) childcare<-readJPEG(system.file("img", "childcare.jpg", package="patternplot")) food<-readJPEG(system.file("img", "food.jpg", package="patternplot")) housing <-readJPEG(system.file("img", "housing.jpg", package="patternplot")) #Example 1 data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-list(housing, food, childcare) imagebar(data,x, y,group=NULL,pattern.type=pattern.type,vjust=-1, hjust=0.5, frame.color='black', ylab='Monthly Expenses, Dollars')+ggtitle('(A) Bar Chart with Images') #Example 2 data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) group<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount x<-factor(data$Location, c('City 1', ' City 1')) pattern.type<-list(housing, food, childcare) imagebar(data,x, y,group,pattern.type=pattern.type,vjust=-1, hjust=0.5, frame.color='black', ylab='Monthly Expenses, Dollars')+ggtitle('(B) Image Bar Chart with Two Grouping Variables') ## ----e10, fig.width=6, fig.height=6-------------------------------------- library(patternplot) library(jpeg) library(ggplot2) childcare<-readJPEG(system.file("img", "childcare.jpg", package="patternplot")) food<-readJPEG(system.file("img", "food.jpg", package="patternplot")) housing <-readJPEG(system.file("img", "housing.jpg", package="patternplot")) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) x<-data$Location y<-data$Amount group<-data$Type pattern.type<-list(childcare, food, housing) imagebar_s(data,x, y, group, xlab='', ylab='Monthly Expenses, Dollar', pattern.type=pattern.type, label.size=3.5, frame.size=1.25, frame.color='black',legend.type='h', legend.h=6, legend.y.pos=0.49, legend.pixel=20, legend.w=0.2,legend.x.pos=1.1)+ scale_y_continuous(limits = c(0, 6800))+ggtitle('Stacked Bar Chart with Images') ## ----e11, fig.height = 6, fig.width = 12--------------------------------- #Example 1 data <- read.csv(system.file("extdata", "fruits.csv", package="patternplot")) group<-data$Fruit y<-data$Weight x<-data$Store pattern.type<-c('nwlines', 'blank', 'waves') pattern.color=c('black','black', 'black') background.color=c('white','gray80', 'white') frame.color=c('black', 'black', 'black') pattern.line.size<-c(6, 1,6) density<-c(6, 1, 8) box1<-patternboxplot(data,x, y,group,pattern.type=pattern.type,pattern.line.size=pattern.line.size, label.size=3, pattern.color=pattern.color, background.color=background.color,frame.color=frame.color, density=density, legend.h=2, legend.x.pos=1.075, legend.y.pos=0.499, legend.pixel=10, legend.w=0.18)+ggtitle('(A) Boxplot with Black and White Patterns') #Example 2 pattern.color=c('black','white', 'grey20') background.color=c('gold','lightpink', 'lightgreen') box2<-patternboxplot(data,x, y,group=group,pattern.type=pattern.type,pattern.line.size=pattern.line.size, label.size=3, pattern.color=pattern.color, background.color=background.color, frame.color=frame.color, density=density, legend.h=2, legend.x.pos=1.075, legend.y.pos=0.499, legend.pixel=10, legend.w=0.18)+ggtitle('(B) Boxplot with Colors and Patterns') library(gridExtra) grid.arrange(box1,box2, nrow = 1) ## ----e12, fig.height = 6, fig.width = 12--------------------------------- library(patternplot) library(jpeg) library(ggplot2) Orange<-readJPEG(system.file("img", "oranges.jpg", package="patternplot")) Strawberry <-readJPEG(system.file("img", "strawberries.jpg", package="patternplot")) Watermelon<-readJPEG(system.file("img", "watermelons.jpg", package="patternplot")) #Example 1 data <- read.csv(system.file("extdata", "fruits.csv", package="patternplot")) x<-data$Fruit y<-data$Weight group<-data$Store pattern.type<-list(Orange, Strawberry, Watermelon) box1<-imageboxplot(data,x, y,group=NULL,pattern.type=pattern.type,frame.color=c('orange', 'darkred', 'darkgreen'),ylab='Weight, Pounds')+ggtitle('(A) Image Boxplot with One Grouping Variable') #Example 2 x<-data$Store y<-data$Weight group<-data$Fruit pattern.type<-list(Orange, Strawberry, Watermelon) box2<-imageboxplot(data,x, y,group=group, pattern.type=pattern.type, frame.color=c('orange', 'darkred', 'darkgreen'), linetype=c('solid', 'dashed', 'dotted'),frame.size=0.8, xlab='', ylab='Weights, pounds', legend.h=2, legend.x.pos=1.1, legend.y.pos=0.499, legend.w=0.2)+ggtitle('(B) Image Boxplot with Two Grouping Variables') library(gridExtra) grid.arrange(box1,box2, nrow = 1) ## ----e13, fig.height = 6, fig.width = 12--------------------------------- library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-c('hdashes', 'blank', 'crosshatch') pattern.color=c('black','black', 'black') background.color=c('white','white', 'white') density<-c(20, 20, 10) g1<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=-1, hjust=0.5, bar.width=0.75)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(A) Vertical Bar Chart') g2<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=0.5, hjust=-0.25, bar.width=0.5)+scale_y_continuous(limits = c(0,2800))+ggtitle('(B) Horizontal Bar Chart')+coord_flip() g3<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=2, hjust=0.5, bar.width=0.75)+ggtitle('(C) Reverse Bar Chart')+ scale_y_reverse(limits = c(2800,0)) library(gridExtra) grid.arrange(g1,g2,g3, nrow = 1) ## ----e14, fig.height = 6, fig.width = 10--------------------------------- library(patternplot) library(png) library(ggplot2) data <- read.csv(system.file("extdata", "monthlyexp.csv", package="patternplot")) data<-data[which(data$Location=='City 1'),] x<-factor(data$Type, c('Housing', 'Food', 'Childcare')) y<-data$Amount pattern.type<-c('hdashes', 'blank', 'crosshatch') pattern.color=c('black','black', 'black') background.color=c('white','white', 'white') density<-c(20, 20, 10) g1<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=-1, hjust=0.5)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(A) Bar Chart with Default Theme') g2<-patternbar(data,x, y,group=NULL,ylab='Monthly Expenses, Dollars', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(5.5, 1, 4),frame.color=c('black', 'black', 'black'), density=density, vjust=-1, hjust=0.5)+scale_y_continuous(limits = c(0, 2800))+ggtitle('(B) Bar Chart with Classic Theme')+ theme_classic() library(gridExtra) grid.arrange(g1,g2, nrow = 1) ## ----e15, fig.height = 6, fig.width = 10--------------------------------- library(patternplot) library(png) library(ggplot2) #http://www.alanwood.net/demos/wgl4.html data <- data.frame(Type=c('Sunny', 'Cloudy', 'Rainy', 'Snowy'), Amount=c(5, 2, 3, 4)) x<-factor(data$Type, c('Sunny', 'Cloudy', 'Rainy', 'Snowy')) y<-data$Amount pattern.type<-c('Unicode_\u2600', 'Unicode_\u2601', 'Unicode_\u2602', 'Unicode_\u2603') pattern.color<-c('yellow','white','red', 'white') background.color=c('deepskyblue','deepskyblue','deepskyblue', 'deepskyblue') density<-c(16, 20, 16, 16) g1<-patternbar(data,x, y,group=NULL,ylab='Number of Days', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(10, 7, 10, 10), density=density, vjust=-1, hjust=0.5, bar.width =0.5)+scale_y_continuous(limits = c(0, 6))+ggtitle('(A) Bar Chart with Weather Symbols') data <- data.frame(Type=c('Female', 'Male'), Amount=c(50, 40)) x<-data$Type y<-data$Amount pattern.type<-c('Unicode_\u2640', 'Unicode_\u2642') pattern.color<-c('violet','deepskyblue') background.color=c('seashell','seashell') density<-c(10, 10) g2<-patternbar(data,x, y,group=NULL,ylab='Number of People', pattern.type=pattern.type,pattern.color=pattern.color, background.color=background.color,pattern.line.size=c(14, 14), density=density, pixel=18, vjust=-1, hjust=0.5, bar.width =0.5)+scale_y_continuous(limits = c(0, 60))+ggtitle('(B) Bar Chart with Gender Symbols') library(gridExtra) grid.arrange(g1,g2, nrow = 1)
\name{incrementalMultivariateRegression} \alias{incrementalMultivariateRegression} \alias{incrementalMultivariateRegression-methods} \alias{incrementalMultivariateRegression,data.frame-method} \alias{incrementalMultivariateRegression,matrix-method} \alias{incrementalMultivariateRegression,numeric-method} \alias{incrementalMultivariateRegression,vector-method} \title{ incremental Multivariate Regression } \description{ processed the incremental Multivariate Regression } \usage{ incrementalMultivariateRegression(dataSet, yName, alphaValue, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{dataSet}{ input data set } \item{yName}{ Name of the column which should be predicted } \item{alphaValue}{ significance level } \item{\dots}{ not used } } \author{ Alexander Entzian \email{a.entzian@alexander-entzian.de} } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{incReg}} \code{\link{car}} \code{\link{stats}} } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ models } \keyword{ regression } \keyword{ multivariate }
/man/incrementalMultivariateRegression.Rd
no_license
cran/incReg
R
false
false
1,214
rd
\name{incrementalMultivariateRegression} \alias{incrementalMultivariateRegression} \alias{incrementalMultivariateRegression-methods} \alias{incrementalMultivariateRegression,data.frame-method} \alias{incrementalMultivariateRegression,matrix-method} \alias{incrementalMultivariateRegression,numeric-method} \alias{incrementalMultivariateRegression,vector-method} \title{ incremental Multivariate Regression } \description{ processed the incremental Multivariate Regression } \usage{ incrementalMultivariateRegression(dataSet, yName, alphaValue, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{dataSet}{ input data set } \item{yName}{ Name of the column which should be predicted } \item{alphaValue}{ significance level } \item{\dots}{ not used } } \author{ Alexander Entzian \email{a.entzian@alexander-entzian.de} } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \code{\link{incReg}} \code{\link{car}} \code{\link{stats}} } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \keyword{ models } \keyword{ regression } \keyword{ multivariate }
rm(list = ls()) library(magrittr) library(dplyr) library(VIM) library(caret) library(randomForest) library(verification) # normalized gini function taked from: # https://www.kaggle.com/c/ClaimPredictionChallenge/discussion/703 normalizedGini <- function(aa, pp) { Gini <- function(a, p) { if (length(a) != length(p)) stop("Actual and Predicted need to be equal lengths!") temp.df <- data.frame(actual = a, pred = p, range=c(1:length(a))) temp.df <- temp.df[order(-temp.df$pred, temp.df$range),] population.delta <- 1 / length(a) total.losses <- sum(a) null.losses <- rep(population.delta, length(a)) # Hopefully is similar to accumulatedPopulationPercentageSum accum.losses <- temp.df$actual / total.losses # Hopefully is similar to accumulatedLossPercentageSum gini.sum <- cumsum(accum.losses - null.losses) # Not sure if this is having the same effect or not sum(gini.sum) / length(a) } Gini(aa,pp) / Gini(aa,aa) } setwd("C:\\Users\\shrad\\Desktop\\AML\\Kaggle") file_name <- "train.csv" train <- read.csv(file_name) train[train == -1] <- NA #removing all the columns of calc as there is hardly any variation in target values drops <- names(train)[grepl('_calc', names(train))] ################################### handling missing values ########################################### # 79% data have atleast one NA value (nrow(train) - sum(complete.cases(train)))/nrow(train) # substituting with mean value for -1 in numeric data columns wit missing values train$ps_car_12[train$ps_car_12 == -1] <- mean(train$ps_car_12[train$ps_car_12 != -1]) # number of -1 value = 1 train$ps_car_11[train$ps_car_11 == -1] <- mean(train$ps_car_11[train$ps_car_11 != -1]) # number of -1 value = 5 train$ps_car_14[train$ps_car_14 == -1] <- mean(train$ps_car_14[train$ps_car_14 != -1]) # number of -1 value = 42620 train$ps_reg_03[train$ps_reg_03 == -1] <- mean(train$ps_reg_03[train$ps_reg_03 != -1]) # number of -1 value = 107772 # Adding ps_car_05_cat to the list as 25% values in the column are NA and teh distribution of # target values for the remaining 75% values of ps_car_05_cat is equally distributed drops <- c(drops, "ps_car_05_cat") # ps_car_03_cat : has maximum number of NAs. # However, the prediction follows a linearly increasing graph. # hence, we keep the column as it is with -1 values for NA in the column # ps_ind_04_cat : Has 40% of rows with NA values has target = 1. However, only 3% of both ps_ind_04_cat =0 # and 1 is target = 1. Hence, right now keeping the columns as it is with an exra factor for -1. # ps_car_01_cat : similiar case as above with 38% for NA factor as target = 1 and almost 5% for # all the other values # ps_car_07_cat : similiar to ps_car_03_cat logic. Here, it follows a linearly decreasing graph. # ps_ind_02_cat : similar case as above with 17 % for target = 1. Dropping the column. drops <- c(drops, "ps_ind_02_cat") # ps_car_09_cat : in this case replacing all the values with -1 as 1 as the percentage of target = 1 is almost 9% # ps_car_09_cat = 1 has the most number of target = 1 after NAs which is 5% train$ps_car_09_cat[train$ps_car_09_cat == -1] <- 1 # ps_ind_05_cat : with similiar logic to above, replacing the values with 2. train$ps_ind_05_cat[train$ps_ind_05_cat == -1] <- 2 # ps_car_02_cat : similiar logic as above train$ps_car_02_cat[train$ps_car_02_cat == -1] <- 0 dtrain <- train[,!(names(train) %in% drops)] sort(colSums(dtrain == -1)) ######################## one hot encoding for factor variables ############################## # collect the categorical variable names cat_vars <- names(dtrain)[grepl('_cat$', names(dtrain))] # removing ps_car_11_cat as the number of levels is huge and it might not be a categorical variable cat_vars <- cat_vars[1:11] # convert categorical features to factors dtrain <- dtrain %>% mutate_at(.vars = cat_vars, .funs = as.factor) str(dtrain) # One hot encode the factor variables dtrain <- as.data.frame(model.matrix(~ . - 1, data = dtrain)) str(dtrain) #make target variable into factors dtrain$target <- as.factor(dtrain$target) # set seed for reproducibility set.seed(123) # making a train index train_index <- sample(c(TRUE, FALSE), replace = TRUE, size = nrow(dtrain), prob = c(0.1,0.9)) names(dtrain)[5] <- "ps_ind_04_cat_1" # split the data according to the train index training <- as.data.frame(dtrain[train_index, ]) testing <- as.data.frame(dtrain[!train_index, ]) ########################### Random Forest ########################################################## library(randomForest) str(training) drops <- c("id") training <- training[,!(names(training) %in% drops)] fit <- randomForest(target ~ ., training,ntree=500) predicted <- predict(fit,testing, type = "prob") normalizedGini(as.integer(testing$target), predicted[,2]) # gini coefficient on train data is 0.2157639
/Random_Forest.R
no_license
BBaggines/ML
R
false
false
4,998
r
rm(list = ls()) library(magrittr) library(dplyr) library(VIM) library(caret) library(randomForest) library(verification) # normalized gini function taked from: # https://www.kaggle.com/c/ClaimPredictionChallenge/discussion/703 normalizedGini <- function(aa, pp) { Gini <- function(a, p) { if (length(a) != length(p)) stop("Actual and Predicted need to be equal lengths!") temp.df <- data.frame(actual = a, pred = p, range=c(1:length(a))) temp.df <- temp.df[order(-temp.df$pred, temp.df$range),] population.delta <- 1 / length(a) total.losses <- sum(a) null.losses <- rep(population.delta, length(a)) # Hopefully is similar to accumulatedPopulationPercentageSum accum.losses <- temp.df$actual / total.losses # Hopefully is similar to accumulatedLossPercentageSum gini.sum <- cumsum(accum.losses - null.losses) # Not sure if this is having the same effect or not sum(gini.sum) / length(a) } Gini(aa,pp) / Gini(aa,aa) } setwd("C:\\Users\\shrad\\Desktop\\AML\\Kaggle") file_name <- "train.csv" train <- read.csv(file_name) train[train == -1] <- NA #removing all the columns of calc as there is hardly any variation in target values drops <- names(train)[grepl('_calc', names(train))] ################################### handling missing values ########################################### # 79% data have atleast one NA value (nrow(train) - sum(complete.cases(train)))/nrow(train) # substituting with mean value for -1 in numeric data columns wit missing values train$ps_car_12[train$ps_car_12 == -1] <- mean(train$ps_car_12[train$ps_car_12 != -1]) # number of -1 value = 1 train$ps_car_11[train$ps_car_11 == -1] <- mean(train$ps_car_11[train$ps_car_11 != -1]) # number of -1 value = 5 train$ps_car_14[train$ps_car_14 == -1] <- mean(train$ps_car_14[train$ps_car_14 != -1]) # number of -1 value = 42620 train$ps_reg_03[train$ps_reg_03 == -1] <- mean(train$ps_reg_03[train$ps_reg_03 != -1]) # number of -1 value = 107772 # Adding ps_car_05_cat to the list as 25% values in the column are NA and teh distribution of # target values for the remaining 75% values of ps_car_05_cat is equally distributed drops <- c(drops, "ps_car_05_cat") # ps_car_03_cat : has maximum number of NAs. # However, the prediction follows a linearly increasing graph. # hence, we keep the column as it is with -1 values for NA in the column # ps_ind_04_cat : Has 40% of rows with NA values has target = 1. However, only 3% of both ps_ind_04_cat =0 # and 1 is target = 1. Hence, right now keeping the columns as it is with an exra factor for -1. # ps_car_01_cat : similiar case as above with 38% for NA factor as target = 1 and almost 5% for # all the other values # ps_car_07_cat : similiar to ps_car_03_cat logic. Here, it follows a linearly decreasing graph. # ps_ind_02_cat : similar case as above with 17 % for target = 1. Dropping the column. drops <- c(drops, "ps_ind_02_cat") # ps_car_09_cat : in this case replacing all the values with -1 as 1 as the percentage of target = 1 is almost 9% # ps_car_09_cat = 1 has the most number of target = 1 after NAs which is 5% train$ps_car_09_cat[train$ps_car_09_cat == -1] <- 1 # ps_ind_05_cat : with similiar logic to above, replacing the values with 2. train$ps_ind_05_cat[train$ps_ind_05_cat == -1] <- 2 # ps_car_02_cat : similiar logic as above train$ps_car_02_cat[train$ps_car_02_cat == -1] <- 0 dtrain <- train[,!(names(train) %in% drops)] sort(colSums(dtrain == -1)) ######################## one hot encoding for factor variables ############################## # collect the categorical variable names cat_vars <- names(dtrain)[grepl('_cat$', names(dtrain))] # removing ps_car_11_cat as the number of levels is huge and it might not be a categorical variable cat_vars <- cat_vars[1:11] # convert categorical features to factors dtrain <- dtrain %>% mutate_at(.vars = cat_vars, .funs = as.factor) str(dtrain) # One hot encode the factor variables dtrain <- as.data.frame(model.matrix(~ . - 1, data = dtrain)) str(dtrain) #make target variable into factors dtrain$target <- as.factor(dtrain$target) # set seed for reproducibility set.seed(123) # making a train index train_index <- sample(c(TRUE, FALSE), replace = TRUE, size = nrow(dtrain), prob = c(0.1,0.9)) names(dtrain)[5] <- "ps_ind_04_cat_1" # split the data according to the train index training <- as.data.frame(dtrain[train_index, ]) testing <- as.data.frame(dtrain[!train_index, ]) ########################### Random Forest ########################################################## library(randomForest) str(training) drops <- c("id") training <- training[,!(names(training) %in% drops)] fit <- randomForest(target ~ ., training,ntree=500) predicted <- predict(fit,testing, type = "prob") normalizedGini(as.integer(testing$target), predicted[,2]) # gini coefficient on train data is 0.2157639
# ============================================================================================================ # Description: Course Project Week 1 / LabWeek 1 # Coursera Statistics at Duke University # # Author: Bruno Hunkeler # Date: xx.07.2016 # # ============================================================================================================ install.packages("devtools") devtools::install_github("StatsWithR/statsr") # ============================================================================================================ # Load Libraries # ============================================================================================================ library('dplyr') library('ggplot2') library('plyr') library('devtools') library('statsr') library('shiny') # ============================================================================================================ # Download and extract Data and load file # ============================================================================================================ data(nc) # Question 1 str(nc) # Answer: 7 # Question 2 hist(nc$weight) # Answer: left skewed # Question 3 bayes_inference(y = weight, data = nc, cred_level = 0.99, statistic = "mean", type = "ci") # Answer: B 99% CI: (6.9778 , 7.2244) # Question 4 bayes_inference(y = weight, data = nc, statistic = "mean", type = "ht", null = 7, alternative = "twosided") # Answer: Positive BF[H1:H2] = 3.3915 boxplot(weight~habit,data=nc, main="title", xlab="smoker / non smoker", ylab="weight") dpois(10, 10) pbeta(0.5, 1 + 5029, 1 + 4971)
/Statistics - Duke University/004_Bayesian_Statistics/Week 3/Lab/Labweek3.R
no_license
bhunkeler/DataScienceCoursera
R
false
false
1,622
r
# ============================================================================================================ # Description: Course Project Week 1 / LabWeek 1 # Coursera Statistics at Duke University # # Author: Bruno Hunkeler # Date: xx.07.2016 # # ============================================================================================================ install.packages("devtools") devtools::install_github("StatsWithR/statsr") # ============================================================================================================ # Load Libraries # ============================================================================================================ library('dplyr') library('ggplot2') library('plyr') library('devtools') library('statsr') library('shiny') # ============================================================================================================ # Download and extract Data and load file # ============================================================================================================ data(nc) # Question 1 str(nc) # Answer: 7 # Question 2 hist(nc$weight) # Answer: left skewed # Question 3 bayes_inference(y = weight, data = nc, cred_level = 0.99, statistic = "mean", type = "ci") # Answer: B 99% CI: (6.9778 , 7.2244) # Question 4 bayes_inference(y = weight, data = nc, statistic = "mean", type = "ht", null = 7, alternative = "twosided") # Answer: Positive BF[H1:H2] = 3.3915 boxplot(weight~habit,data=nc, main="title", xlab="smoker / non smoker", ylab="weight") dpois(10, 10) pbeta(0.5, 1 + 5029, 1 + 4971)
library(sp) library(rgdal) # Pitch Interactive's Population based tilegram ---- # Read The shapefile for US Population Tilegram Pitch_US_Population_2016_v1 <- readOGR('./data-raw/Pitch_US_Population_2016_v1', 'Pitch_US_Population_2016_v1') devtools::use_data(Pitch_US_Population_2016_v1, overwrite = TRUE) # Dissolve polygons in to state polygons # So that we have one polygon per state Pitch_US_Population_2016_v1.states <- rmapshaper::ms_dissolve( Pitch_US_Population_2016_v1, 'state' ) devtools::use_data(Pitch_US_Population_2016_v1.states, overwrite = TRUE) # Centers for each state of the US Population Timegram Pitch_US_Population_2016_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(Pitch_US_Population_2016_v1.states, byid = TRUE, id=Pitch_US_Population_2016_v1.states@data$state), Pitch_US_Population_2016_v1.states@data, match.ID = F) devtools::use_data(Pitch_US_Population_2016_v1.centers, overwrite = TRUE) # fivethirtyeight.com's Electoral College based Tilegram ---- # Read the shapefile for the 538 Electoral College Tilegram # So that we have one polygon per state FiveThirtyEightElectoralCollege <- readOGR('./data-raw/FiveThirtyEightElectoralCollege', 'FiveThirtyEightElectoralCollege') devtools::use_data(FiveThirtyEightElectoralCollege, overwrite = TRUE) # Dissolve polygons in to state polygons FiveThirtyEightElectoralCollege.states <- rmapshaper::ms_dissolve( FiveThirtyEightElectoralCollege, 'state' ) devtools::use_data(FiveThirtyEightElectoralCollege.states, overwrite = TRUE) # Centers for each state of the 538 Electoral College Tilegram FiveThirtyEightElectoralCollege.centers = SpatialPointsDataFrame( rgeos::gCentroid(FiveThirtyEightElectoralCollege.states, byid = TRUE, id=FiveThirtyEightElectoralCollege.states@data$state), FiveThirtyEightElectoralCollege.states@data, match.ID = F) devtools::use_data(FiveThirtyEightElectoralCollege.centers, overwrite = TRUE) # NPR's Hexbin based tilegram ---- # Read the shapefile for the NPR 1 to 1 Tilegram NPR1to1 <- readOGR('./data-raw/NPR1to1', 'NPR1to1') devtools::use_data(NPR1to1, overwrite = TRUE) # No need to dissolve polygons as we already have one polygon per state # Centers for each state of the NPR 1 to 1 Tilegram NPR1to1.centers = SpatialPointsDataFrame( rgeos::gCentroid(NPR1to1, byid = TRUE, id=levels(NPR1to1@data$state)), NPR1to1@data, match.ID = F) devtools::use_data(NPR1to1.centers, overwrite = TRUE) # Congressional District Hexmaps from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/hexmap DKOS_CD_Hexmap_v1.1 <- readOGR('./data-raw/HexCDv11/','HexCDv11') devtools::use_data(DKOS_CD_Hexmap_v1.1, overwrite = TRUE) # The states shapefile has an invalid geometry which is fixed using cleangeo DKOS_CD_Hexmap_v1.1.states <- cleangeo::clgeo_Clean( readOGR('./data-raw/HexSTv11/','HexSTv11')) devtools::use_data(DKOS_CD_Hexmap_v1.1.states, overwrite = TRUE) DKOS_CD_Hexmap_v1.1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_CD_Hexmap_v1.1.states, byid = TRUE, id=DKOS_CD_Hexmap_v1.1.states@data$STATE), DKOS_CD_Hexmap_v1.1.states@data, match.ID = F) devtools::use_data(DKOS_CD_Hexmap_v1.1.centers, overwrite = TRUE) # Electoral College Map from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/electoral-college-map # The shapefile has an invalid geometry which is fixed using cleangeo DKOS_Electoral_College_Map_v1 <- cleangeo::clgeo_Clean( readOGR('./data-raw/ElecCollv10/','ElecCollv10')) # The state filed has different entries for Nebraska and Maine's Districts # So we need to extract the trueState from them. DKOS_Electoral_College_Map_v1@data %<>% dplyr::mutate(trueState=as.factor(stringr::str_extract(State,'^..'))) devtools::use_data(DKOS_Electoral_College_Map_v1, overwrite = TRUE) DKOS_Electoral_College_Map_v1.states <- rmapshaper::ms_dissolve( DKOS_Electoral_College_Map_v1, 'trueState' ) devtools::use_data(DKOS_Electoral_College_Map_v1.states, overwrite = TRUE) DKOS_Electoral_College_Map_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_Electoral_College_Map_v1.states, byid = TRUE, id=DKOS_Electoral_College_Map_v1.states@data$trueState), DKOS_Electoral_College_Map_v1.states@data, match.ID = F) devtools::use_data(DKOS_Electoral_College_Map_v1.centers, overwrite = TRUE) # Distorted Electoral College Map from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/electoral-college-map # The geometries of this shapefile can be simplified for performance reasons DKOS_Distorted_Electoral_College_Map_v1 <- rmapshaper::ms_simplify( readOGR('./data-raw/DistortECv10/','DistortECv10')) devtools::use_data(DKOS_Distorted_Electoral_College_Map_v1, overwrite = TRUE) DKOS_Distorted_Electoral_College_Map_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_Distorted_Electoral_College_Map_v1, byid = TRUE, id=DKOS_Distorted_Electoral_College_Map_v1@data$STUSPS), DKOS_Distorted_Electoral_College_Map_v1@data, match.ID = F) devtools::use_data(DKOS_Distorted_Electoral_College_Map_v1.centers, overwrite = TRUE) # 50 State Dual Hexbin Tilemap from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/tile-map DKOS_50_State_OuterHex_Tilemap_v1 <- readOGR('./data-raw/TileOutv10/','TileOutv10') DKOS_50_State_InnerHex_Tilemap_v1 <- readOGR('./data-raw/TileInv10/','TileInv10') devtools::use_data(DKOS_50_State_OuterHex_Tilemap_v1, overwrite = TRUE) devtools::use_data(DKOS_50_State_InnerHex_Tilemap_v1, overwrite = TRUE) DKOS_50_State_Hex_Tilemap_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_50_State_OuterHex_Tilemap_v1, byid = TRUE, id=DKOS_50_State_OuterHex_Tilemap_v1@data$State), DKOS_50_State_OuterHex_Tilemap_v1@data, match.ID = F) devtools::use_data(DKOS_50_State_Hex_Tilemap_v1.centers, overwrite = TRUE) # NPR Demers Cartogram ---- # http://www.npr.org/2016/10/09/497277536 NPR.DemersCartogram <- readOGR('./data-raw/NPR/npr.geojson', 'OGRGeoJSON') proj4string(NPR.DemersCartogram) <- '' devtools::use_data(NPR.DemersCartogram, overwrite = TRUE) NPR.DemersCartogram.centers = SpatialPointsDataFrame( rgeos::gCentroid(NPR.DemersCartogram, byid = TRUE, id=NPR.DemersCartogram@data$id), NPR.DemersCartogram@data, match.ID = F) devtools::use_data(NPR.DemersCartogram.centers, overwrite = TRUE) # Washington Post Tiles ---- # https://www.washingtonpost.com/graphics/politics/2016-election/50-state-poll/ WP <- readOGR('./data-raw/WashingtonPost/wp.geojson', 'OGRGeoJSON') proj4string(WP) <- '' devtools::use_data(WP, overwrite = TRUE) WP.centers = SpatialPointsDataFrame( rgeos::gCentroid(WP, byid = TRUE, id=WP@data$id), WP@data, match.ID = F) devtools::use_data(WP.centers, overwrite = TRUE) # Wall Street Journal Tiles ---- # http://graphics.wsj.com/elections/2016/2016-electoral-college-map-predictions/ WSJ <- readOGR('./data-raw/WallStreetJournal/wsj.geojson', 'OGRGeoJSON') proj4string(WSJ) <- '' devtools::use_data(WSJ, overwrite = TRUE) WSJ.centers = SpatialPointsDataFrame( rgeos::gCentroid(WSJ, byid = TRUE, id=WSJ@data$id), WSJ@data, match.ID = F) devtools::use_data(WSJ.centers, overwrite = TRUE) # Datamap.io ---- # https://elections.datamap.io/us/2016/09/23/electoral_college_forecast # http://bl.ocks.org/rogerfischer/15ef631812c56e3ef85af8191ef0de75 Datamap.io.tilegram <- readOGR('./data-raw/datamap', 'us_ec2016_state_hexagon') Datamap.io.tilegram@data %<>% dplyr::mutate(FIPS=stringr::str_extract(id,'..$')) Datamap.io.tilegram@data %<>% dplyr::left_join( usgazetteer::state.areas.2010 %>% dplyr::select(State, FIPS, USPS), by=c('FIPS'='FIPS')) devtools::use_data(Datamap.io.tilegram, overwrite = TRUE) Datamap.io.tilegram.centers = SpatialPointsDataFrame( rgeos::gCentroid(Datamap.io.tilegram, byid = TRUE, id=Datamap.io.tilegram@data$id), Datamap.io.tilegram@data, match.ID = F) devtools::use_data(Datamap.io.tilegram.centers, overwrite = TRUE)
/data-raw/data.R
no_license
radovankavicky/tilegramsR
R
false
false
8,335
r
library(sp) library(rgdal) # Pitch Interactive's Population based tilegram ---- # Read The shapefile for US Population Tilegram Pitch_US_Population_2016_v1 <- readOGR('./data-raw/Pitch_US_Population_2016_v1', 'Pitch_US_Population_2016_v1') devtools::use_data(Pitch_US_Population_2016_v1, overwrite = TRUE) # Dissolve polygons in to state polygons # So that we have one polygon per state Pitch_US_Population_2016_v1.states <- rmapshaper::ms_dissolve( Pitch_US_Population_2016_v1, 'state' ) devtools::use_data(Pitch_US_Population_2016_v1.states, overwrite = TRUE) # Centers for each state of the US Population Timegram Pitch_US_Population_2016_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(Pitch_US_Population_2016_v1.states, byid = TRUE, id=Pitch_US_Population_2016_v1.states@data$state), Pitch_US_Population_2016_v1.states@data, match.ID = F) devtools::use_data(Pitch_US_Population_2016_v1.centers, overwrite = TRUE) # fivethirtyeight.com's Electoral College based Tilegram ---- # Read the shapefile for the 538 Electoral College Tilegram # So that we have one polygon per state FiveThirtyEightElectoralCollege <- readOGR('./data-raw/FiveThirtyEightElectoralCollege', 'FiveThirtyEightElectoralCollege') devtools::use_data(FiveThirtyEightElectoralCollege, overwrite = TRUE) # Dissolve polygons in to state polygons FiveThirtyEightElectoralCollege.states <- rmapshaper::ms_dissolve( FiveThirtyEightElectoralCollege, 'state' ) devtools::use_data(FiveThirtyEightElectoralCollege.states, overwrite = TRUE) # Centers for each state of the 538 Electoral College Tilegram FiveThirtyEightElectoralCollege.centers = SpatialPointsDataFrame( rgeos::gCentroid(FiveThirtyEightElectoralCollege.states, byid = TRUE, id=FiveThirtyEightElectoralCollege.states@data$state), FiveThirtyEightElectoralCollege.states@data, match.ID = F) devtools::use_data(FiveThirtyEightElectoralCollege.centers, overwrite = TRUE) # NPR's Hexbin based tilegram ---- # Read the shapefile for the NPR 1 to 1 Tilegram NPR1to1 <- readOGR('./data-raw/NPR1to1', 'NPR1to1') devtools::use_data(NPR1to1, overwrite = TRUE) # No need to dissolve polygons as we already have one polygon per state # Centers for each state of the NPR 1 to 1 Tilegram NPR1to1.centers = SpatialPointsDataFrame( rgeos::gCentroid(NPR1to1, byid = TRUE, id=levels(NPR1to1@data$state)), NPR1to1@data, match.ID = F) devtools::use_data(NPR1to1.centers, overwrite = TRUE) # Congressional District Hexmaps from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/hexmap DKOS_CD_Hexmap_v1.1 <- readOGR('./data-raw/HexCDv11/','HexCDv11') devtools::use_data(DKOS_CD_Hexmap_v1.1, overwrite = TRUE) # The states shapefile has an invalid geometry which is fixed using cleangeo DKOS_CD_Hexmap_v1.1.states <- cleangeo::clgeo_Clean( readOGR('./data-raw/HexSTv11/','HexSTv11')) devtools::use_data(DKOS_CD_Hexmap_v1.1.states, overwrite = TRUE) DKOS_CD_Hexmap_v1.1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_CD_Hexmap_v1.1.states, byid = TRUE, id=DKOS_CD_Hexmap_v1.1.states@data$STATE), DKOS_CD_Hexmap_v1.1.states@data, match.ID = F) devtools::use_data(DKOS_CD_Hexmap_v1.1.centers, overwrite = TRUE) # Electoral College Map from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/electoral-college-map # The shapefile has an invalid geometry which is fixed using cleangeo DKOS_Electoral_College_Map_v1 <- cleangeo::clgeo_Clean( readOGR('./data-raw/ElecCollv10/','ElecCollv10')) # The state filed has different entries for Nebraska and Maine's Districts # So we need to extract the trueState from them. DKOS_Electoral_College_Map_v1@data %<>% dplyr::mutate(trueState=as.factor(stringr::str_extract(State,'^..'))) devtools::use_data(DKOS_Electoral_College_Map_v1, overwrite = TRUE) DKOS_Electoral_College_Map_v1.states <- rmapshaper::ms_dissolve( DKOS_Electoral_College_Map_v1, 'trueState' ) devtools::use_data(DKOS_Electoral_College_Map_v1.states, overwrite = TRUE) DKOS_Electoral_College_Map_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_Electoral_College_Map_v1.states, byid = TRUE, id=DKOS_Electoral_College_Map_v1.states@data$trueState), DKOS_Electoral_College_Map_v1.states@data, match.ID = F) devtools::use_data(DKOS_Electoral_College_Map_v1.centers, overwrite = TRUE) # Distorted Electoral College Map from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/electoral-college-map # The geometries of this shapefile can be simplified for performance reasons DKOS_Distorted_Electoral_College_Map_v1 <- rmapshaper::ms_simplify( readOGR('./data-raw/DistortECv10/','DistortECv10')) devtools::use_data(DKOS_Distorted_Electoral_College_Map_v1, overwrite = TRUE) DKOS_Distorted_Electoral_College_Map_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_Distorted_Electoral_College_Map_v1, byid = TRUE, id=DKOS_Distorted_Electoral_College_Map_v1@data$STUSPS), DKOS_Distorted_Electoral_College_Map_v1@data, match.ID = F) devtools::use_data(DKOS_Distorted_Electoral_College_Map_v1.centers, overwrite = TRUE) # 50 State Dual Hexbin Tilemap from Daily KOS ---- # http://refinery.dailykosbeta.com/elections-maps/tile-map DKOS_50_State_OuterHex_Tilemap_v1 <- readOGR('./data-raw/TileOutv10/','TileOutv10') DKOS_50_State_InnerHex_Tilemap_v1 <- readOGR('./data-raw/TileInv10/','TileInv10') devtools::use_data(DKOS_50_State_OuterHex_Tilemap_v1, overwrite = TRUE) devtools::use_data(DKOS_50_State_InnerHex_Tilemap_v1, overwrite = TRUE) DKOS_50_State_Hex_Tilemap_v1.centers = SpatialPointsDataFrame( rgeos::gCentroid(DKOS_50_State_OuterHex_Tilemap_v1, byid = TRUE, id=DKOS_50_State_OuterHex_Tilemap_v1@data$State), DKOS_50_State_OuterHex_Tilemap_v1@data, match.ID = F) devtools::use_data(DKOS_50_State_Hex_Tilemap_v1.centers, overwrite = TRUE) # NPR Demers Cartogram ---- # http://www.npr.org/2016/10/09/497277536 NPR.DemersCartogram <- readOGR('./data-raw/NPR/npr.geojson', 'OGRGeoJSON') proj4string(NPR.DemersCartogram) <- '' devtools::use_data(NPR.DemersCartogram, overwrite = TRUE) NPR.DemersCartogram.centers = SpatialPointsDataFrame( rgeos::gCentroid(NPR.DemersCartogram, byid = TRUE, id=NPR.DemersCartogram@data$id), NPR.DemersCartogram@data, match.ID = F) devtools::use_data(NPR.DemersCartogram.centers, overwrite = TRUE) # Washington Post Tiles ---- # https://www.washingtonpost.com/graphics/politics/2016-election/50-state-poll/ WP <- readOGR('./data-raw/WashingtonPost/wp.geojson', 'OGRGeoJSON') proj4string(WP) <- '' devtools::use_data(WP, overwrite = TRUE) WP.centers = SpatialPointsDataFrame( rgeos::gCentroid(WP, byid = TRUE, id=WP@data$id), WP@data, match.ID = F) devtools::use_data(WP.centers, overwrite = TRUE) # Wall Street Journal Tiles ---- # http://graphics.wsj.com/elections/2016/2016-electoral-college-map-predictions/ WSJ <- readOGR('./data-raw/WallStreetJournal/wsj.geojson', 'OGRGeoJSON') proj4string(WSJ) <- '' devtools::use_data(WSJ, overwrite = TRUE) WSJ.centers = SpatialPointsDataFrame( rgeos::gCentroid(WSJ, byid = TRUE, id=WSJ@data$id), WSJ@data, match.ID = F) devtools::use_data(WSJ.centers, overwrite = TRUE) # Datamap.io ---- # https://elections.datamap.io/us/2016/09/23/electoral_college_forecast # http://bl.ocks.org/rogerfischer/15ef631812c56e3ef85af8191ef0de75 Datamap.io.tilegram <- readOGR('./data-raw/datamap', 'us_ec2016_state_hexagon') Datamap.io.tilegram@data %<>% dplyr::mutate(FIPS=stringr::str_extract(id,'..$')) Datamap.io.tilegram@data %<>% dplyr::left_join( usgazetteer::state.areas.2010 %>% dplyr::select(State, FIPS, USPS), by=c('FIPS'='FIPS')) devtools::use_data(Datamap.io.tilegram, overwrite = TRUE) Datamap.io.tilegram.centers = SpatialPointsDataFrame( rgeos::gCentroid(Datamap.io.tilegram, byid = TRUE, id=Datamap.io.tilegram@data$id), Datamap.io.tilegram@data, match.ID = F) devtools::use_data(Datamap.io.tilegram.centers, overwrite = TRUE)
source("load_data.R") plot3 <- function(data=NULL) { if(is.null(data)) data <- load_data() png("plot3.png", width=400, height=400) plot(data$Time, data$Sub_metering_1, type="l", col="black", xlab="", ylab="Energy sub metering") lines(data$Time, data$Sub_metering_2, col="red") lines(data$Time, data$Sub_metering_3, col="blue") legend("topright", col=c("black", "red", "blue"), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1) dev.off() }
/plot3.R
no_license
christophersushil/PowerConsumption
R
false
false
514
r
source("load_data.R") plot3 <- function(data=NULL) { if(is.null(data)) data <- load_data() png("plot3.png", width=400, height=400) plot(data$Time, data$Sub_metering_1, type="l", col="black", xlab="", ylab="Energy sub metering") lines(data$Time, data$Sub_metering_2, col="red") lines(data$Time, data$Sub_metering_3, col="blue") legend("topright", col=c("black", "red", "blue"), c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1) dev.off() }
#' @noRd graph2adj <- function(gR) { adj.matrix <- matrix(0, length(nodes(gR)), length(nodes(gR)) ) rownames(adj.matrix) <- nodes(gR) colnames(adj.matrix) <- nodes(gR) for (i in 1:length(nodes(gR))) { adj.matrix[nodes(gR)[i],adj(gR,nodes(gR)[i])[[1]]] <- 1 } return(adj.matrix) }
/R/graph2adj.R
no_license
bitmask/B-NEM
R
false
false
380
r
#' @noRd graph2adj <- function(gR) { adj.matrix <- matrix(0, length(nodes(gR)), length(nodes(gR)) ) rownames(adj.matrix) <- nodes(gR) colnames(adj.matrix) <- nodes(gR) for (i in 1:length(nodes(gR))) { adj.matrix[nodes(gR)[i],adj(gR,nodes(gR)[i])[[1]]] <- 1 } return(adj.matrix) }
## Matrix inversion is usually a costly computation and there may be some ## benefit to caching the inverse of a matrix rather than compute it repeatedly. ## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { x <<- y m <<- NULL } get <- function() x setinverse <- function(solve) m <<- solve getinverse <- function() m list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## 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, ...) { m <- x$getinverse() if(!is.null(m)) { message("getting cached data") return(m) } data <- x$get() m <- solve(data, ...) x$setinverse(m) m }
/cachematrix.R
no_license
D-soft/ProgrammingAssignment2
R
false
false
1,009
r
## Matrix inversion is usually a costly computation and there may be some ## benefit to caching the inverse of a matrix rather than compute it repeatedly. ## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { x <<- y m <<- NULL } get <- function() x setinverse <- function(solve) m <<- solve getinverse <- function() m list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## 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, ...) { m <- x$getinverse() if(!is.null(m)) { message("getting cached data") return(m) } data <- x$get() m <- solve(data, ...) x$setinverse(m) m }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/clustermap.R \name{draw.gap} \alias{draw.gap} \title{draw.gap} \usage{ draw.gap(clust = "col", B = 100, K = 6) } \arguments{ \item{clust}{String. Sets direction of clustering, default is "col" (column-wise)} \item{B}{Integer.} \item{K}{Integer} } \description{ Plots gap statistic }
/man/draw.gap.Rd
permissive
hjanime/clustermap
R
false
true
363
rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/clustermap.R \name{draw.gap} \alias{draw.gap} \title{draw.gap} \usage{ draw.gap(clust = "col", B = 100, K = 6) } \arguments{ \item{clust}{String. Sets direction of clustering, default is "col" (column-wise)} \item{B}{Integer.} \item{K}{Integer} } \description{ Plots gap statistic }
#' Optimal Transport Alignment #' #' This function aligns an ensemble of partitions with a reference partition by optimal transport. #' @param data -- a numeric matrix of horizontally stacked cluster labels. Each column contains cluster labels for all the data points according to one clustering result. The reference clustering result is put in the first column, and the first cluster must be labeled as 1. #' @return a list of alignment result. #' \item{distance}{Wasserstein distances between the reference partition and the others.} #' \item{numcls}{the number of clusters for each partition.} #' \item{statistics}{average tightness ratio, average coverage ratio, 1-average jaccard distance.} #' \item{cap}{cluster alignment and points based (CAP) separability.} #' \item{id}{switched labels.} #' \item{cps}{covering point set.} #' \item{match}{topological relationship statistics between the reference partition and the others.} #' \item{Weight}{weight matrix.} #' @examples #' data(sim1) #' # the number of clusters. #' C = 4 #' # calculate baseline method for comparison. #' kcl = kmeans(sim1$X,C) #' # align clustering results for convenience of comparison. #' compar = align(cbind(sim1$z,kcl$cluster)) #' @export align <- function(data){ if(!is.matrix(data)) stop('data must be a matrix\n') if(ncol(data)<2) stop('data must have at least 2 columns\n') if(min(data)<1) stop('the first cluster must be labeled as 1\n') nbs = ncol(data) res = ACPS(c(data)-1,nbs,1) cname = paste("C",1:res$numcls[1],sep="") rownames(res$statistics)=cname rownames(res$cap)=colnames(res$cap)=cname rownames(res$cps)=cname rownames(res$match)=cname colnames(res$weight)=cname weight=list() for(i in 1:(nbs-1)){ weight[[i]] = res$weight[(sum(res$numcls[2:(i+1)])-res$numcls[i+1]+1):sum(res$numcls[2:(i+1)]),] } res$weight = weight return(res) }
/R/align.R
no_license
cran/OTclust
R
false
false
1,868
r
#' Optimal Transport Alignment #' #' This function aligns an ensemble of partitions with a reference partition by optimal transport. #' @param data -- a numeric matrix of horizontally stacked cluster labels. Each column contains cluster labels for all the data points according to one clustering result. The reference clustering result is put in the first column, and the first cluster must be labeled as 1. #' @return a list of alignment result. #' \item{distance}{Wasserstein distances between the reference partition and the others.} #' \item{numcls}{the number of clusters for each partition.} #' \item{statistics}{average tightness ratio, average coverage ratio, 1-average jaccard distance.} #' \item{cap}{cluster alignment and points based (CAP) separability.} #' \item{id}{switched labels.} #' \item{cps}{covering point set.} #' \item{match}{topological relationship statistics between the reference partition and the others.} #' \item{Weight}{weight matrix.} #' @examples #' data(sim1) #' # the number of clusters. #' C = 4 #' # calculate baseline method for comparison. #' kcl = kmeans(sim1$X,C) #' # align clustering results for convenience of comparison. #' compar = align(cbind(sim1$z,kcl$cluster)) #' @export align <- function(data){ if(!is.matrix(data)) stop('data must be a matrix\n') if(ncol(data)<2) stop('data must have at least 2 columns\n') if(min(data)<1) stop('the first cluster must be labeled as 1\n') nbs = ncol(data) res = ACPS(c(data)-1,nbs,1) cname = paste("C",1:res$numcls[1],sep="") rownames(res$statistics)=cname rownames(res$cap)=colnames(res$cap)=cname rownames(res$cps)=cname rownames(res$match)=cname colnames(res$weight)=cname weight=list() for(i in 1:(nbs-1)){ weight[[i]] = res$weight[(sum(res$numcls[2:(i+1)])-res$numcls[i+1]+1):sum(res$numcls[2:(i+1)]),] } res$weight = weight return(res) }
datasplit<-function(AU,rat,seed) { set.seed(seed) t<-ncol(AU) ss = sample.split(AU[,c(t)], SplitRatio = rat) #write.csv(AU,'AU.csv') train = subset(AU, ss == TRUE) test = subset(AU, ss == FALSE) list1<-list("a"=train,"b"=test) return(list1) }
/datasplit.r
no_license
PhilipDocs/Imarticus-Project-1-and-2
R
false
false
268
r
datasplit<-function(AU,rat,seed) { set.seed(seed) t<-ncol(AU) ss = sample.split(AU[,c(t)], SplitRatio = rat) #write.csv(AU,'AU.csv') train = subset(AU, ss == TRUE) test = subset(AU, ss == FALSE) list1<-list("a"=train,"b"=test) return(list1) }
#' @title Create Field #' #' @description #' \code{create_field} This function will generate a new field associated with the user's account in the aWhere API. #' This is a one-time operation for each field. #' #' @details #' Fields are how you manage the locations for which you're tracking weather, agronomics, #' models, and progress over growing seasons in the aWhere API. By registering a field, you create a quick way #' to consistently reference locations across all of our APIs, and allow our modeling APIs #' to better operate and tune to the conditions and status of each specific field. #' #' Creating a field registers the location with the aWhere system, making it easier to reference #' and track your locations as well as run agronomics and models automatically. You #' only need to create a field once, after which you can reference the field by ID #' (you'll use this ID in most URI endpoints in the aWhere system). #' #' All spaces will be converted to underscores to conform with the requirements of the API. #' #' @param - field_id: an ID of your choosing (string) #' @param - latitude: the latitude of the field location in decimal format (double) #' @param - longitude: the longitude of the field location in decimal format (double) #' @param - farmid: an ID of your choosing for the farm to which this field belongs (string) #' @param - field_name: a name of the location (optional - string) #' @param - acres: the acres of the field (optional) #' @param - keyToUse: aWhere API key to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - secretToUse: aWhere API secret to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - tokenToUse: aWhere API token to use. For advanced use only. Most users will not need to use this parameter (optional) #' #' @return - printed text that informs if the query succeeded or not #' #' @references http://developer.awhere.com/api/reference/fields/create-field #' #' @import httr #' #' @examples #' \dontrun{ #' create_field(field_id = "field123",latitude = 39.8282,longitude = -98.5795,farm_id = "farmA",field_name = "Some Field Location",acres = 100) #' create_field(field_id = "field_test", latitude = 39.971906, longitude = -105.088773, farm_id = "Office") #' } #' @export create_field <- function(field_id ,latitude ,longitude ,farm_id ,field_name = "" ,acres = "" ,keyToUse = awhereEnv75247$uid ,secretToUse = awhereEnv75247$secret ,tokenToUse = awhereEnv75247$token) { ############################################################# #Checking Input Parameters checkCredentials(keyToUse,secretToUse,tokenToUse) checkValidLatLong(latitude,longitude) if (acres != "") { if (suppressWarnings(is.na(as.double(acres))) == TRUE) { warning('The entered acres Value is not valid. Please correct\n') return() } } field_id <- gsub(' ','_',field_id) farm_id <- gsub(' ','_',farm_id) ## Create Request url <- "https://api.awhere.com/v2/fields" postbody <- paste0('{"id":"', field_id, '",', '"centerPoint":{"latitude":', latitude, ',"longitude":', longitude, '}', ',"farmId":"', farm_id, '"') if(field_name != "") { postbody <- paste0(postbody, ',"name":"', field_name, '"') } if(acres != "") { postbody <- paste0(postbody, ',"acres":', acres) } postbody <- paste0(postbody, '}') doWeatherGet <- TRUE while (doWeatherGet == TRUE) { request <- httr::POST(url, body=postbody, httr::content_type('application/json'), httr::add_headers(Authorization = paste0("Bearer ", tokenToUse))) a <- suppressMessages(httr::content(request, as = "text")) doWeatherGet <- check_JSON(a,request) } cat(paste0('Operation Complete \n')) } #' @title Create Planting #' #' @description #' \code{create_planting} creates a planting in a field location in the aWhere platform for which you can request weather #' #' @details #' Fields are how you manage the locations for which you're tracking weather, agronomics, #' models, and progress over growing seasons. By registering a field, you create a quick way #' to consistently reference locations across all our APIs, and allow our modeling APIs #' to better operate and tune to the conditions and status of each specific field. A Planting #' is the record of a crop's season in a given field, and is where you tell the platform #' about what is planted there and when it was planted. #' #' Creating a planting will provide the aWhere platform the information needed to run models #' and more efficiently calculate agronomic values. You can also use these properties to record #' projections for the field, like yield or harvest date, to track the success of a field over #' the course of a growing season. Recording projected and actual yield and harvest date also helps #' aWhere tune the models for even greater accuracy. #' #' There can only be one active planting per field. You can create multiple plantings per field #' but only the most recent one will be considered the "current" one. Use this functionality to #' create historical records if you have them. #' #' When creating a planting, you must specify the crop and planting date. #' The crop must be an option from the Crops API; but there is also a short cut where if you don't #' know or want to use a specific crop ID, you can simply specify the crop name, such as "corn" or #' "wheat" and the the API will select the default for that category. #' #' This script creates a planting in a field location in the aWhere platform. By setting an Id you can retrieve the weather #' and agronomics for that location in all the other APIs. The planting ID corresponds to a planting within a field. #' #' @param - field_id: an ID of your choosing (string) #' @param - crop: cropId or crop name (string) #' @param - planting_date: date crop was planted in the field. Format as YYYY-MM-DD (string) #' @param - proj_yield_amount: amount of projected yield from planting (string) #' @param - proj_yield_units: units of projected yield (string - optional) #' @param - proj_harvest_date: projected harvest date at the start of the season. Format as YYYY-MM-DD (string - optional) #' @param - yield_amount: actual yield (string - optional) #' @param - yield_units: units of actual yield (string - optional) #' @param - harvest_date: actual harvest date at end of season. Format as YYYY-MM-DD (string - optional) #' @param - keyToUse: aWhere API key to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - secretToUse: aWhere API secret to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - tokenToUse: aWhere API token to use. For advanced use only. Most users will not need to use this parameter (optional) #' #' @return - system generated planting id along with a print text that informs if the query succeeded or not #' #' @references http://developer.awhere.com/api/reference/plantings/create #' #' @import httr #' #' @examples #' \dontrun{create_planting(field_id='field_test',crop='corn', planting_date='2015-10-25', proj_yield_amount='100', #' proj_yield_units='Bushels', proj_harvest_date='2016-02-01', yield_amount='110', #' yield_units='Bushels', harvest_date='2016-02-01') #' } #' @export create_planting <- function(field_id ,crop ,planting_date ,proj_yield_amount = "" ,proj_yield_units = "" ,proj_harvest_date = "" ,yield_amount = "" ,yield_units = "" ,harvest_date = "" ,keyToUse = awhereEnv75247$uid ,secretToUse = awhereEnv75247$secret ,tokenToUse = awhereEnv75247$token) { checkCredentials(keyToUse,secretToUse,tokenToUse) ## Error checking for valid entries if((proj_yield_amount != "" & proj_yield_units == "") || (proj_yield_amount == "" & proj_yield_units != "")) { stop("Must either have both projected yield amount and projected units, or neither") } if((yield_amount != "" & yield_units == "") | (yield_amount == "" & yield_units != "")) { stop("Must either have both yield amount and yield units, or neither") } checkValidField(field_id,keyToUse,secretToUse,tokenToUse) url <- paste0("https://api.awhere.com/v2/agronomics/fields/", field_id, "/plantings") postbody <- paste0('{', '"crop":"', crop, '",', '"plantingDate":"', planting_date, '"') if(proj_yield_amount != "" | proj_harvest_date != "") { postbody <- paste0(postbody, ',"projections":{') if(proj_yield_amount != "") { postbody <- paste0(postbody, '"yield":{', '"amount":', proj_yield_amount,',', '"units":"', proj_yield_units, '"}') if(proj_harvest_date != "") { postbody <- paste0(postbody, ",") } } if(proj_harvest_date != "") { postbody <- paste0(postbody, '"harvestDate":"', proj_harvest_date, '"', '}') } } if(yield_amount != "") { postbody <- paste0(postbody, ',"yield":{', '"amount":', yield_amount, ',', '"units":"', yield_units, '"', '},') } if(harvest_date != "") { postbody <- paste0(postbody, '"harvestDate":"', harvest_date, '"') } postbody <- paste0(postbody, '}') doWeatherGet <- TRUE while (doWeatherGet == TRUE) { request <- httr::POST(url, body=postbody, httr::content_type('application/json'), httr::add_headers(Authorization = paste0("Bearer ", tokenToUse))) a <- suppressMessages(httr::content(request)) doWeatherGet <- check_JSON(a,request) } cat(paste0('Operation Complete \n Planting ID: ', a$id),'\n') return(a$id) } #' @title Create Job #' #' @description #' \code{create_job} This API will register a batch job in the aWhere platform. #' #' @details #' Batch jobs allow you to execute many API calls in a single batch, which is much more efficient and faster than making hundreds #' or thousands of individual requests. When you create a batch, you define each endpoint you want to call, and then aWhere's platform #' steps through each internally and provides all the results at once. Any GET request from any of our Version-2 APIs can be included # in a batch. The batch job system treats each API request individually, which means you can easily identify which API request produced # which results. It is also fault-tolerant, so that if one request resulted in an error, all the others will execute normally. Note that # if you request a set of paged results, only the first page of results will be returned; be sure to use the limit and offset parameters # of that API to get all the results you need. #' #' Batch jobs are queued and executed in the order they are created, from across all customers using aWhere APIs. While many jobs can run #' concurrently, the rest are inserted into a queue and executed quite quickly. Use the Status and Results endpoint to monitor your job status #' and retrieve the results when complete. #' #' Important: This API will return a job ID which you must retain; there is not currently an API to list all jobs that you've created. #' Important: There is a limit of 10,000 requests per batch job. #' Note: The current conditions API cannot be included in batch jobs. #' #' @param - api_requests: a list of "verb endpoint" strings. This is the actual API request you're asking the Batch Jobs system to call. #' It must be a valid aWhere endpoint and is expressed as the HTTP verb, a space, and the relative URI. #' For example: "GET /v2/weather/fields/1234/observations" #' @param - titles: a vector of names for each individual request in api, which can aid in identifying each set of results within a batch. #' This need not be unique between all the jobs. #' @param - job_title: A name for the job, which can aid you in identifying the result set. #' @param - job_type: The type of job. Currently this system only supports the type "batch." #' @return - job_id: The Job ID. You will need this to retrieve the job status and results. #' @param - keyToUse: aWhere API key to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - secretToUse: aWhere API secret to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - tokenToUse: aWhere API token to use. For advanced use only. Most users will not need to use this parameter (optional) #' #' @references https://developer.awhere.com/api/reference/batch/create #' #' @import httr #' #' @examples #' \dontrun{create_job(c("GET /v2/weather/fields/field_test/observations", "GET /v2/weather/fields/aWhereOffice/observations"), c("farmA", "farmB"), "job_1")} #' @export create_job <- function(api_requests ,request_titles ,job_title ,job_type="batch" ,keyToUse = awhereEnv75247$uid ,secretToUse = awhereEnv75247$secret ,tokenToUse = awhereEnv75247$token) { ############################################################# #Checking Input Parameters checkCredentials(keyToUse,secretToUse,tokenToUse) job_title <- gsub(' ','_', job_title) ## Create Request url <- "https://api.awhere.com/v2/jobs" requests <- data.frame(title=request_titles, api=api_requests) postbody <- jsonlite::toJSON(list(title=job_title, type=job_type, requests=requests), auto_unbox=T) doWeatherGet <- TRUE while (doWeatherGet == TRUE) { request <- httr::POST(url, body=postbody, httr::content_type('application/json'), httr::add_headers(Authorization = paste0("Bearer ", tokenToUse))) doWeatherGet <- check_JSON(a,request) } cat(paste0('Operation Complete \n Job ID: ',a$jobId,'\n')) return(a$jobId) }
/R/create.R
permissive
colinloftin-awhere/aWhere-R-Library
R
false
false
14,550
r
#' @title Create Field #' #' @description #' \code{create_field} This function will generate a new field associated with the user's account in the aWhere API. #' This is a one-time operation for each field. #' #' @details #' Fields are how you manage the locations for which you're tracking weather, agronomics, #' models, and progress over growing seasons in the aWhere API. By registering a field, you create a quick way #' to consistently reference locations across all of our APIs, and allow our modeling APIs #' to better operate and tune to the conditions and status of each specific field. #' #' Creating a field registers the location with the aWhere system, making it easier to reference #' and track your locations as well as run agronomics and models automatically. You #' only need to create a field once, after which you can reference the field by ID #' (you'll use this ID in most URI endpoints in the aWhere system). #' #' All spaces will be converted to underscores to conform with the requirements of the API. #' #' @param - field_id: an ID of your choosing (string) #' @param - latitude: the latitude of the field location in decimal format (double) #' @param - longitude: the longitude of the field location in decimal format (double) #' @param - farmid: an ID of your choosing for the farm to which this field belongs (string) #' @param - field_name: a name of the location (optional - string) #' @param - acres: the acres of the field (optional) #' @param - keyToUse: aWhere API key to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - secretToUse: aWhere API secret to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - tokenToUse: aWhere API token to use. For advanced use only. Most users will not need to use this parameter (optional) #' #' @return - printed text that informs if the query succeeded or not #' #' @references http://developer.awhere.com/api/reference/fields/create-field #' #' @import httr #' #' @examples #' \dontrun{ #' create_field(field_id = "field123",latitude = 39.8282,longitude = -98.5795,farm_id = "farmA",field_name = "Some Field Location",acres = 100) #' create_field(field_id = "field_test", latitude = 39.971906, longitude = -105.088773, farm_id = "Office") #' } #' @export create_field <- function(field_id ,latitude ,longitude ,farm_id ,field_name = "" ,acres = "" ,keyToUse = awhereEnv75247$uid ,secretToUse = awhereEnv75247$secret ,tokenToUse = awhereEnv75247$token) { ############################################################# #Checking Input Parameters checkCredentials(keyToUse,secretToUse,tokenToUse) checkValidLatLong(latitude,longitude) if (acres != "") { if (suppressWarnings(is.na(as.double(acres))) == TRUE) { warning('The entered acres Value is not valid. Please correct\n') return() } } field_id <- gsub(' ','_',field_id) farm_id <- gsub(' ','_',farm_id) ## Create Request url <- "https://api.awhere.com/v2/fields" postbody <- paste0('{"id":"', field_id, '",', '"centerPoint":{"latitude":', latitude, ',"longitude":', longitude, '}', ',"farmId":"', farm_id, '"') if(field_name != "") { postbody <- paste0(postbody, ',"name":"', field_name, '"') } if(acres != "") { postbody <- paste0(postbody, ',"acres":', acres) } postbody <- paste0(postbody, '}') doWeatherGet <- TRUE while (doWeatherGet == TRUE) { request <- httr::POST(url, body=postbody, httr::content_type('application/json'), httr::add_headers(Authorization = paste0("Bearer ", tokenToUse))) a <- suppressMessages(httr::content(request, as = "text")) doWeatherGet <- check_JSON(a,request) } cat(paste0('Operation Complete \n')) } #' @title Create Planting #' #' @description #' \code{create_planting} creates a planting in a field location in the aWhere platform for which you can request weather #' #' @details #' Fields are how you manage the locations for which you're tracking weather, agronomics, #' models, and progress over growing seasons. By registering a field, you create a quick way #' to consistently reference locations across all our APIs, and allow our modeling APIs #' to better operate and tune to the conditions and status of each specific field. A Planting #' is the record of a crop's season in a given field, and is where you tell the platform #' about what is planted there and when it was planted. #' #' Creating a planting will provide the aWhere platform the information needed to run models #' and more efficiently calculate agronomic values. You can also use these properties to record #' projections for the field, like yield or harvest date, to track the success of a field over #' the course of a growing season. Recording projected and actual yield and harvest date also helps #' aWhere tune the models for even greater accuracy. #' #' There can only be one active planting per field. You can create multiple plantings per field #' but only the most recent one will be considered the "current" one. Use this functionality to #' create historical records if you have them. #' #' When creating a planting, you must specify the crop and planting date. #' The crop must be an option from the Crops API; but there is also a short cut where if you don't #' know or want to use a specific crop ID, you can simply specify the crop name, such as "corn" or #' "wheat" and the the API will select the default for that category. #' #' This script creates a planting in a field location in the aWhere platform. By setting an Id you can retrieve the weather #' and agronomics for that location in all the other APIs. The planting ID corresponds to a planting within a field. #' #' @param - field_id: an ID of your choosing (string) #' @param - crop: cropId or crop name (string) #' @param - planting_date: date crop was planted in the field. Format as YYYY-MM-DD (string) #' @param - proj_yield_amount: amount of projected yield from planting (string) #' @param - proj_yield_units: units of projected yield (string - optional) #' @param - proj_harvest_date: projected harvest date at the start of the season. Format as YYYY-MM-DD (string - optional) #' @param - yield_amount: actual yield (string - optional) #' @param - yield_units: units of actual yield (string - optional) #' @param - harvest_date: actual harvest date at end of season. Format as YYYY-MM-DD (string - optional) #' @param - keyToUse: aWhere API key to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - secretToUse: aWhere API secret to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - tokenToUse: aWhere API token to use. For advanced use only. Most users will not need to use this parameter (optional) #' #' @return - system generated planting id along with a print text that informs if the query succeeded or not #' #' @references http://developer.awhere.com/api/reference/plantings/create #' #' @import httr #' #' @examples #' \dontrun{create_planting(field_id='field_test',crop='corn', planting_date='2015-10-25', proj_yield_amount='100', #' proj_yield_units='Bushels', proj_harvest_date='2016-02-01', yield_amount='110', #' yield_units='Bushels', harvest_date='2016-02-01') #' } #' @export create_planting <- function(field_id ,crop ,planting_date ,proj_yield_amount = "" ,proj_yield_units = "" ,proj_harvest_date = "" ,yield_amount = "" ,yield_units = "" ,harvest_date = "" ,keyToUse = awhereEnv75247$uid ,secretToUse = awhereEnv75247$secret ,tokenToUse = awhereEnv75247$token) { checkCredentials(keyToUse,secretToUse,tokenToUse) ## Error checking for valid entries if((proj_yield_amount != "" & proj_yield_units == "") || (proj_yield_amount == "" & proj_yield_units != "")) { stop("Must either have both projected yield amount and projected units, or neither") } if((yield_amount != "" & yield_units == "") | (yield_amount == "" & yield_units != "")) { stop("Must either have both yield amount and yield units, or neither") } checkValidField(field_id,keyToUse,secretToUse,tokenToUse) url <- paste0("https://api.awhere.com/v2/agronomics/fields/", field_id, "/plantings") postbody <- paste0('{', '"crop":"', crop, '",', '"plantingDate":"', planting_date, '"') if(proj_yield_amount != "" | proj_harvest_date != "") { postbody <- paste0(postbody, ',"projections":{') if(proj_yield_amount != "") { postbody <- paste0(postbody, '"yield":{', '"amount":', proj_yield_amount,',', '"units":"', proj_yield_units, '"}') if(proj_harvest_date != "") { postbody <- paste0(postbody, ",") } } if(proj_harvest_date != "") { postbody <- paste0(postbody, '"harvestDate":"', proj_harvest_date, '"', '}') } } if(yield_amount != "") { postbody <- paste0(postbody, ',"yield":{', '"amount":', yield_amount, ',', '"units":"', yield_units, '"', '},') } if(harvest_date != "") { postbody <- paste0(postbody, '"harvestDate":"', harvest_date, '"') } postbody <- paste0(postbody, '}') doWeatherGet <- TRUE while (doWeatherGet == TRUE) { request <- httr::POST(url, body=postbody, httr::content_type('application/json'), httr::add_headers(Authorization = paste0("Bearer ", tokenToUse))) a <- suppressMessages(httr::content(request)) doWeatherGet <- check_JSON(a,request) } cat(paste0('Operation Complete \n Planting ID: ', a$id),'\n') return(a$id) } #' @title Create Job #' #' @description #' \code{create_job} This API will register a batch job in the aWhere platform. #' #' @details #' Batch jobs allow you to execute many API calls in a single batch, which is much more efficient and faster than making hundreds #' or thousands of individual requests. When you create a batch, you define each endpoint you want to call, and then aWhere's platform #' steps through each internally and provides all the results at once. Any GET request from any of our Version-2 APIs can be included # in a batch. The batch job system treats each API request individually, which means you can easily identify which API request produced # which results. It is also fault-tolerant, so that if one request resulted in an error, all the others will execute normally. Note that # if you request a set of paged results, only the first page of results will be returned; be sure to use the limit and offset parameters # of that API to get all the results you need. #' #' Batch jobs are queued and executed in the order they are created, from across all customers using aWhere APIs. While many jobs can run #' concurrently, the rest are inserted into a queue and executed quite quickly. Use the Status and Results endpoint to monitor your job status #' and retrieve the results when complete. #' #' Important: This API will return a job ID which you must retain; there is not currently an API to list all jobs that you've created. #' Important: There is a limit of 10,000 requests per batch job. #' Note: The current conditions API cannot be included in batch jobs. #' #' @param - api_requests: a list of "verb endpoint" strings. This is the actual API request you're asking the Batch Jobs system to call. #' It must be a valid aWhere endpoint and is expressed as the HTTP verb, a space, and the relative URI. #' For example: "GET /v2/weather/fields/1234/observations" #' @param - titles: a vector of names for each individual request in api, which can aid in identifying each set of results within a batch. #' This need not be unique between all the jobs. #' @param - job_title: A name for the job, which can aid you in identifying the result set. #' @param - job_type: The type of job. Currently this system only supports the type "batch." #' @return - job_id: The Job ID. You will need this to retrieve the job status and results. #' @param - keyToUse: aWhere API key to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - secretToUse: aWhere API secret to use. For advanced use only. Most users will not need to use this parameter (optional) #' @param - tokenToUse: aWhere API token to use. For advanced use only. Most users will not need to use this parameter (optional) #' #' @references https://developer.awhere.com/api/reference/batch/create #' #' @import httr #' #' @examples #' \dontrun{create_job(c("GET /v2/weather/fields/field_test/observations", "GET /v2/weather/fields/aWhereOffice/observations"), c("farmA", "farmB"), "job_1")} #' @export create_job <- function(api_requests ,request_titles ,job_title ,job_type="batch" ,keyToUse = awhereEnv75247$uid ,secretToUse = awhereEnv75247$secret ,tokenToUse = awhereEnv75247$token) { ############################################################# #Checking Input Parameters checkCredentials(keyToUse,secretToUse,tokenToUse) job_title <- gsub(' ','_', job_title) ## Create Request url <- "https://api.awhere.com/v2/jobs" requests <- data.frame(title=request_titles, api=api_requests) postbody <- jsonlite::toJSON(list(title=job_title, type=job_type, requests=requests), auto_unbox=T) doWeatherGet <- TRUE while (doWeatherGet == TRUE) { request <- httr::POST(url, body=postbody, httr::content_type('application/json'), httr::add_headers(Authorization = paste0("Bearer ", tokenToUse))) doWeatherGet <- check_JSON(a,request) } cat(paste0('Operation Complete \n Job ID: ',a$jobId,'\n')) return(a$jobId) }
#' Compute number of neighbors out of 4 neighboring cells #' #' This function is based on the simecol::neighbors function. #' @inherit simecol::neighbors #' #' @return a matrix #' @export fourneighbors <- function(landscape, state = 1, bounds = 1) { neighborhood <- matrix( c(0, 1, 0, 1, 0, 1, 0, 1, 0), nrow = 3) nb_neighbors <- simecol::neighbors( x = landscape, state = state, wdist = neighborhood, bounds = bounds) }
/R/ca_transitions_functions.R
permissive
alaindanet/indirect_facilitation_model
R
false
false
465
r
#' Compute number of neighbors out of 4 neighboring cells #' #' This function is based on the simecol::neighbors function. #' @inherit simecol::neighbors #' #' @return a matrix #' @export fourneighbors <- function(landscape, state = 1, bounds = 1) { neighborhood <- matrix( c(0, 1, 0, 1, 0, 1, 0, 1, 0), nrow = 3) nb_neighbors <- simecol::neighbors( x = landscape, state = state, wdist = neighborhood, bounds = bounds) }