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
|
---|---|---|---|---|---|---|---|---|---|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tickdb-packages.R
\docType{package}
\name{tickdb-package}
\alias{tickdb-package}
\title{tickdb}
\description{
Functions to access the Liquid Capital Tick Database
}
\author{
David Bellot \email{dbellot@liquidcapital.com}
}
|
/tickdb/man/tickdb-package.Rd
|
no_license
|
sheryllan/tickdb
|
R
| false | true | 301 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tickdb-packages.R
\docType{package}
\name{tickdb-package}
\alias{tickdb-package}
\title{tickdb}
\description{
Functions to access the Liquid Capital Tick Database
}
\author{
David Bellot \email{dbellot@liquidcapital.com}
}
|
#' Function to return the team data
#'
#' Returns data on the fantasy football team
#'
#' @param GameID The number assigned
#' to the annual fantasy footbal compettion. Games should
#' not be confused with a weekly NFL football game. See
#' also the GetGameID() function.
#'
#' @param LeagueID The ID number representing the specific
#' fantasy football league.
#'
#' @param team The team ID, possible values
#' are based on the number of teams in the league, ypically
#' ranging from 1-10.
#'
#' @param DataType The type of data desired for the team.
#' Possible values are stats, standings, or matchups.
#'
#' @param sig See also the GetSig() function
#' @return List. Fiels will vary by the datatype used.
#' @import httr
#'
GetTeamData<-function(GameID,LeagueID,team=1,DataType="stats",sig){
base <- "http://fantasysports.yahooapis.com/fantasy/v2/team/"
formatting <- switch(DataType,
stats = "/stats?format=json",
standings = "/standings?format=json",
matchups = "/matchups?format=json")
x <- paste(GameID,".l.",LeagueID,".t.",team,sep="")
y <- paste(base,x,formatting,sep="")
z <- httr::GET(y,sig)
}
|
/R/GetTeamData.R
|
no_license
|
kuhnrl30/Touchdown
|
R
| false | false | 1,155 |
r
|
#' Function to return the team data
#'
#' Returns data on the fantasy football team
#'
#' @param GameID The number assigned
#' to the annual fantasy footbal compettion. Games should
#' not be confused with a weekly NFL football game. See
#' also the GetGameID() function.
#'
#' @param LeagueID The ID number representing the specific
#' fantasy football league.
#'
#' @param team The team ID, possible values
#' are based on the number of teams in the league, ypically
#' ranging from 1-10.
#'
#' @param DataType The type of data desired for the team.
#' Possible values are stats, standings, or matchups.
#'
#' @param sig See also the GetSig() function
#' @return List. Fiels will vary by the datatype used.
#' @import httr
#'
GetTeamData<-function(GameID,LeagueID,team=1,DataType="stats",sig){
base <- "http://fantasysports.yahooapis.com/fantasy/v2/team/"
formatting <- switch(DataType,
stats = "/stats?format=json",
standings = "/standings?format=json",
matchups = "/matchups?format=json")
x <- paste(GameID,".l.",LeagueID,".t.",team,sep="")
y <- paste(base,x,formatting,sep="")
z <- httr::GET(y,sig)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plotLollipops.R
\name{plotLollipops.GrowthData}
\alias{plotLollipops.GrowthData}
\title{plot lollipops for fits to molt increment data}
\usage{
plotLollipops.GrowthData(
mdfr,
type = "zscores",
extreme = 3,
dw = 1,
size = 0.1,
xlab = "pre-molt size",
ylab = type
)
}
\arguments{
\item{mdfr}{\itemize{
\item input dataframe from \code{\link[=extractMDFR.Fits.GrowthData]{extractMDFR.Fits.GrowthData()}}
}}
\item{type}{\itemize{
\item type of value to plot (e.g., "zscores")
}}
\item{extreme}{\itemize{
\item criteria for extreme values
}}
\item{dw}{\itemize{
\item dodge width (x-axis units)
}}
\item{size}{\itemize{
\item line size for lollipop stems
}}
\item{xlab}{\itemize{
\item x-axis label
}}
\item{ylab}{\itemize{
\item y-axis label
}}
}
\value{
ggplot2 plot object
}
\description{
function to plot lollipops for fits to molt increment data.
}
\details{
Plots \code{type} as lollipops against pre-molt size.
}
|
/man/plotLollipops.GrowthData.Rd
|
permissive
|
wStockhausen/rCompTCMs
|
R
| false | true | 1,014 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plotLollipops.R
\name{plotLollipops.GrowthData}
\alias{plotLollipops.GrowthData}
\title{plot lollipops for fits to molt increment data}
\usage{
plotLollipops.GrowthData(
mdfr,
type = "zscores",
extreme = 3,
dw = 1,
size = 0.1,
xlab = "pre-molt size",
ylab = type
)
}
\arguments{
\item{mdfr}{\itemize{
\item input dataframe from \code{\link[=extractMDFR.Fits.GrowthData]{extractMDFR.Fits.GrowthData()}}
}}
\item{type}{\itemize{
\item type of value to plot (e.g., "zscores")
}}
\item{extreme}{\itemize{
\item criteria for extreme values
}}
\item{dw}{\itemize{
\item dodge width (x-axis units)
}}
\item{size}{\itemize{
\item line size for lollipop stems
}}
\item{xlab}{\itemize{
\item x-axis label
}}
\item{ylab}{\itemize{
\item y-axis label
}}
}
\value{
ggplot2 plot object
}
\description{
function to plot lollipops for fits to molt increment data.
}
\details{
Plots \code{type} as lollipops against pre-molt size.
}
|
#figures and tests from ANOVA lecture
#iris example, from first lecture
#
library(ggplot2)
#point plot####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#bar chart with error bars ####
require(Rmisc)
function_output <- summarySE(iris, measurevar="Sepal.Length", groupvars =
c("Species"))
ggplot(function_output, aes(x=Species, y=Sepal.Length)) +
geom_col(aes(fill=Species), size = 3) +
geom_errorbar(aes(ymin=Sepal.Length-ci, ymax=Sepal.Length+ci), size=1.5) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#boxplot####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_boxplot(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#stacked histogram####
ggplot(iris, aes(Sepal.Length)) +
geom_histogram(aes(fill=Species), size=3) +
xlab("Sepal Length (cm)")+
ylab("Frequency")+
ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#facet####
ggplot(iris, aes(Sepal.Length)) +
geom_histogram(aes(fill=Species), size=3) +
xlab("Sepal Length (cm)")+
ylab("Frequency")+
ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
legend.position = "bottom",
plot.title = element_text(hjust = 0.5, face="bold", size=32))+
facet_wrap(~Species, ncol = 1)
#point plot with means####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_hline(aes(yintercept=mean(iris$Sepal.Length)), size = 2, color = "orange")
#point plot with means for each group####
#make extra column for output and rename here
function_output$Sepal.Length <- function_output$mean
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_errorbar(aes(ymin=Sepal.Length, ymax=Sepal.Length), size=1.5,
data = function_output, color = "black")
#combine these two ####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_errorbar(aes(ymin=Sepal.Length, ymax=Sepal.Length), size=1.5,
data = function_output, color = "black") +
geom_hline(aes(yintercept=mean(iris$Sepal.Length)), size = 2, color = "orange")
#show null hypothesis
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_errorbar(aes(ymin=Sepal.Length, ymax=Sepal.Length), size=1.5,
data = function_output, color = "black") +
geom_hline(aes(yintercept=mean(iris$Sepal.Length)), size = 2, color = "orange") +
geom_errorbar(aes(ymin=mean(iris$Sepal.Length), ymax=mean(iris$Sepal.Length)), size=1.5, color = "purple", linetype = 3)
#p value via simulation ####
#get overall variance and mean estimate
variance_estimate <- sum((function_output$N -1) * (function_output$sd)^2)/(sum(function_output$N)-length(function_output$N))
mean_sepal <- mean(iris$Sepal.Length)
#sample
ratio <- data.frame(rep = 1:10000, mse = rep(NA,10000),
msg = rep(NA,10000), ratio = rep(NA,10000))
for(i in 1:10000){
setosa <- rnorm(50, mean_sepal, sd= sqrt(variance_estimate))
versicolor <- rnorm(50, mean_sepal, sd= sqrt(variance_estimate))
virginica <- rnorm(50, mean_sepal, sd= sqrt(variance_estimate))
mean_overall <- mean(c(setosa, versicolor, virginica))
ratio$mse[i] <- (49 * var(setosa) + 49 * var(versicolor) + 49 * var(virginica))/(150 - 3)
ratio$msg[i] <- (50 * (mean(setosa)-mean_overall)^2 +
50 * (mean(versicolor)-mean_overall)^2 +
50 * (mean (virginica)-mean_overall)^2)/2
ratio$ratio[i] <- ratio$msg[i]/ratio$mse[i]
}
summary(lm(Sepal.Length~Species, iris))$fstatistic[1]
ggplot(ratio, aes(ratio)) +
geom_histogram(aes(y=..count../sum(..count..)), fill = "orange", bins = 15) +
ggtitle("Ratio under null hypothesis") +
ylab("Probability") +
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#with f####
#notice i specify degrees of freedom for numerator (df1) and denomitor (df2)
ggplot(ratio, aes(ratio)) +
geom_histogram(aes(y=..count../sum(..count..)), fill = "orange",
breaks = seq(0,15,1)) +
stat_function(fun = df, args = list(df1 =2, df2 = 147),size = 3, color = "green") +
ggtitle("Signal under null hypothesis") +
ggtitle("Ratio under null hypothesis") +
ylab("Probability") +
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#build model####
iris_anova <- lm(Sepal.Length~Species, iris)
#it creates an object you can manipulate
#check assumptions####
par(mfrow = c(2,2))
plot(iris_anova)
#look at outputs using p-values
summary(iris_anova)
#you can get specific group means by builidng model without intercept
iris_anova_no_intercept <- lm(Sepal.Length~Species - 1, iris)
summary(iris_anova_no_intercept)
#but don't do this in general (R and F stats will be skewed!)
#just use to get group coefficients if needed
#note relationship between model coefficients here as well
#Anova command from car package is needed to give overall group p-value
library(car)
Anova(iris_anova, type = "III")
#since our overall anova was significant, we need to carry out multiple comparisons
#to see what groups are driving the difference
#multcomp
library(multcomp)
#where's the almost difference? use Tukey's HSD for all pairs
library(multcomp)
compare_cont_tukey <- glht(iris_anova, linfct = mcp(Species = "Tukey"))
summary(compare_cont_tukey)
#or you can specify what you want to consider
compare_virginica_only <- glht(iris_anova, linfct = mcp(Species =
c("virginica - versicolor = 0",
"virginica - setosa = 0")))
#remember to control for error rates!
summary(compare_virginica_only, test=adjusted("holm"))
#other options
summary(compare_virginica_only, test=adjusted("fdr"))
#we can "find" significance more easily, but you need to justify why you did this
#we can "find" significance more easily, but you need to justify why you did this
#using set contrasts####
#are versicolor and virginica different from setosa
contr <- rbind("setosa - virginica - setosa" = c(-1,.5,.5))
summary(glht(iris_anova, linfct = mcp(Species = contr)))
summary(iris_anova) # this appears to be right
#orthogonal
contr <- rbind("setosa - virginica - setosa" = c(-1,.5,.5),
"virginica - setosa" = c(0,-1,1))
summary(glht(iris_anova, linfct = mcp(Species = contr)))
summary(iris_anova) # this appears to be right
#R2####
#R2 explains how much variation is explained by our model (groups in this instance)
summary(iris_anova)
#or
summary(iris_anova)$r.squared
#note you can have a low p-value model that also explains only small amount of
#variation in the data
#graphical comparison####
#add comparison portion to fuction_output
function_output$comparison <- "NA"
#enter by hand for small groups by comparing function_output means with multcomp
#output (usually tukey)
function_output
summary(compare_cont_tukey)
#all different here, so
function_output$comparison <- letters[1:3]
ggplot(function_output, aes(x=Species, y=Sepal.Length)) +
geom_point(aes(fill=Species), size = 3) +
geom_errorbar(aes(ymin=Sepal.Length-ci, ymax=Sepal.Length+ci), size=1.5) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))+
#offset from mean by hand
geom_text(aes(x = Species, y = mean + .35, label = comparison), size = 28)
#another option for labelling if you are doing tukey is to automate (easy for more comparisons)
post_hoc_spray_cld <- cld(compare_cont_tukey)
#fortify to make a dataframe
post_hoc_spray_cld_fortify <- fortify(post_hoc_spray_cld)
#rename lhs to group and then merge (rename to whatever you used as groupvar in
#summary SE)
names(post_hoc_spray_cld_fortify)[names(post_hoc_spray_cld_fortify) == "lhs"] <- "Species"
function_output <- merge(function_output, post_hoc_spray_cld_fortify)
#plot
ggplot(function_output, aes(x=Species, y=Sepal.Length)) +
geom_point(aes(fill=Species), size = 3) +
geom_errorbar(aes(ymin=Sepal.Length-ci, ymax=Sepal.Length+ci), size=1.5) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))+
#offset from mean by hand
geom_text(aes(x = Species, y = Sepal.Length + .35, label = letters), size = 28)
#kruskal.wallis####
kruskal.test(Sepal.Length ~ Species, data = iris)
pairwise.wilcox.test(iris$Sepal.Length,
iris$Species,
p.adjust.method="holm")
#building to bootstrap options####
library(WRS2)
#first, just using trimmed means, which help
t1way(Sepal.Length~Species, iris)
contrasts <- lincon(Sepal.Length~Species, iris)
contrasts
#if we don't trim mean, we use Welch's approximation for ANOVA
t1way(Sepal.Length~Species, iris, tr = 0)
contrasts <- lincon(Sepal.Length~Species, iris, tr = 0)
contrasts
#to actually use the bootstrap version
t1waybt(Sepal.Length~Species, iris)
bootstrap_post_hoc <- mcppb20(Sepal.Length~Species, iris)
#use p.adjust to correct for FWER
p.adjust(as.numeric(bootstrap_post_hoc$comp[,6]), "holm")
|
/lecture_files/7_ANOVAs.R
|
no_license
|
kkruegerhirt/CUNY-BioStats
|
R
| false | false | 14,724 |
r
|
#figures and tests from ANOVA lecture
#iris example, from first lecture
#
library(ggplot2)
#point plot####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#bar chart with error bars ####
require(Rmisc)
function_output <- summarySE(iris, measurevar="Sepal.Length", groupvars =
c("Species"))
ggplot(function_output, aes(x=Species, y=Sepal.Length)) +
geom_col(aes(fill=Species), size = 3) +
geom_errorbar(aes(ymin=Sepal.Length-ci, ymax=Sepal.Length+ci), size=1.5) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#boxplot####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_boxplot(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#stacked histogram####
ggplot(iris, aes(Sepal.Length)) +
geom_histogram(aes(fill=Species), size=3) +
xlab("Sepal Length (cm)")+
ylab("Frequency")+
ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#facet####
ggplot(iris, aes(Sepal.Length)) +
geom_histogram(aes(fill=Species), size=3) +
xlab("Sepal Length (cm)")+
ylab("Frequency")+
ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
legend.position = "bottom",
plot.title = element_text(hjust = 0.5, face="bold", size=32))+
facet_wrap(~Species, ncol = 1)
#point plot with means####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_hline(aes(yintercept=mean(iris$Sepal.Length)), size = 2, color = "orange")
#point plot with means for each group####
#make extra column for output and rename here
function_output$Sepal.Length <- function_output$mean
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_errorbar(aes(ymin=Sepal.Length, ymax=Sepal.Length), size=1.5,
data = function_output, color = "black")
#combine these two ####
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_errorbar(aes(ymin=Sepal.Length, ymax=Sepal.Length), size=1.5,
data = function_output, color = "black") +
geom_hline(aes(yintercept=mean(iris$Sepal.Length)), size = 2, color = "orange")
#show null hypothesis
ggplot(iris, aes(Species,Sepal.Length)) +
geom_point(aes(colour=Species), size = 3) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32)) +
geom_errorbar(aes(ymin=Sepal.Length, ymax=Sepal.Length), size=1.5,
data = function_output, color = "black") +
geom_hline(aes(yintercept=mean(iris$Sepal.Length)), size = 2, color = "orange") +
geom_errorbar(aes(ymin=mean(iris$Sepal.Length), ymax=mean(iris$Sepal.Length)), size=1.5, color = "purple", linetype = 3)
#p value via simulation ####
#get overall variance and mean estimate
variance_estimate <- sum((function_output$N -1) * (function_output$sd)^2)/(sum(function_output$N)-length(function_output$N))
mean_sepal <- mean(iris$Sepal.Length)
#sample
ratio <- data.frame(rep = 1:10000, mse = rep(NA,10000),
msg = rep(NA,10000), ratio = rep(NA,10000))
for(i in 1:10000){
setosa <- rnorm(50, mean_sepal, sd= sqrt(variance_estimate))
versicolor <- rnorm(50, mean_sepal, sd= sqrt(variance_estimate))
virginica <- rnorm(50, mean_sepal, sd= sqrt(variance_estimate))
mean_overall <- mean(c(setosa, versicolor, virginica))
ratio$mse[i] <- (49 * var(setosa) + 49 * var(versicolor) + 49 * var(virginica))/(150 - 3)
ratio$msg[i] <- (50 * (mean(setosa)-mean_overall)^2 +
50 * (mean(versicolor)-mean_overall)^2 +
50 * (mean (virginica)-mean_overall)^2)/2
ratio$ratio[i] <- ratio$msg[i]/ratio$mse[i]
}
summary(lm(Sepal.Length~Species, iris))$fstatistic[1]
ggplot(ratio, aes(ratio)) +
geom_histogram(aes(y=..count../sum(..count..)), fill = "orange", bins = 15) +
ggtitle("Ratio under null hypothesis") +
ylab("Probability") +
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#with f####
#notice i specify degrees of freedom for numerator (df1) and denomitor (df2)
ggplot(ratio, aes(ratio)) +
geom_histogram(aes(y=..count../sum(..count..)), fill = "orange",
breaks = seq(0,15,1)) +
stat_function(fun = df, args = list(df1 =2, df2 = 147),size = 3, color = "green") +
ggtitle("Signal under null hypothesis") +
ggtitle("Ratio under null hypothesis") +
ylab("Probability") +
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))
#build model####
iris_anova <- lm(Sepal.Length~Species, iris)
#it creates an object you can manipulate
#check assumptions####
par(mfrow = c(2,2))
plot(iris_anova)
#look at outputs using p-values
summary(iris_anova)
#you can get specific group means by builidng model without intercept
iris_anova_no_intercept <- lm(Sepal.Length~Species - 1, iris)
summary(iris_anova_no_intercept)
#but don't do this in general (R and F stats will be skewed!)
#just use to get group coefficients if needed
#note relationship between model coefficients here as well
#Anova command from car package is needed to give overall group p-value
library(car)
Anova(iris_anova, type = "III")
#since our overall anova was significant, we need to carry out multiple comparisons
#to see what groups are driving the difference
#multcomp
library(multcomp)
#where's the almost difference? use Tukey's HSD for all pairs
library(multcomp)
compare_cont_tukey <- glht(iris_anova, linfct = mcp(Species = "Tukey"))
summary(compare_cont_tukey)
#or you can specify what you want to consider
compare_virginica_only <- glht(iris_anova, linfct = mcp(Species =
c("virginica - versicolor = 0",
"virginica - setosa = 0")))
#remember to control for error rates!
summary(compare_virginica_only, test=adjusted("holm"))
#other options
summary(compare_virginica_only, test=adjusted("fdr"))
#we can "find" significance more easily, but you need to justify why you did this
#we can "find" significance more easily, but you need to justify why you did this
#using set contrasts####
#are versicolor and virginica different from setosa
contr <- rbind("setosa - virginica - setosa" = c(-1,.5,.5))
summary(glht(iris_anova, linfct = mcp(Species = contr)))
summary(iris_anova) # this appears to be right
#orthogonal
contr <- rbind("setosa - virginica - setosa" = c(-1,.5,.5),
"virginica - setosa" = c(0,-1,1))
summary(glht(iris_anova, linfct = mcp(Species = contr)))
summary(iris_anova) # this appears to be right
#R2####
#R2 explains how much variation is explained by our model (groups in this instance)
summary(iris_anova)
#or
summary(iris_anova)$r.squared
#note you can have a low p-value model that also explains only small amount of
#variation in the data
#graphical comparison####
#add comparison portion to fuction_output
function_output$comparison <- "NA"
#enter by hand for small groups by comparing function_output means with multcomp
#output (usually tukey)
function_output
summary(compare_cont_tukey)
#all different here, so
function_output$comparison <- letters[1:3]
ggplot(function_output, aes(x=Species, y=Sepal.Length)) +
geom_point(aes(fill=Species), size = 3) +
geom_errorbar(aes(ymin=Sepal.Length-ci, ymax=Sepal.Length+ci), size=1.5) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))+
#offset from mean by hand
geom_text(aes(x = Species, y = mean + .35, label = comparison), size = 28)
#another option for labelling if you are doing tukey is to automate (easy for more comparisons)
post_hoc_spray_cld <- cld(compare_cont_tukey)
#fortify to make a dataframe
post_hoc_spray_cld_fortify <- fortify(post_hoc_spray_cld)
#rename lhs to group and then merge (rename to whatever you used as groupvar in
#summary SE)
names(post_hoc_spray_cld_fortify)[names(post_hoc_spray_cld_fortify) == "lhs"] <- "Species"
function_output <- merge(function_output, post_hoc_spray_cld_fortify)
#plot
ggplot(function_output, aes(x=Species, y=Sepal.Length)) +
geom_point(aes(fill=Species), size = 3) +
geom_errorbar(aes(ymin=Sepal.Length-ci, ymax=Sepal.Length+ci), size=1.5) +
ylab("Sepal Length (cm)")+ggtitle("Sepal Length of various iris species")+
theme(axis.title.x = element_text(face="bold", size=28),
axis.title.y = element_text(face="bold", size=28),
axis.text.y = element_text(size=20),
axis.text.x = element_text(size=20),
legend.text =element_text(size=20),
legend.title = element_text(size=20, face="bold"),
plot.title = element_text(hjust = 0.5, face="bold", size=32))+
#offset from mean by hand
geom_text(aes(x = Species, y = Sepal.Length + .35, label = letters), size = 28)
#kruskal.wallis####
kruskal.test(Sepal.Length ~ Species, data = iris)
pairwise.wilcox.test(iris$Sepal.Length,
iris$Species,
p.adjust.method="holm")
#building to bootstrap options####
library(WRS2)
#first, just using trimmed means, which help
t1way(Sepal.Length~Species, iris)
contrasts <- lincon(Sepal.Length~Species, iris)
contrasts
#if we don't trim mean, we use Welch's approximation for ANOVA
t1way(Sepal.Length~Species, iris, tr = 0)
contrasts <- lincon(Sepal.Length~Species, iris, tr = 0)
contrasts
#to actually use the bootstrap version
t1waybt(Sepal.Length~Species, iris)
bootstrap_post_hoc <- mcppb20(Sepal.Length~Species, iris)
#use p.adjust to correct for FWER
p.adjust(as.numeric(bootstrap_post_hoc$comp[,6]), "holm")
|
## The following pair of functions aim to cache the inverse of a matrix
## This function creates a special 'matrix' object, which is a list containing
## functions to: set the matrix, get the matrix, set the inverse the matrix and
## get the inverse of the matrix.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function(z) inv <<- z
getinv <- function() inv
list(set = set, get = get, setinv = setinv, getinv = getinv)
}
## This function calculates the inverse of a matrix.
## The function first checks to see if the inverse of the matrix has already
## been calculated. If so, it retrieves the object from the cache. Otherwise,
## this function does the inversion and sets the object in the cache.
cacheSolve <- function(x, ...) {
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
|
/ProgrammingAssignment2/cachematrix.R
|
no_license
|
rouille/CourseraDataScienceJHU
|
R
| false | false | 1,056 |
r
|
## The following pair of functions aim to cache the inverse of a matrix
## This function creates a special 'matrix' object, which is a list containing
## functions to: set the matrix, get the matrix, set the inverse the matrix and
## get the inverse of the matrix.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function(z) inv <<- z
getinv <- function() inv
list(set = set, get = get, setinv = setinv, getinv = getinv)
}
## This function calculates the inverse of a matrix.
## The function first checks to see if the inverse of the matrix has already
## been calculated. If so, it retrieves the object from the cache. Otherwise,
## this function does the inversion and sets the object in the cache.
cacheSolve <- function(x, ...) {
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
|
# File name: 04a_plot_marg_fitted_xp09.R
# Online archive: gitlab
# Authors: Brice Beffara & Amélie Bret
# Tue Jun 26 11:57:07 2018 ------------------------------
# Contact: brice.beffara@slowpen.science amelie.bret@univ-grenoble-alpes.fr http://slowpen.science
#
# This R script was used to create the marginal plots from brms models
# corresponding to the 10th experiment of Amelie Bret's doctoral work
#
# This R script plots marginal effect corresponding to the association
# of RWA with grebles' ratings in all combinations of the other indepentdent variables :
# usvalence : positive (0.5) vs. negative (-0.5)
# and load : load (0.5) vs. no load (-0.5)
#
# This program is believed to be free of errors, but it comes with no guarantee!
# The user bears all responsibility for interpreting the results.
#
# This preambule is largely inspired by John K. Kruschke's work at https://osf.io/wp2ry/
#
### To run this program, please do the following:
### 1. Install the general-purpose programming language R from
### http://www.r-project.org/
### Install the version of R appropriate for your computer's operating
### system (Windows, MacOS, or Linux).
### 2. Install the R editor, RStudio, from
### http://rstudio.org/
### This editor is not necessary, but highly recommended.
### 3. After the above actions are accomplished, this program should
### run as-is in R. You may "source" it to run the whole thing at once,
### or, preferably, run lines consecutively from the beginning.
################################################################################
# Loading packages needed (and installing if necessary) for this part
if (!require("pacman")) install.packages("pacman")
p_load(ggplot2, # main package for plots
colorRamps, # to add color palettes
ggpubr, # to combine plots
extrafontdb, # to get more available fonts for plots
hrbrthemes, # for ggplot2 theme
extrafont,
ggExtra,
install = TRUE,
update = getOption("pac_update"),
character.only = FALSE)
#------------------------------------------------------------------------------------
# First we determine all the possible combinations of modalities
# between the two categorical independent variables :
# "load" and "usvalence"
#------------------------------------------------------------------------------------
# !!orginally!! conditioned stimuli with !!negative!! valence
cond_on <- data.frame(load = -0.5, usvalence = -0.5,
cond__ = "noload_negative")
# !!orginally!! conditioned stimuli with !!positive!! valence
cond_op <- data.frame(load = -0.5, usvalence = 0.5,
cond__ = "noload_positive")
# !!spread!! conditionned stimuli with !!negative!! valence
cond_sn <- data.frame(load = 0.5, usvalence = -0.5,
cond__ = "load_negative")
# !!spread!! conditionned stimuli with !!positive!! valence
cond_sp <- data.frame(load = 0.5, usvalence = 0.5,
cond__ = "load_positive")
#------------------------------------------------------------------------------------
# We then select the marginal effects of RWA from the model
# for each combination of modalities
#------------------------------------------------------------------------------------
# !!orginally!! conditioned stimuli with !!negative!! valence
marg_on <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_on, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
# !!orginally!! conditioned stimuli with !!positive!! valence
marg_op <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_op, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
# !!spread!! conditionned stimuli with !!negative!! valence
marg_sn <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_sn, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
# !!spread!! conditionned stimuli with !!positive!! valence
marg_sp <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_sp, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
#------------------------------------------------------------------------------------
# Now we can plot marginal effects for each combination of conditions...
#------------------------------------------------------------------------------------
# load fonts and themes
hrbrthemes::import_roboto_condensed()
loadfonts()
# !!orginally!! conditioned stimuli with !!negative!! valence
marg_plot_on = plot(marg_on, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Musique neutre pendant le contre-conditionnement positif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
# !!orginally!! conditioned stimuli with !!positive!! valence
marg_plot_op = plot(marg_op, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Musique neutre pendant le contre-conditionnement négatif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
# !!spread!! conditionned stimuli with !!negative!! valence
marg_plot_sn = plot(marg_sn, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Charge cognitive pendant le contre-conditionnement positif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
# !!spread!! conditionned stimuli with !!positive!! valence
marg_plot_sp = plot(marg_sp, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Charge cognitive pendant le contre-conditionnement négatif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
#------------------------------------------------------------------------------------
# ...and combine plots together
#------------------------------------------------------------------------------------
# Combine plot
marg_all <- ggarrange(marg_plot_on,
marg_plot_op,
marg_plot_sn,
marg_plot_sp,
ncol = 2, nrow = 2)
# uncomment to display plot
# marg_all
# save plot
ggsave("plots/marg_all_xp09_french.pdf", width = 50, height = 30, units = "cm")
|
/drafts/xp09/04a_plot_marg_fitted_xp09.R
|
no_license
|
bricebeffara/rwa_attitude_change
|
R
| false | false | 8,624 |
r
|
# File name: 04a_plot_marg_fitted_xp09.R
# Online archive: gitlab
# Authors: Brice Beffara & Amélie Bret
# Tue Jun 26 11:57:07 2018 ------------------------------
# Contact: brice.beffara@slowpen.science amelie.bret@univ-grenoble-alpes.fr http://slowpen.science
#
# This R script was used to create the marginal plots from brms models
# corresponding to the 10th experiment of Amelie Bret's doctoral work
#
# This R script plots marginal effect corresponding to the association
# of RWA with grebles' ratings in all combinations of the other indepentdent variables :
# usvalence : positive (0.5) vs. negative (-0.5)
# and load : load (0.5) vs. no load (-0.5)
#
# This program is believed to be free of errors, but it comes with no guarantee!
# The user bears all responsibility for interpreting the results.
#
# This preambule is largely inspired by John K. Kruschke's work at https://osf.io/wp2ry/
#
### To run this program, please do the following:
### 1. Install the general-purpose programming language R from
### http://www.r-project.org/
### Install the version of R appropriate for your computer's operating
### system (Windows, MacOS, or Linux).
### 2. Install the R editor, RStudio, from
### http://rstudio.org/
### This editor is not necessary, but highly recommended.
### 3. After the above actions are accomplished, this program should
### run as-is in R. You may "source" it to run the whole thing at once,
### or, preferably, run lines consecutively from the beginning.
################################################################################
# Loading packages needed (and installing if necessary) for this part
if (!require("pacman")) install.packages("pacman")
p_load(ggplot2, # main package for plots
colorRamps, # to add color palettes
ggpubr, # to combine plots
extrafontdb, # to get more available fonts for plots
hrbrthemes, # for ggplot2 theme
extrafont,
ggExtra,
install = TRUE,
update = getOption("pac_update"),
character.only = FALSE)
#------------------------------------------------------------------------------------
# First we determine all the possible combinations of modalities
# between the two categorical independent variables :
# "load" and "usvalence"
#------------------------------------------------------------------------------------
# !!orginally!! conditioned stimuli with !!negative!! valence
cond_on <- data.frame(load = -0.5, usvalence = -0.5,
cond__ = "noload_negative")
# !!orginally!! conditioned stimuli with !!positive!! valence
cond_op <- data.frame(load = -0.5, usvalence = 0.5,
cond__ = "noload_positive")
# !!spread!! conditionned stimuli with !!negative!! valence
cond_sn <- data.frame(load = 0.5, usvalence = -0.5,
cond__ = "load_negative")
# !!spread!! conditionned stimuli with !!positive!! valence
cond_sp <- data.frame(load = 0.5, usvalence = 0.5,
cond__ = "load_positive")
#------------------------------------------------------------------------------------
# We then select the marginal effects of RWA from the model
# for each combination of modalities
#------------------------------------------------------------------------------------
# !!orginally!! conditioned stimuli with !!negative!! valence
marg_on <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_on, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
# !!orginally!! conditioned stimuli with !!positive!! valence
marg_op <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_op, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
# !!spread!! conditionned stimuli with !!negative!! valence
marg_sn <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_sn, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
# !!spread!! conditionned stimuli with !!positive!! valence
marg_sp <- marginal_effects(load_resp, effects = "RWAscore", ordinal = TRUE,
conditions = cond_sp, method = c("fitted"), # here his where we specify the combination
re_formula = NULL)
#------------------------------------------------------------------------------------
# Now we can plot marginal effects for each combination of conditions...
#------------------------------------------------------------------------------------
# load fonts and themes
hrbrthemes::import_roboto_condensed()
loadfonts()
# !!orginally!! conditioned stimuli with !!negative!! valence
marg_plot_on = plot(marg_on, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Musique neutre pendant le contre-conditionnement positif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
# !!orginally!! conditioned stimuli with !!positive!! valence
marg_plot_op = plot(marg_op, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Musique neutre pendant le contre-conditionnement négatif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
# !!spread!! conditionned stimuli with !!negative!! valence
marg_plot_sn = plot(marg_sn, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Charge cognitive pendant le contre-conditionnement positif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
# !!spread!! conditionned stimuli with !!positive!! valence
marg_plot_sp = plot(marg_sp, plot = FALSE)[[1]] + # here his where we specify the marginal effects of interest
scale_fill_gradientn(colors = matlab.like(10), na.value = "transparent") +
scale_y_continuous(name="Évaluations", breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9), expand = c(0,0)) +
scale_x_continuous(name="RWA", breaks = scales::pretty_breaks(n = 10), expand=c(0,0)) +
labs(fill="Probabilité",
subtitle="Charge cognitive pendant le contre-conditionnement négatif") + # here his where we mention the marginal effects of interest
theme_ipsum_rc(base_size = 13,
subtitle_size = 20,
axis_title_size = 15) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
#------------------------------------------------------------------------------------
# ...and combine plots together
#------------------------------------------------------------------------------------
# Combine plot
marg_all <- ggarrange(marg_plot_on,
marg_plot_op,
marg_plot_sn,
marg_plot_sp,
ncol = 2, nrow = 2)
# uncomment to display plot
# marg_all
# save plot
ggsave("plots/marg_all_xp09_french.pdf", width = 50, height = 30, units = "cm")
|
## makeCacheMatrix is really a list of functions. cacheSolve function computes the
## inverse of the special "matrix" returned by makeCacheMatrix.
## Within the makeCacheMatrix function, "set" function sets the matrix to a new
## matrix y, "get" returns the matrix, "setinv" sets the inverse of the matrix, and
## "getinv" returns the inverse of the matrix.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- Null
}
get <- function() x
setinv <- function(solve) inv <<- solve
getinv <- function() inv
list(set = set, get = get, setinv = setinv, getinv = getinv)
}
## In the cacheSolve function, 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, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
|
/cachematrix.R
|
no_license
|
bahman20/Assignment2
|
R
| false | false | 1,240 |
r
|
## makeCacheMatrix is really a list of functions. cacheSolve function computes the
## inverse of the special "matrix" returned by makeCacheMatrix.
## Within the makeCacheMatrix function, "set" function sets the matrix to a new
## matrix y, "get" returns the matrix, "setinv" sets the inverse of the matrix, and
## "getinv" returns the inverse of the matrix.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- Null
}
get <- function() x
setinv <- function(solve) inv <<- solve
getinv <- function() inv
list(set = set, get = get, setinv = setinv, getinv = getinv)
}
## In the cacheSolve function, 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, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Do not modify this file since it was automatically generated from:
%
% Reporter.R
%
% by the Rdoc compiler part of the R.oo package.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\name{write.Reporter}
\alias{write.Reporter}
\alias{Reporter.write}
\alias{write.Reporter}
\alias{write,Reporter-method}
\title{Writes objects to document}
\usage{\method{write}{Reporter}(this, ..., sep="", line=FALSE)}
\arguments{
\item{...}{The object to be written.}
\item{sep}{Separator between object. Default value is \code{""} (note
the difference from \code{cat()} and \code{paste()}.}
\item{line}{If \code{\link[base:logical]{TRUE}}, a newline is written at the end, otherwise not.}
}
\description{
Writes objects to document.
}
\value{
Returns nothing.
}
\author{Henrik Bengtsson (\url{http://www.braju.com/R/})}
\seealso{
For more information see \code{\link{Reporter}}.
}
\keyword{internal}
\keyword{methods}
|
/man/write.Reporter.Rd
|
no_license
|
HenrikBengtsson/R.io
|
R
| false | false | 1,075 |
rd
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Do not modify this file since it was automatically generated from:
%
% Reporter.R
%
% by the Rdoc compiler part of the R.oo package.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\name{write.Reporter}
\alias{write.Reporter}
\alias{Reporter.write}
\alias{write.Reporter}
\alias{write,Reporter-method}
\title{Writes objects to document}
\usage{\method{write}{Reporter}(this, ..., sep="", line=FALSE)}
\arguments{
\item{...}{The object to be written.}
\item{sep}{Separator between object. Default value is \code{""} (note
the difference from \code{cat()} and \code{paste()}.}
\item{line}{If \code{\link[base:logical]{TRUE}}, a newline is written at the end, otherwise not.}
}
\description{
Writes objects to document.
}
\value{
Returns nothing.
}
\author{Henrik Bengtsson (\url{http://www.braju.com/R/})}
\seealso{
For more information see \code{\link{Reporter}}.
}
\keyword{internal}
\keyword{methods}
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/stata.R
\name{theme_stata}
\alias{theme_stata}
\title{Themes based on Stata graph schemes}
\usage{
theme_stata(base_size = 11, base_family = "sans", scheme = "s2color")
}
\arguments{
\item{base_size}{base font size}
\item{base_family}{base font family}
\item{scheme}{One of "s2color", "s2mono", "s1color", "s1rcolor", or "s1mono", "s2manual",
"s1manual", or "sj"}
}
\description{
Themes based on Stata graph schemes
}
\note{
Stata graph schemes include what \pkg{ggplot2} seperates
into themes and scales, as well as defaults specific to different
graph types (which ggplot does not support).
}
\examples{
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
q1 <- (qplot(carat, price, data=dsamp, colour=clarity)
+ ggtitle("Diamonds"))
q2 <- (qplot(carat, price, data=dsamp)
+ facet_wrap(~ clarity)
+ ggtitle("Diamonds"))
q1mono <- (qplot(carat, price, shape=clarity, color=clarity,
data=dsamp)
+ scale_shape_stata()
+ ggtitle("Diamonds"))
## s2color
(q1 + theme_stata() + scale_colour_stata(scheme = "s2color"))
(q2 + theme_stata())
## s2mono
(q1mono + theme_stata(scheme = "s2mono") + scale_colour_stata("mono"))
(q2 + theme_stata(scheme = "s2mono"))
## s1color
(q1 + theme_stata(scheme = "s1color") + scale_colour_stata("s1color"))
(q2 + theme_stata(scheme = "s1color"))
## s1rcolor
(q1 + theme_stata(scheme = "s1rcolor") + scale_colour_stata("s1rcolor"))
(ggplot(dsamp, aes(x=carat, y=price)) + geom_point(colour="white")
+ facet_wrap(~ clarity) + scale_colour_stata("s1rcolor")
+ ggtitle("Diamonds"))
## s1mono
(q1mono + theme_stata(scheme = "s1mono") + scale_colour_stata("mono"))
(q2 + theme_stata(scheme = "s1mono"))
}
\references{
\url{http://www.stata.com/help.cgi?schemes}
}
|
/man/theme_stata.Rd
|
no_license
|
nishantsbi/ggthemes
|
R
| false | false | 1,829 |
rd
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/stata.R
\name{theme_stata}
\alias{theme_stata}
\title{Themes based on Stata graph schemes}
\usage{
theme_stata(base_size = 11, base_family = "sans", scheme = "s2color")
}
\arguments{
\item{base_size}{base font size}
\item{base_family}{base font family}
\item{scheme}{One of "s2color", "s2mono", "s1color", "s1rcolor", or "s1mono", "s2manual",
"s1manual", or "sj"}
}
\description{
Themes based on Stata graph schemes
}
\note{
Stata graph schemes include what \pkg{ggplot2} seperates
into themes and scales, as well as defaults specific to different
graph types (which ggplot does not support).
}
\examples{
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
q1 <- (qplot(carat, price, data=dsamp, colour=clarity)
+ ggtitle("Diamonds"))
q2 <- (qplot(carat, price, data=dsamp)
+ facet_wrap(~ clarity)
+ ggtitle("Diamonds"))
q1mono <- (qplot(carat, price, shape=clarity, color=clarity,
data=dsamp)
+ scale_shape_stata()
+ ggtitle("Diamonds"))
## s2color
(q1 + theme_stata() + scale_colour_stata(scheme = "s2color"))
(q2 + theme_stata())
## s2mono
(q1mono + theme_stata(scheme = "s2mono") + scale_colour_stata("mono"))
(q2 + theme_stata(scheme = "s2mono"))
## s1color
(q1 + theme_stata(scheme = "s1color") + scale_colour_stata("s1color"))
(q2 + theme_stata(scheme = "s1color"))
## s1rcolor
(q1 + theme_stata(scheme = "s1rcolor") + scale_colour_stata("s1rcolor"))
(ggplot(dsamp, aes(x=carat, y=price)) + geom_point(colour="white")
+ facet_wrap(~ clarity) + scale_colour_stata("s1rcolor")
+ ggtitle("Diamonds"))
## s1mono
(q1mono + theme_stata(scheme = "s1mono") + scale_colour_stata("mono"))
(q2 + theme_stata(scheme = "s1mono"))
}
\references{
\url{http://www.stata.com/help.cgi?schemes}
}
|
library(MASS)
library(cluster)
library(emdbook)
library(dplyr)
library(reshape2)
library(RobustGaSP)
library(mvtnorm)
library(Matrix)
library(stringr)
library(GGally)
col_alpha <- function(col_str, alpha){
if(alpha<0|alpha>1){
stop('Alpha must be within (0,1)')
}
rgb_mat <- col2rgb(col_str,alpha = TRUE)
return(rgb(rgb_mat[1],rgb_mat[2],rgb_mat[3],alpha = 255*alpha, maxColorValue = 255))
}
# base_save_path = "/Users/Jake/Box Sync/Research/Computer_Emulation/Shanshan_Project/Results/"
# save_folder = ""
#
# save_path = paste0(base_save_path,save_folder)
##########################################################################
####These are plots to assess the sampler from jetscape_2_concatenate.R
##########################################################################
#Test for Normality
#None are <0.05 even without accounting for multiple testing
normality_test <- function(Y_final){
for(j in 1:dim(Y_final)[2]){
print(shapiro.test(Y_final[,j])$p.value)
}
}
#How many PCs?
calc_Vq <- function(Y_svd,save_pics = FALSE, plotit = FALSE){
eigs <- Y_svd$d^2
(V_q <- cumsum(eigs)/sum(eigs))
if(plotit){
if(save_pics) pdf(paste0(save_path,'var_explained.pdf'))
plot(V_q[1:6],type = 'o',
xlab = "Total Number of PCs R",
main = "Fraction of Variance Explained",
ylab = expression(F[R]),
cex.lab = 2,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(2.3,1,0),
pch = 19)
if(save_pics) dev.off()
}
return(V_q)
}
###########
##Results
#########
plot_heatmaps <- function(param_plot,ranges,
param_names = colnames(param_plot),
pairs = NULL,
save_param_names = NULL,
save_pics = FALSE,save_path = "", save_end = "", title = 'Posterior Heatmap',
plt_points = FALSE,design = NULL, ...){
if(save_pics & save_path==""){
print('Warning: saving plots to working directory')
}
#If you don't specify pairs, just do all of them
if(is.null(pairs)){
num_params = dim(param_plot)[2]
num_pairs = sum(1:(num_params-1))
i = 0
pairs = vector('list',num_pairs)
for(k in 1:(num_params-1)){
for(l in k:num_params)
i = i + 1
pairs[[i]] <- c(k,l)
}
}
num_pairs = length(pairs)
if(is.null(save_param_names)){
save_param_names <- vector('list',num_pairs)
}
for(i in 1:num_pairs){
(k = pairs[[i]][1])
(l = pairs[[i]][2])
f1 <- kde2d(param_plot[,k], (param_plot[,l]), n = 100,
lims = c(ranges[[k]],ranges[[l]]))
if(is.null(save_param_names[[i]])){
save_param_names[[i]] <- paste0(param_names[k],'_',param_names[l])
print(save_param_names[[i]])
}
if(save_pics) pdf(paste0(save_path,'heatmap_',save_param_names[[i]],save_end,'.pdf'))
par(mar=c(5.1, 5.1, 4.1, 2.1))
image(f1,
xlab = param_names[k],
ylab = "",
main = title,
cex.lab = 2,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(3,1,0), ...#,
# xlim = ranges[[1]],
# ylim = ranges[[2]]
)
title(ylab = param_names[l],
mgp = c(2.1,1,0),
cex.lab = 2,
cex.axis = 1.3)
perc_lvl = c(.6,.75,.9)
HPDregionplot(param_plot[,c(k,l)], prob = perc_lvl,
col=c("black"), lty = c(1,5,3), add=TRUE)
if(plt_points){
points(design[,k],design[,l],pch = 19, cex = 0.7)
}
# legend('topright',paste0(perc_lvl*100,"%"),title = "Highest Density Kernel Estimate",
# lty = c(1,5,3),
# bty="n")
if(save_pics) dev.off()
}
}
make_param_plot <- function(res_params, ranges){
param_plot <- matrix(0,dim(res_params)[1],dim(res_params)[2])
for(j in 1:dim(param_plot)[2]){
param_plot[,j] <- res_params[,j]*(ranges[[j]][2] - ranges[[j]][1]) + ranges[[j]][1]
}
colnames(param_plot) <- names(ranges)
return(param_plot)
}
unmake_param_plot <- function(param_plot, ranges){
res_params <- matrix(0,dim(param_plot)[1], dim(param_plot)[2])
for(j in 1:dim(res_params)[2]){
res_params[,j] <- (param_plot[,j] - ranges[[j]][1])/(ranges[[j]][2] - ranges[[j]][1])
}
colnames(res_params) <- names(ranges)
return(res_params)
}
transform_draws <- function(param_plot,cols_to_transform = c(1,2),
new_names = c('A','C')){
X = param_plot[,cols_to_transform[1]]
Y = param_plot[,cols_to_transform[2]]
new_param_plot = param_plot
new_param_plot[,1] = X*Y
new_param_plot[,2] = X*(1-Y)
colnames(new_param_plot)[cols_to_transform] = new_names
return(new_param_plot)
}
transform_ranges <- function(ranges,vars_to_transform = c(1,2),
new_names = c('A','C')){
ranges_t <- ranges
ranges_t[[1]] <- c(0,ranges[[1]][2])
ranges_t[[2]] <- c(0, ranges[[1]][2])
names(ranges_t)[1:2] <- new_names
return(ranges_t)
}
heat_pairplot <- function(param_plot,
ranges,
split_num = dim(param_plot)[1],
param_names = colnames(param_plot),
title = 'Calibration Pairplot',save_pics = FALSE,
save_path = "",
save_end = "",
include_legend = FALSE,
legend_names = NULL,
legend_cols = NULL,
off_diag = "heatmap"){
panel.hist <- function(x,col_hist,split_num, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
h <- hist(x[1:split_num], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(1,0,0,.1), ...)
if(split_num<length(x)){
h <- hist(x[(split_num+1):length(x)], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(0,0,1,.1), ...)
}
}
panel.dens <- function(x,split_num,...){
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
plot(density(x[1:split_num],))
h <- hist(x[1:split_num], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(1,0,0,.1), ...)
if(split_num<length(x)){
h <- hist(x[(split_num+1):length(x)], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(0,0,1,.1), ...)
}
}
panel.scatter <- function(x,y,split_num,...){
first_pts = 1:split_num
points(x[first_pts],y[first_pts],#pch = 19,
col = rgb(1,0,0,.01),cex=.7,
...)
#If you actually want to split
if(split_num<length(x)){
second_pts <- (split_num+1):length(x)
points(x[second_pts],y[second_pts],#pch =19,
col = rgb(0,0,1,.01), cex = 0.7,
...)
}
}
panel.image <- function(x,y,split_num,...){
f1 <- kde2d(x, y, n = 100)
image(f1,add = TRUE)
}
if(off_diag=="scatter"){
panel_off = panel.scatter
}else if(off_diag=="heatmap"){
if(split_num<dim(param_plot)[1]){
stop('Heatmap only appropriate for one set of calibration results')
}
panel_off = panel.image
}else{stop("Whoops off_diag parameter is wrong")}
if(save_pics){ pdf(paste0(save_path,'calibration_pairplot',save_end,".pdf"))}
pairs(param_plot,
panel = panel_off,
diag.panel = panel.hist,
#pch = 19,
#cex = .3,
# col = rgb(1,0,0,.1),
labels = param_names,
upper.panel = NULL,
cex.lab = 1.5,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(2.3,1,0),
#col_hist = 'green',
las = 2,
main = title,
split_num = split_num)
if(include_legend){
legend('topright',legend_names,col = legend_cols,
pch = 19,inset = .13)
}
if(save_pics) dev.off()
}
gg_heat_pairs <- function(all_data,
ranges,
cols_to_use = 1:4,
scatter_alpha = 0.1,
col_names = c('A','B','C','D')){
both_col <- 'red3'
lhc_col <- 'deepskyblue'
rhic_col <- 'forestgreen'
my_dens <- function(data, mapping, ...) {
ggplot(data = data, mapping=mapping) +
geom_density(..., alpha = 0.7, size = 1.1) +
scale_fill_manual(values=c( both_col, lhc_col, rhic_col )) +
scale_color_manual(values=c( both_col,lhc_col, rhic_col))
}
my_scatter <- function(data,mapping,...){
ggplot(data = data, mapping = mapping) +
geom_jitter(alpha = scatter_alpha,size = .3) +
guides(col = guide_legend(override.aes = list(shape = 15,
size = 8,
alpha = 1),
label.theme = element_text(size = 12))) +
scale_fill_manual(values=c( both_col, lhc_col, rhic_col )) +
scale_color_manual(values=c( both_col,lhc_col, rhic_col)) +
theme(legend.title=element_blank())
}
p <- ggpairs(all_data, mapping = aes(color = Collider), columns = cols_to_use,
lower = list(continuous = my_scatter),
diag = list(continuous = my_dens),
upper = list(continuous = 'blank'),
columnLabels = col_names,
labeller = 'label_parsed'
#,legend = c(2,1)
)
for(i in 1:length(cols_to_use)){
for(j in 1:length(cols_to_use)){
if(j<=i){
p[i,j] <- p[i,j] + xlim(ranges[[j]][1],ranges[[j]][2]) +
theme(axis.text = element_text(size = 11.5))
}
}
}
#p <- p + theme(strip.text = element_text(size = 15))
#Remove yaxis on first plot, to remove confusion
#p[1,1] <- p[1,1] + theme(axis.text.y = element_blank(),
# axis.ticks = element_blank())
points_legend <- gglegend(my_scatter)
p[1,p$ncol] <- points_legend(all_data, ggplot2::aes(all_data[1,cols_to_use[1]],
all_data[1,cols_to_use[2]],
color = Collider))
#p[1,p$ncol-1] <- points_legend(all_data, ggplot2::aes(all_data[1,cols_to_use[1]],
# all_data[1,cols_to_use[2]],
# color = Collider))
#print(p + theme(strip.text = element_text(size = 15)))
print(p)
}
make_combined_pairplot <- function(save_lists,
labels,
ranges,
save_pics = FALSE,
save_path = '',
save_end = '',
cols_to_use = 1:5,
scatter_alpha = 0.1,
num_samples = 1E4,
str_param_to_use = 'transformed_params',
col_names = c('A','B','C','D'),
make_pdf = FALSE){
load(save_lists[1])
data_to_plot <- matrix(,0,ncol(save_list[[str_param_to_use]]))
if(length(save_lists)!=length(labels)){
stop('lists and labels not same length')
}
for(i in 1:length(save_lists)){
load(save_lists[i])
cur_data <- as.data.frame(save_list[[str_param_to_use]]) %>%
dplyr::sample_n(.,num_samples)
cur_data$Collider <- labels[i]
data_to_plot <- rbind(data_to_plot, cur_data)
}
if(save_pics){
if(make_pdf){
pdf(paste0(save_path,'combined_pairplot',save_end,'.pdf'))
}else{
png(paste0(save_path,'combined_pairplot',save_end,'.png'))
}
}
gg_heat_pairs(data_to_plot,
ranges = ranges,
cols_to_use = cols_to_use,
col_names = col_names,
scatter_alpha = scatter_alpha)
if(save_pics) dev.off()
}
plot_lines <- function(pred_dat,exp_dat,
med_pred_vec = NULL,
pT_col = 'pT',
exp_col = 'RAA_exp',
err_col_stat = 'exp_err_stat',
err_col_sys = 'exp_err_sys',
col_str = 'red',
col_pts = 'darkred',
all_col_pts = c('darkred','darkblue'),
all_col_strs = c('red','blue'),
alpha_val = 0.01,
delta = rep(0,dim(exp_dat)[1]),
include_legend = TRUE,
legend_loc = 'top_left',
include_med = FALSE,
add = FALSE,
include_arrows = TRUE,
cen_labels = NULL,
plot_title = "",
data_loc_name = "",
...){
if(!add){
#xlimits
pt_lim = min(exp_dat[,pT_col])
if(str_detect(plot_title,'AuAu200')){
pt_lim = c(pt_lim,20)
txt_x = 11.7
}else if(str_detect(plot_title,'PbPb2760')){
pt_lim = c(pt_lim,90)
#txt_x = 45 #for MATTER (?why)
txt_x = 27
}else if(str_detect(plot_title,'PbPb5020')){
pt_lim = c(pt_lim,100)
#txt_x = 45 #for MATTER (?why)
txt_x = 30
}else{
print('Warning: Using auto-generated tick marks for pT')
pt_lim = c(pt_lim,max(exp_dat[,pT_col]))
}
plot(exp_dat[,pT_col],pred_dat[,1],
cex = 0.5,
col = col_alpha(col_str,alpha_val),
type = 'l',
# ylim = c(min(exp_dat[,exp_col] - 2*exp_dat[,err_col_sys],
# exp_dat[,exp_col] - 2*exp_dat[,err_col_stat]),
# max(exp_dat[,exp_col] + 2*exp_dat[,err_col_sys],
# exp_dat[,exp_col] + 2*exp_dat[,err_col_stat])),
ylim = c(0,1.8),
xlim = pt_lim,
xlab = expression(p[T]~"(GeV)"),
ylab = expression(R[AA]),
cex.lab = 2,
mgp = c(2.3,1,0),
pch = 15,
yaxt = 'n',
xaxt = 'n',
...)
title(main = plot_title, line = -1.5, cex.main = 1.3, adj = .97)
box(lwd = 3)
#Add data location labels
text(txt_x, 1.47, paste0('Data from ',data_loc_name),cex = 1, font = 2)
#y axis ticks and labels
axis(side = 2, at = seq(0,1.5,by = 0.3), las = 1, lwd.ticks = 3, labels = NA)
axis(side = 2, at = seq(0,1.5,by = 0.3), las = 1,
cex.axis = 1.2, lwd = 0, line = -0.4)
#x axis ticks and labels
if(str_detect(plot_title,'AuAu')){
pt_ticks = seq(10,20,by = 2)
}else if(str_detect(plot_title,'PbPb')){
pt_ticks = seq(10,100, by = 10)
}else{
print('Warning: Using auto-generated tick marks for pT')
pt_ticks = seq(min(exp_dat[,pT_col]),max(exp_dat[,pT_col]), length.out = 5)
}
axis(side = 1, at = pt_ticks, lwd.ticks = 3, labels = NA)
axis(side = 1, at = pt_ticks, cex.axis = 1.2, lwd = 0, line = -0.4)
}else{
lines(exp_dat[,pT_col],pred_dat[,1],
cex = 0.5,
col = col_alpha(col_str,alpha_val),type = 'l')
}
#x_range = max(exp_dat[,pT_col]) - min(exp_dat[,pT_col])
#arrow_offset = x_range/130
arrow_offset = 0
for(i in 2:dim(pred_dat)[2]){
lines(exp_dat[,pT_col],pred_dat[,i] + delta,cex = 0.5,
col = col_alpha(col_str,alpha_val))
}
if(include_med){
lines(exp_dat[,pT_col], med_pred_vec,lty = 2, lwd = 2)
}
##############
### DEPRECIATED: NOW WE PUT THE POINTS AND ARROWS IN AFTER ALL LINES
###############
# if(!add){
# exp_pch = 15
# }else{
# exp_pch = 17
# }
#
# ## Add experimental points
# points(exp_dat[,pT_col],exp_dat[,exp_col],
# pch = exp_pch, col = col_pts)
#
# #ylim = c(0,1))
# if(include_arrows){
# arrow_stat_col = col_pts
# arrow_sys_col = col_pts
#
# #Statistical errors
# arrows(exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_stat],
# exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_stat],
# length=0.05, angle=90, code=3,col = arrow_stat_col)
#
# #Systematic errors
# arrows(exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_sys],
# exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_sys],
# length=0.05, angle=90, code=3, col = arrow_sys_col)
# }
if(include_legend){
legend_cex = 1.1
if(include_med){
legend(legend_loc, c(paste(cen_labels,'Centrality'),'Median Predictions'),
lty = c(1,1,2),lwd = c(2,2,2),col = c(all_col_strs,'black'),
box.lwd = 2, cex = legend_cex)
#Put the point shapes on top
legend(legend_loc, c(rep("",length(cen_labels)),""), col = all_col_pts,
pch = c(15,17,NA), bty='n', cex = legend_cex)
}else{
legend(legend_loc, paste(cen_labels,'Centrality'),lwd = 2, col = all_col_strs,
box.lwd = 2, cex = legend_cex)
#Put the point shapes on top
legend(legend_loc, rep("",length(cen_labels)), col = all_col_pts,
pch = c(15, 17), bty='n', box.lwd = 2, cex = legend_cex)
}
}
}
plot_draws_together <- function(draws,
train_mod,
rot_mat,
original_dset_list,
q_index = NA,
condition_on_q = FALSE,
dset_labels = NULL,
data_orig_labels = NULL,
cen_groups = NULL,
cen_labels = NULL,
RAA_med_vals = NULL,
med_pred_type = 'RAA',
col_str_vec = c('red','blue'),
col_pts_vec = c('darkred','darkblue'),
include_med = FALSE,
scale_mean_vec = NULL, #sd_vec
scale_sd_vec = NULL, #y_means
delta_list = NULL,
num_samples = 1E3,
title_end = "",
alpha_val = 0.01,
save_pics = FALSE,
save_path = "",
save_end = "",
include_legend = TRUE,
include_arrows = TRUE,
legend_spots = replicate(J,'top_left')){
if(is.null(scale_sd_vec)|is.null(scale_mean_vec)){
stop('Must set values for scale_sd_vec and scale_mean_vec. Try sd_vec and y_means')
}else if(dim(draws)[1]<num_samples){
stop('Num samples bigger than number of draws')
}else if(sum(do.call(c,lapply(cen_groups,length)) - length(col_str_vec))){
print('Centrality Groups:')
print(cen_group)
print('Color vector:')
print(col_str_vec)
stop("Color vec and centrality group lengths not all the same")
}
Y_pred = exp_predictions(theta = draws,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t()
Y_pred <- Y_pred[sample(1:dim(Y_pred)[1],num_samples),]
if(include_med){
if(med_pred_type=='emulator'){
if(condition_on_q){
q_mode <- density(draws[,q_index])$x[which.max(density(draws[,q_index])$y)]
q_width = 0.3
good_q <- which(draws[,q_index] > (q_mode - q_width) &
draws[,q_index] < (q_mode + q_width) )
draws <- draws[good_q, ]
}
(param_meds <- apply(draws,2,median) %>% t())
(med_pred <- exp_predictions(theta = param_meds,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t())
}else if(med_pred_type=='RAA'){
(med_pred = RAA_med_vals)
}else{
stop('med_pred_type must be one of "emulator", "RAA"')
}
print(paste0('Median prediction values are ',med_pred_type))
}else{
med_pred <- matrix(0,1,length(scale_mean_vec))
}
cur_col <- 1
for(j in 1:length(cen_groups)){
(cur_cen_labels = cen_labels[[j]])
(cur_group = names(cen_groups)[j])
(K_j <- length(cen_groups[[j]]))
(cur_data_loc_name = data_orig_labels[j])
exp_dset_list_j = vector('list',K_j)
for(k in 1:K_j){
(dset_index = cen_groups[[j]][k])
(cur_color <- col_str_vec[k])
(cur_pts_col <- col_pts_vec[k])
(num_pT <- dim(original_dset_list[[dset_index]])[1])
cur_dset <- t(Y_pred[,cur_col:(cur_col + num_pT - 1)])
if(med_pred_type=='emulator'){
(cur_med_pred <- med_pred[,cur_col:(cur_col + num_pT - 1)])
}else{
(cur_med_pred <- RAA_med_vals[[j]][[k]])
}
exp_dset <- cbind('pT' = original_dset_list[[dset_index]]$pT,
'RAA_exp' = original_dset_list[[dset_index]]$RAA_exp,
'exp_err_stat' = original_dset_list[[dset_index]]$Stat_err,
'exp_err_sys' = original_dset_list[[dset_index]]$Sys_err)
exp_dset_list_j[[k]] <- exp_dset
(cur_col = cur_col + num_pT)
#Plot 'em
if(k==1){
if(save_pics) pdf(paste0(save_path,dset_labels[j],save_end,'.pdf'))
plot_lines(pred_dat = cur_dset,
exp_dat = exp_dset,
med_pred_vec = cur_med_pred,
delta = delta_list[[dset_index]],
alpha_val = alpha_val,
include_legend = include_legend,
legend_loc = legend_spots[dset_index],
include_med = include_med,
col_str = cur_color,
all_col_strs = col_str_vec,
col_pts = cur_pts_col,
all_col_pts = col_pts_vec,
cen_labels = cur_cen_labels,
include_arrows = include_arrows,
plot_title = paste(cur_group,title_end),
data_loc_name = cur_data_loc_name
)
}else{
plot_lines(pred_dat = cur_dset,
exp_dat = exp_dset,
med_pred_vec = cur_med_pred,
delta = delta_list[[dset_index]],
alpha_val = alpha_val,
include_legend = include_legend,
legend_loc = legend_spots[dset_index],
include_med = include_med,
col_str = cur_color,
all_col_strs = col_str_vec,
col_pts = cur_pts_col,
all_col_pts = col_pts_vec,
cen_labels = cur_cen_labels,
include_arrows = include_arrows,
add = TRUE)
}
if(k==K_j){
#########
## Plot all the points on top of the lines
#########
pT_col = 'pT'
exp_col = 'RAA_exp'
err_col_stat = 'exp_err_stat'
err_col_sys = 'exp_err_sys'
#Loop over the datasets in this collision system
for(i in 1:K_j){
(col_pts <- col_pts_vec[i])
exp_dat = exp_dset_list_j[[i]]
if(i < K_j){
exp_pch = 15
}else{
exp_pch = 17
}
## Add experimental points
points(exp_dat[,pT_col],exp_dat[,exp_col],
pch = exp_pch, col = col_pts)
#ylim = c(0,1))
if(include_arrows){
arrow_stat_col = col_pts
arrow_sys_col = col_pts
#x_range = max(exp_dat[,pT_col]) - min(exp_dat[,pT_col])
#arrow_offset = x_range/130
arrow_offset = 0
#Statistical errors
arrows(exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_stat],
exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_stat],
length=0.05, angle=90, code=3,col = arrow_stat_col)
#Systematic errors
arrows(exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_sys],
exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_sys],
length=0.05, angle=90, code=3, col = arrow_sys_col)
}
}
if(save_pics) dev.off()
}
}#k loop
}#j loop
}
#Predict PCA vals
###DEPRECIATED######
plot_draws <- function(draws,
train_mod,
rot_mat,
original_dset_list,
include_med = FALSE,
dset_labels = NULL,
scale_mean_vec = NULL, #sd_vec
scale_sd_vec = NULL, #y_means
delta_list = NULL,
num_samples = 1E3,
title_end = "",
alpha_val = 0.01,
save_pics = FALSE,
save_path = "",
save_end = "",
include_legend = TRUE,
include_arrows = TRUE,
legend_spots = replicate(J,'top_left')){
if(is.null(scale_sd_vec)|is.null(scale_mean_vec)){
stop('Must set values for scale_sd_vec and scale_mean_vec. Try sd_vec and y_means')
}else if(dim(draws)[1]<num_samples){
stop('Num samples bigger than number of draws')
}
Y_pred = exp_predictions(theta = draws,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t() #%>%
#dplyr::slice(sample(1:dim(Y_pred)[1],num_samples))
# ##Predict the mu_Z, collect them
# colnames(draws) <- colnames(ranges)
# post_pred_mod <-lapply(train_mod, RobustGaSP::predict,
# # testing_trend = as.data.frame(cbind(rep(1,dim(draws)[1]),draws)),
# testing_input = as.data.frame(draws))
#
# pred_means <- lapply(post_pred_mod,function(x)x$mean) %>%
# do.call(cbind,.)
#
#
# #Rotate
# Y_pred_scaled <- pred_means %*%t(rot_mat)
#
# #Scale
#
# Y_pred <- sweep(Y_pred_scaled,2,scale_sd_vec,FUN = "*") %>%
# sweep(2,scale_mean_vec,FUN = '+')
# #Y_pred <- sweep(Y_pred_scaled,2,apply(scale_mat,2,mean),FUN = '+')
#
Y_pred <- Y_pred[sample(1:dim(Y_pred)[1],num_samples),]
if(include_med){
(param_meds <- apply(draws,2,median) %>% t())
(med_pred <- exp_predictions(theta = param_meds,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t())
}else{
med_pred <- matrix(0,1,length(scale_mean_vec))
}
cur_col <- 1
for(j in 1:length(original_dset_list)){
(num_pT <- dim(original_dset_list[[j]])[1])
cur_dset <- t(Y_pred[,cur_col:(cur_col + num_pT - 1)])
cur_med_pred <- med_pred[,cur_col:(cur_col + num_pT - 1)]
exp_dset <- cbind('pT' = original_dset_list[[j]]$pT,
'RAA_exp' = original_dset_list[[j]]$RAA_exp,
'exp_err_stat' = original_dset_list[[j]]$Stat_err,
'exp_err_sys' = original_dset_list[[j]]$Sys_err)
(cur_col = cur_col + num_pT)
#Plot 'em
if(save_pics) pdf(paste0(save_path,dset_labels[j],save_end,'.pdf'))
plot_lines(pred_dat = cur_dset,
exp_dat = exp_dset,
med_pred_vec = cur_med_pred,
delta = delta_list[[j]],
main = paste(dset_labels[j],title_end),
alpha_val = alpha_val,
include_legend = include_legend,
legend_loc = legend_spots[j],
include_med = include_med)
if(save_pics) dev.off()
}
}
plot_discrep_fun <- function(discrep_list,
ell_mat,
lambda_mat,
pT_train,
pT_pred,
alpha = 2,
include_pts = TRUE,
dset_labels = dset_strings,
save_pics = FALSE,
save_path = "",
save_suffix = ""){
mu_delt <- sig_delt <- vector('list',length(discrep_list))
for(j in 1:length(discrep_list)){
y = discrep_list[[j]]
x_train = matrix(pT_train[[j]])
x_pred = matrix(sort(c(pT_train[[j]],pT_pred[[j]])))
ell_j = mean(ell_mat[,j])
lambda_j = mean(lambda_mat[,j])
sig_22 = cov_mat_multi(x_train,
x_train,
ell_vec = ell_j,
lambda = lambda_j,
alpha_vec = alpha,
nugget = 1E-6)
sig_22_inv <- chol2inv(chol(sig_22))
sig_12 = cov_mat_multi(x_pred,
x_train,
ell_vec = ell_j,
lambda = lambda_j,
alpha_vec = alpha,
nugget = 1E-6)
sig_21 = t(sig_12)
sig_11 = cov_mat_multi(x_pred,
x_pred,
ell_vec = ell_j,
lambda = lambda_j,
alpha_vec = alpha,
nugget = 1E-6)
mu_delt[[j]] <- sig_12%*%sig_22_inv%*%y
sig_delt[[j]] <- diag(sig_11 - sig_12%*%sig_22_inv%*%sig_21)
if(save_pics)pdf(paste0(save_path,"discrep_",dset_labels[j],save_suffix,".pdf"))
plot(x_pred,mu_delt[[j]],type = 'l',
# ylim = c(min(mu_delt[[j]] - 2*sqrt(sig_delt[[j]])),
# max(mu_delt[[j]] + 2*sqrt(sig_delt[[j]]))))
ylim = c(-.23,.23),
xlab = expression(p[T]~"(GeV)"),
#ylab = expression(delta[j]),
main = paste0("Discrepancy for ",dset_labels[j]),
cex.lab = 2,
cex.main = 2,
ylab = "")
title(ylab = expression(delta[j]),cex.lab = 2,mgp=c(2,1,0))
lines(x_pred,mu_delt[[j]] - 2*sqrt(sig_delt[[j]]),col = 'blue',
lty = 2)
lines(x_pred,mu_delt[[j]] + 2*sqrt(sig_delt[[j]]),col = 'blue',
lty = 2)
abline(h=0)
if(include_pts){
points(x_train,y)
}
if(save_pics) dev.off()
}
invisible(list(mu_delt = mu_delt,sig_delt = sig_delt))
}
###########
##Validation Plot
##########
##Requires:
#Holdout point
#Design
#Train dset
# V
# y_sd
# y_mean
##Ugh...should change this to use the new prediction function
predict_holdout <- function(holdout,
design = comp_mod$all_data$scaled_d,
Y_scaled = comp_mod$Y_final,
#Y_orig = Y,
y_sd_cur = comp_mod$y_sd,
y_mean_cur = comp_mod$y_means,
q = length(comp_mod$train_mods), plotit = FALSE,
verbose = FALSE,
cover_level = 95){
train_d <- design[-holdout, ]
test_d <- design[holdout, ]
train_Y <- Y_scaled[-holdout, ]
Y_orig <- sweep(Y_scaled,2,y_sd_cur,"*")%>%
sweep(2,y_mean_cur, "+")
test_Y <- Y_orig[holdout, ]
V_train <- svd(train_Y)$v[ , 1:q]
train_Z = as.matrix(train_Y)%*%V_train
sink("NUL")
train_mod <- lapply(as.data.frame(train_Z),rgasp,design = train_d,
kernel_type = 'pow_exp')
sink()
test_mod <- lapply(train_mod,RobustGaSP::predict,testing_input = test_d)
pred_Z <- lapply(test_mod,function(x)x$mean) %>%
do.call(c,.) %>%
t()
pred_err_Z <- lapply(test_mod,function(x)x$sd^2) %>%
do.call(c,.)
pred_Y <- pred_Z %*% t(V_train) %*% diag(y_sd_cur) + y_mean_cur
pred_err_Y <- diag(y_sd_cur) %*% V_train %*% diag(pred_err_Z) %*% t(V_train) %*% diag(y_sd_cur) %>%
diag()
if(cover_level == 95){
sd_mult = 2
}else if(cover_level == 60){
sd_mult = 1
}else{
stop('Must pick 95% or 60% for cover level')
}
if(plotit){
plot(as.numeric(test_Y),as.numeric(pred_Y),pch = 19,cex = .5,
xlab = 'Holdout Values',
ylab = 'Predicted Values',
main = paste0('Emulator Prediction, Holdout ',holdout),
cex.lab = 2,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(2.4,1,0),
ylim = c(min(as.numeric(pred_Y) - sd_mult*sqrt(pred_err_Y)),
max(as.numeric(pred_Y) + sd_mult*sqrt(pred_err_Y))))
arrows(as.numeric(test_Y), as.numeric(pred_Y) - sd_mult*sqrt(pred_err_Y),
as.numeric(test_Y), as.numeric(pred_Y) + sd_mult*sqrt(pred_err_Y),
length=0, angle=90, code=3)
abline(a = 0,b = 1)
}
good_pred_95 <- test_Y < as.numeric(pred_Y) + 2*sqrt(pred_err_Y) &
test_Y > as.numeric(pred_Y) - 2*sqrt(pred_err_Y)
good_pred_60 <- test_Y < as.numeric(pred_Y) + sqrt(pred_err_Y) &
test_Y > as.numeric(pred_Y) - sqrt(pred_err_Y)
return(list(mean_cover_95 = mean(good_pred_95), mean_cover_60 = mean(good_pred_60),
mean_width = mean(4*sqrt(pred_err_Y))))
}
collect_all_holdouts <- function(D_c_theta = comp_mod$all_data$scaled_d,
Y_scaled = comp_mod$Y_final,
#Y_orig = Y,
y_sd_cur = comp_mod$y_sd,
y_mean_cur = comp_mod$y_means,
q = length(comp_mod$train_mods)){
n_holdouts <- nrow(D_c_theta)
cover_95 <- cover_60 <- widths <- numeric(n_holdouts)
for(h in 1:n_holdouts){
invisible(pred_hold_h <- predict_holdout(holdout = h,
design = D_c_theta,
Y_scaled = Y_scaled,
y_sd_cur = y_sd_cur,
y_mean_cur = y_mean_cur,
q = q))
cover_95[h] <- pred_hold_h$mean_cover_95
cover_60[h] <- pred_hold_h$mean_cover_60
widths[h] <- pred_hold_h$mean_width
flush.console()
cat("\r FINISHED HOLDOUT ", h ,'/',n_holdouts)
}
return(list(cover_95 = cover_95, cover_60 = cover_60, widths = widths))
}
|
/outdated_scripts/assess_concat_analysis.R
|
no_license
|
jake-coleman32/JETSCAPE-STAT-Rpkg
|
R
| false | false | 35,900 |
r
|
library(MASS)
library(cluster)
library(emdbook)
library(dplyr)
library(reshape2)
library(RobustGaSP)
library(mvtnorm)
library(Matrix)
library(stringr)
library(GGally)
col_alpha <- function(col_str, alpha){
if(alpha<0|alpha>1){
stop('Alpha must be within (0,1)')
}
rgb_mat <- col2rgb(col_str,alpha = TRUE)
return(rgb(rgb_mat[1],rgb_mat[2],rgb_mat[3],alpha = 255*alpha, maxColorValue = 255))
}
# base_save_path = "/Users/Jake/Box Sync/Research/Computer_Emulation/Shanshan_Project/Results/"
# save_folder = ""
#
# save_path = paste0(base_save_path,save_folder)
##########################################################################
####These are plots to assess the sampler from jetscape_2_concatenate.R
##########################################################################
#Test for Normality
#None are <0.05 even without accounting for multiple testing
normality_test <- function(Y_final){
for(j in 1:dim(Y_final)[2]){
print(shapiro.test(Y_final[,j])$p.value)
}
}
#How many PCs?
calc_Vq <- function(Y_svd,save_pics = FALSE, plotit = FALSE){
eigs <- Y_svd$d^2
(V_q <- cumsum(eigs)/sum(eigs))
if(plotit){
if(save_pics) pdf(paste0(save_path,'var_explained.pdf'))
plot(V_q[1:6],type = 'o',
xlab = "Total Number of PCs R",
main = "Fraction of Variance Explained",
ylab = expression(F[R]),
cex.lab = 2,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(2.3,1,0),
pch = 19)
if(save_pics) dev.off()
}
return(V_q)
}
###########
##Results
#########
plot_heatmaps <- function(param_plot,ranges,
param_names = colnames(param_plot),
pairs = NULL,
save_param_names = NULL,
save_pics = FALSE,save_path = "", save_end = "", title = 'Posterior Heatmap',
plt_points = FALSE,design = NULL, ...){
if(save_pics & save_path==""){
print('Warning: saving plots to working directory')
}
#If you don't specify pairs, just do all of them
if(is.null(pairs)){
num_params = dim(param_plot)[2]
num_pairs = sum(1:(num_params-1))
i = 0
pairs = vector('list',num_pairs)
for(k in 1:(num_params-1)){
for(l in k:num_params)
i = i + 1
pairs[[i]] <- c(k,l)
}
}
num_pairs = length(pairs)
if(is.null(save_param_names)){
save_param_names <- vector('list',num_pairs)
}
for(i in 1:num_pairs){
(k = pairs[[i]][1])
(l = pairs[[i]][2])
f1 <- kde2d(param_plot[,k], (param_plot[,l]), n = 100,
lims = c(ranges[[k]],ranges[[l]]))
if(is.null(save_param_names[[i]])){
save_param_names[[i]] <- paste0(param_names[k],'_',param_names[l])
print(save_param_names[[i]])
}
if(save_pics) pdf(paste0(save_path,'heatmap_',save_param_names[[i]],save_end,'.pdf'))
par(mar=c(5.1, 5.1, 4.1, 2.1))
image(f1,
xlab = param_names[k],
ylab = "",
main = title,
cex.lab = 2,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(3,1,0), ...#,
# xlim = ranges[[1]],
# ylim = ranges[[2]]
)
title(ylab = param_names[l],
mgp = c(2.1,1,0),
cex.lab = 2,
cex.axis = 1.3)
perc_lvl = c(.6,.75,.9)
HPDregionplot(param_plot[,c(k,l)], prob = perc_lvl,
col=c("black"), lty = c(1,5,3), add=TRUE)
if(plt_points){
points(design[,k],design[,l],pch = 19, cex = 0.7)
}
# legend('topright',paste0(perc_lvl*100,"%"),title = "Highest Density Kernel Estimate",
# lty = c(1,5,3),
# bty="n")
if(save_pics) dev.off()
}
}
make_param_plot <- function(res_params, ranges){
param_plot <- matrix(0,dim(res_params)[1],dim(res_params)[2])
for(j in 1:dim(param_plot)[2]){
param_plot[,j] <- res_params[,j]*(ranges[[j]][2] - ranges[[j]][1]) + ranges[[j]][1]
}
colnames(param_plot) <- names(ranges)
return(param_plot)
}
unmake_param_plot <- function(param_plot, ranges){
res_params <- matrix(0,dim(param_plot)[1], dim(param_plot)[2])
for(j in 1:dim(res_params)[2]){
res_params[,j] <- (param_plot[,j] - ranges[[j]][1])/(ranges[[j]][2] - ranges[[j]][1])
}
colnames(res_params) <- names(ranges)
return(res_params)
}
transform_draws <- function(param_plot,cols_to_transform = c(1,2),
new_names = c('A','C')){
X = param_plot[,cols_to_transform[1]]
Y = param_plot[,cols_to_transform[2]]
new_param_plot = param_plot
new_param_plot[,1] = X*Y
new_param_plot[,2] = X*(1-Y)
colnames(new_param_plot)[cols_to_transform] = new_names
return(new_param_plot)
}
transform_ranges <- function(ranges,vars_to_transform = c(1,2),
new_names = c('A','C')){
ranges_t <- ranges
ranges_t[[1]] <- c(0,ranges[[1]][2])
ranges_t[[2]] <- c(0, ranges[[1]][2])
names(ranges_t)[1:2] <- new_names
return(ranges_t)
}
heat_pairplot <- function(param_plot,
ranges,
split_num = dim(param_plot)[1],
param_names = colnames(param_plot),
title = 'Calibration Pairplot',save_pics = FALSE,
save_path = "",
save_end = "",
include_legend = FALSE,
legend_names = NULL,
legend_cols = NULL,
off_diag = "heatmap"){
panel.hist <- function(x,col_hist,split_num, ...)
{
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
h <- hist(x[1:split_num], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(1,0,0,.1), ...)
if(split_num<length(x)){
h <- hist(x[(split_num+1):length(x)], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(0,0,1,.1), ...)
}
}
panel.dens <- function(x,split_num,...){
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
plot(density(x[1:split_num],))
h <- hist(x[1:split_num], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(1,0,0,.1), ...)
if(split_num<length(x)){
h <- hist(x[(split_num+1):length(x)], plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y,xlim = c(0,0.35),col = rgb(0,0,1,.1), ...)
}
}
panel.scatter <- function(x,y,split_num,...){
first_pts = 1:split_num
points(x[first_pts],y[first_pts],#pch = 19,
col = rgb(1,0,0,.01),cex=.7,
...)
#If you actually want to split
if(split_num<length(x)){
second_pts <- (split_num+1):length(x)
points(x[second_pts],y[second_pts],#pch =19,
col = rgb(0,0,1,.01), cex = 0.7,
...)
}
}
panel.image <- function(x,y,split_num,...){
f1 <- kde2d(x, y, n = 100)
image(f1,add = TRUE)
}
if(off_diag=="scatter"){
panel_off = panel.scatter
}else if(off_diag=="heatmap"){
if(split_num<dim(param_plot)[1]){
stop('Heatmap only appropriate for one set of calibration results')
}
panel_off = panel.image
}else{stop("Whoops off_diag parameter is wrong")}
if(save_pics){ pdf(paste0(save_path,'calibration_pairplot',save_end,".pdf"))}
pairs(param_plot,
panel = panel_off,
diag.panel = panel.hist,
#pch = 19,
#cex = .3,
# col = rgb(1,0,0,.1),
labels = param_names,
upper.panel = NULL,
cex.lab = 1.5,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(2.3,1,0),
#col_hist = 'green',
las = 2,
main = title,
split_num = split_num)
if(include_legend){
legend('topright',legend_names,col = legend_cols,
pch = 19,inset = .13)
}
if(save_pics) dev.off()
}
gg_heat_pairs <- function(all_data,
ranges,
cols_to_use = 1:4,
scatter_alpha = 0.1,
col_names = c('A','B','C','D')){
both_col <- 'red3'
lhc_col <- 'deepskyblue'
rhic_col <- 'forestgreen'
my_dens <- function(data, mapping, ...) {
ggplot(data = data, mapping=mapping) +
geom_density(..., alpha = 0.7, size = 1.1) +
scale_fill_manual(values=c( both_col, lhc_col, rhic_col )) +
scale_color_manual(values=c( both_col,lhc_col, rhic_col))
}
my_scatter <- function(data,mapping,...){
ggplot(data = data, mapping = mapping) +
geom_jitter(alpha = scatter_alpha,size = .3) +
guides(col = guide_legend(override.aes = list(shape = 15,
size = 8,
alpha = 1),
label.theme = element_text(size = 12))) +
scale_fill_manual(values=c( both_col, lhc_col, rhic_col )) +
scale_color_manual(values=c( both_col,lhc_col, rhic_col)) +
theme(legend.title=element_blank())
}
p <- ggpairs(all_data, mapping = aes(color = Collider), columns = cols_to_use,
lower = list(continuous = my_scatter),
diag = list(continuous = my_dens),
upper = list(continuous = 'blank'),
columnLabels = col_names,
labeller = 'label_parsed'
#,legend = c(2,1)
)
for(i in 1:length(cols_to_use)){
for(j in 1:length(cols_to_use)){
if(j<=i){
p[i,j] <- p[i,j] + xlim(ranges[[j]][1],ranges[[j]][2]) +
theme(axis.text = element_text(size = 11.5))
}
}
}
#p <- p + theme(strip.text = element_text(size = 15))
#Remove yaxis on first plot, to remove confusion
#p[1,1] <- p[1,1] + theme(axis.text.y = element_blank(),
# axis.ticks = element_blank())
points_legend <- gglegend(my_scatter)
p[1,p$ncol] <- points_legend(all_data, ggplot2::aes(all_data[1,cols_to_use[1]],
all_data[1,cols_to_use[2]],
color = Collider))
#p[1,p$ncol-1] <- points_legend(all_data, ggplot2::aes(all_data[1,cols_to_use[1]],
# all_data[1,cols_to_use[2]],
# color = Collider))
#print(p + theme(strip.text = element_text(size = 15)))
print(p)
}
make_combined_pairplot <- function(save_lists,
labels,
ranges,
save_pics = FALSE,
save_path = '',
save_end = '',
cols_to_use = 1:5,
scatter_alpha = 0.1,
num_samples = 1E4,
str_param_to_use = 'transformed_params',
col_names = c('A','B','C','D'),
make_pdf = FALSE){
load(save_lists[1])
data_to_plot <- matrix(,0,ncol(save_list[[str_param_to_use]]))
if(length(save_lists)!=length(labels)){
stop('lists and labels not same length')
}
for(i in 1:length(save_lists)){
load(save_lists[i])
cur_data <- as.data.frame(save_list[[str_param_to_use]]) %>%
dplyr::sample_n(.,num_samples)
cur_data$Collider <- labels[i]
data_to_plot <- rbind(data_to_plot, cur_data)
}
if(save_pics){
if(make_pdf){
pdf(paste0(save_path,'combined_pairplot',save_end,'.pdf'))
}else{
png(paste0(save_path,'combined_pairplot',save_end,'.png'))
}
}
gg_heat_pairs(data_to_plot,
ranges = ranges,
cols_to_use = cols_to_use,
col_names = col_names,
scatter_alpha = scatter_alpha)
if(save_pics) dev.off()
}
plot_lines <- function(pred_dat,exp_dat,
med_pred_vec = NULL,
pT_col = 'pT',
exp_col = 'RAA_exp',
err_col_stat = 'exp_err_stat',
err_col_sys = 'exp_err_sys',
col_str = 'red',
col_pts = 'darkred',
all_col_pts = c('darkred','darkblue'),
all_col_strs = c('red','blue'),
alpha_val = 0.01,
delta = rep(0,dim(exp_dat)[1]),
include_legend = TRUE,
legend_loc = 'top_left',
include_med = FALSE,
add = FALSE,
include_arrows = TRUE,
cen_labels = NULL,
plot_title = "",
data_loc_name = "",
...){
if(!add){
#xlimits
pt_lim = min(exp_dat[,pT_col])
if(str_detect(plot_title,'AuAu200')){
pt_lim = c(pt_lim,20)
txt_x = 11.7
}else if(str_detect(plot_title,'PbPb2760')){
pt_lim = c(pt_lim,90)
#txt_x = 45 #for MATTER (?why)
txt_x = 27
}else if(str_detect(plot_title,'PbPb5020')){
pt_lim = c(pt_lim,100)
#txt_x = 45 #for MATTER (?why)
txt_x = 30
}else{
print('Warning: Using auto-generated tick marks for pT')
pt_lim = c(pt_lim,max(exp_dat[,pT_col]))
}
plot(exp_dat[,pT_col],pred_dat[,1],
cex = 0.5,
col = col_alpha(col_str,alpha_val),
type = 'l',
# ylim = c(min(exp_dat[,exp_col] - 2*exp_dat[,err_col_sys],
# exp_dat[,exp_col] - 2*exp_dat[,err_col_stat]),
# max(exp_dat[,exp_col] + 2*exp_dat[,err_col_sys],
# exp_dat[,exp_col] + 2*exp_dat[,err_col_stat])),
ylim = c(0,1.8),
xlim = pt_lim,
xlab = expression(p[T]~"(GeV)"),
ylab = expression(R[AA]),
cex.lab = 2,
mgp = c(2.3,1,0),
pch = 15,
yaxt = 'n',
xaxt = 'n',
...)
title(main = plot_title, line = -1.5, cex.main = 1.3, adj = .97)
box(lwd = 3)
#Add data location labels
text(txt_x, 1.47, paste0('Data from ',data_loc_name),cex = 1, font = 2)
#y axis ticks and labels
axis(side = 2, at = seq(0,1.5,by = 0.3), las = 1, lwd.ticks = 3, labels = NA)
axis(side = 2, at = seq(0,1.5,by = 0.3), las = 1,
cex.axis = 1.2, lwd = 0, line = -0.4)
#x axis ticks and labels
if(str_detect(plot_title,'AuAu')){
pt_ticks = seq(10,20,by = 2)
}else if(str_detect(plot_title,'PbPb')){
pt_ticks = seq(10,100, by = 10)
}else{
print('Warning: Using auto-generated tick marks for pT')
pt_ticks = seq(min(exp_dat[,pT_col]),max(exp_dat[,pT_col]), length.out = 5)
}
axis(side = 1, at = pt_ticks, lwd.ticks = 3, labels = NA)
axis(side = 1, at = pt_ticks, cex.axis = 1.2, lwd = 0, line = -0.4)
}else{
lines(exp_dat[,pT_col],pred_dat[,1],
cex = 0.5,
col = col_alpha(col_str,alpha_val),type = 'l')
}
#x_range = max(exp_dat[,pT_col]) - min(exp_dat[,pT_col])
#arrow_offset = x_range/130
arrow_offset = 0
for(i in 2:dim(pred_dat)[2]){
lines(exp_dat[,pT_col],pred_dat[,i] + delta,cex = 0.5,
col = col_alpha(col_str,alpha_val))
}
if(include_med){
lines(exp_dat[,pT_col], med_pred_vec,lty = 2, lwd = 2)
}
##############
### DEPRECIATED: NOW WE PUT THE POINTS AND ARROWS IN AFTER ALL LINES
###############
# if(!add){
# exp_pch = 15
# }else{
# exp_pch = 17
# }
#
# ## Add experimental points
# points(exp_dat[,pT_col],exp_dat[,exp_col],
# pch = exp_pch, col = col_pts)
#
# #ylim = c(0,1))
# if(include_arrows){
# arrow_stat_col = col_pts
# arrow_sys_col = col_pts
#
# #Statistical errors
# arrows(exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_stat],
# exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_stat],
# length=0.05, angle=90, code=3,col = arrow_stat_col)
#
# #Systematic errors
# arrows(exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_sys],
# exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_sys],
# length=0.05, angle=90, code=3, col = arrow_sys_col)
# }
if(include_legend){
legend_cex = 1.1
if(include_med){
legend(legend_loc, c(paste(cen_labels,'Centrality'),'Median Predictions'),
lty = c(1,1,2),lwd = c(2,2,2),col = c(all_col_strs,'black'),
box.lwd = 2, cex = legend_cex)
#Put the point shapes on top
legend(legend_loc, c(rep("",length(cen_labels)),""), col = all_col_pts,
pch = c(15,17,NA), bty='n', cex = legend_cex)
}else{
legend(legend_loc, paste(cen_labels,'Centrality'),lwd = 2, col = all_col_strs,
box.lwd = 2, cex = legend_cex)
#Put the point shapes on top
legend(legend_loc, rep("",length(cen_labels)), col = all_col_pts,
pch = c(15, 17), bty='n', box.lwd = 2, cex = legend_cex)
}
}
}
plot_draws_together <- function(draws,
train_mod,
rot_mat,
original_dset_list,
q_index = NA,
condition_on_q = FALSE,
dset_labels = NULL,
data_orig_labels = NULL,
cen_groups = NULL,
cen_labels = NULL,
RAA_med_vals = NULL,
med_pred_type = 'RAA',
col_str_vec = c('red','blue'),
col_pts_vec = c('darkred','darkblue'),
include_med = FALSE,
scale_mean_vec = NULL, #sd_vec
scale_sd_vec = NULL, #y_means
delta_list = NULL,
num_samples = 1E3,
title_end = "",
alpha_val = 0.01,
save_pics = FALSE,
save_path = "",
save_end = "",
include_legend = TRUE,
include_arrows = TRUE,
legend_spots = replicate(J,'top_left')){
if(is.null(scale_sd_vec)|is.null(scale_mean_vec)){
stop('Must set values for scale_sd_vec and scale_mean_vec. Try sd_vec and y_means')
}else if(dim(draws)[1]<num_samples){
stop('Num samples bigger than number of draws')
}else if(sum(do.call(c,lapply(cen_groups,length)) - length(col_str_vec))){
print('Centrality Groups:')
print(cen_group)
print('Color vector:')
print(col_str_vec)
stop("Color vec and centrality group lengths not all the same")
}
Y_pred = exp_predictions(theta = draws,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t()
Y_pred <- Y_pred[sample(1:dim(Y_pred)[1],num_samples),]
if(include_med){
if(med_pred_type=='emulator'){
if(condition_on_q){
q_mode <- density(draws[,q_index])$x[which.max(density(draws[,q_index])$y)]
q_width = 0.3
good_q <- which(draws[,q_index] > (q_mode - q_width) &
draws[,q_index] < (q_mode + q_width) )
draws <- draws[good_q, ]
}
(param_meds <- apply(draws,2,median) %>% t())
(med_pred <- exp_predictions(theta = param_meds,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t())
}else if(med_pred_type=='RAA'){
(med_pred = RAA_med_vals)
}else{
stop('med_pred_type must be one of "emulator", "RAA"')
}
print(paste0('Median prediction values are ',med_pred_type))
}else{
med_pred <- matrix(0,1,length(scale_mean_vec))
}
cur_col <- 1
for(j in 1:length(cen_groups)){
(cur_cen_labels = cen_labels[[j]])
(cur_group = names(cen_groups)[j])
(K_j <- length(cen_groups[[j]]))
(cur_data_loc_name = data_orig_labels[j])
exp_dset_list_j = vector('list',K_j)
for(k in 1:K_j){
(dset_index = cen_groups[[j]][k])
(cur_color <- col_str_vec[k])
(cur_pts_col <- col_pts_vec[k])
(num_pT <- dim(original_dset_list[[dset_index]])[1])
cur_dset <- t(Y_pred[,cur_col:(cur_col + num_pT - 1)])
if(med_pred_type=='emulator'){
(cur_med_pred <- med_pred[,cur_col:(cur_col + num_pT - 1)])
}else{
(cur_med_pred <- RAA_med_vals[[j]][[k]])
}
exp_dset <- cbind('pT' = original_dset_list[[dset_index]]$pT,
'RAA_exp' = original_dset_list[[dset_index]]$RAA_exp,
'exp_err_stat' = original_dset_list[[dset_index]]$Stat_err,
'exp_err_sys' = original_dset_list[[dset_index]]$Sys_err)
exp_dset_list_j[[k]] <- exp_dset
(cur_col = cur_col + num_pT)
#Plot 'em
if(k==1){
if(save_pics) pdf(paste0(save_path,dset_labels[j],save_end,'.pdf'))
plot_lines(pred_dat = cur_dset,
exp_dat = exp_dset,
med_pred_vec = cur_med_pred,
delta = delta_list[[dset_index]],
alpha_val = alpha_val,
include_legend = include_legend,
legend_loc = legend_spots[dset_index],
include_med = include_med,
col_str = cur_color,
all_col_strs = col_str_vec,
col_pts = cur_pts_col,
all_col_pts = col_pts_vec,
cen_labels = cur_cen_labels,
include_arrows = include_arrows,
plot_title = paste(cur_group,title_end),
data_loc_name = cur_data_loc_name
)
}else{
plot_lines(pred_dat = cur_dset,
exp_dat = exp_dset,
med_pred_vec = cur_med_pred,
delta = delta_list[[dset_index]],
alpha_val = alpha_val,
include_legend = include_legend,
legend_loc = legend_spots[dset_index],
include_med = include_med,
col_str = cur_color,
all_col_strs = col_str_vec,
col_pts = cur_pts_col,
all_col_pts = col_pts_vec,
cen_labels = cur_cen_labels,
include_arrows = include_arrows,
add = TRUE)
}
if(k==K_j){
#########
## Plot all the points on top of the lines
#########
pT_col = 'pT'
exp_col = 'RAA_exp'
err_col_stat = 'exp_err_stat'
err_col_sys = 'exp_err_sys'
#Loop over the datasets in this collision system
for(i in 1:K_j){
(col_pts <- col_pts_vec[i])
exp_dat = exp_dset_list_j[[i]]
if(i < K_j){
exp_pch = 15
}else{
exp_pch = 17
}
## Add experimental points
points(exp_dat[,pT_col],exp_dat[,exp_col],
pch = exp_pch, col = col_pts)
#ylim = c(0,1))
if(include_arrows){
arrow_stat_col = col_pts
arrow_sys_col = col_pts
#x_range = max(exp_dat[,pT_col]) - min(exp_dat[,pT_col])
#arrow_offset = x_range/130
arrow_offset = 0
#Statistical errors
arrows(exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_stat],
exp_dat[,pT_col]-arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_stat],
length=0.05, angle=90, code=3,col = arrow_stat_col)
#Systematic errors
arrows(exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] - exp_dat[,err_col_sys],
exp_dat[,pT_col]+arrow_offset, exp_dat[,exp_col] + exp_dat[,err_col_sys],
length=0.05, angle=90, code=3, col = arrow_sys_col)
}
}
if(save_pics) dev.off()
}
}#k loop
}#j loop
}
#Predict PCA vals
###DEPRECIATED######
plot_draws <- function(draws,
train_mod,
rot_mat,
original_dset_list,
include_med = FALSE,
dset_labels = NULL,
scale_mean_vec = NULL, #sd_vec
scale_sd_vec = NULL, #y_means
delta_list = NULL,
num_samples = 1E3,
title_end = "",
alpha_val = 0.01,
save_pics = FALSE,
save_path = "",
save_end = "",
include_legend = TRUE,
include_arrows = TRUE,
legend_spots = replicate(J,'top_left')){
if(is.null(scale_sd_vec)|is.null(scale_mean_vec)){
stop('Must set values for scale_sd_vec and scale_mean_vec. Try sd_vec and y_means')
}else if(dim(draws)[1]<num_samples){
stop('Num samples bigger than number of draws')
}
Y_pred = exp_predictions(theta = draws,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t() #%>%
#dplyr::slice(sample(1:dim(Y_pred)[1],num_samples))
# ##Predict the mu_Z, collect them
# colnames(draws) <- colnames(ranges)
# post_pred_mod <-lapply(train_mod, RobustGaSP::predict,
# # testing_trend = as.data.frame(cbind(rep(1,dim(draws)[1]),draws)),
# testing_input = as.data.frame(draws))
#
# pred_means <- lapply(post_pred_mod,function(x)x$mean) %>%
# do.call(cbind,.)
#
#
# #Rotate
# Y_pred_scaled <- pred_means %*%t(rot_mat)
#
# #Scale
#
# Y_pred <- sweep(Y_pred_scaled,2,scale_sd_vec,FUN = "*") %>%
# sweep(2,scale_mean_vec,FUN = '+')
# #Y_pred <- sweep(Y_pred_scaled,2,apply(scale_mat,2,mean),FUN = '+')
#
Y_pred <- Y_pred[sample(1:dim(Y_pred)[1],num_samples),]
if(include_med){
(param_meds <- apply(draws,2,median) %>% t())
(med_pred <- exp_predictions(theta = param_meds,
model_list = train_mod,
y_sd = scale_sd_vec,
y_means = scale_mean_vec,
Y_svd = comp_mod$Y_svd,
cov_extra = comp_mod$cov_extra,
q = length(train_mod))$mean %>% t())
}else{
med_pred <- matrix(0,1,length(scale_mean_vec))
}
cur_col <- 1
for(j in 1:length(original_dset_list)){
(num_pT <- dim(original_dset_list[[j]])[1])
cur_dset <- t(Y_pred[,cur_col:(cur_col + num_pT - 1)])
cur_med_pred <- med_pred[,cur_col:(cur_col + num_pT - 1)]
exp_dset <- cbind('pT' = original_dset_list[[j]]$pT,
'RAA_exp' = original_dset_list[[j]]$RAA_exp,
'exp_err_stat' = original_dset_list[[j]]$Stat_err,
'exp_err_sys' = original_dset_list[[j]]$Sys_err)
(cur_col = cur_col + num_pT)
#Plot 'em
if(save_pics) pdf(paste0(save_path,dset_labels[j],save_end,'.pdf'))
plot_lines(pred_dat = cur_dset,
exp_dat = exp_dset,
med_pred_vec = cur_med_pred,
delta = delta_list[[j]],
main = paste(dset_labels[j],title_end),
alpha_val = alpha_val,
include_legend = include_legend,
legend_loc = legend_spots[j],
include_med = include_med)
if(save_pics) dev.off()
}
}
plot_discrep_fun <- function(discrep_list,
ell_mat,
lambda_mat,
pT_train,
pT_pred,
alpha = 2,
include_pts = TRUE,
dset_labels = dset_strings,
save_pics = FALSE,
save_path = "",
save_suffix = ""){
mu_delt <- sig_delt <- vector('list',length(discrep_list))
for(j in 1:length(discrep_list)){
y = discrep_list[[j]]
x_train = matrix(pT_train[[j]])
x_pred = matrix(sort(c(pT_train[[j]],pT_pred[[j]])))
ell_j = mean(ell_mat[,j])
lambda_j = mean(lambda_mat[,j])
sig_22 = cov_mat_multi(x_train,
x_train,
ell_vec = ell_j,
lambda = lambda_j,
alpha_vec = alpha,
nugget = 1E-6)
sig_22_inv <- chol2inv(chol(sig_22))
sig_12 = cov_mat_multi(x_pred,
x_train,
ell_vec = ell_j,
lambda = lambda_j,
alpha_vec = alpha,
nugget = 1E-6)
sig_21 = t(sig_12)
sig_11 = cov_mat_multi(x_pred,
x_pred,
ell_vec = ell_j,
lambda = lambda_j,
alpha_vec = alpha,
nugget = 1E-6)
mu_delt[[j]] <- sig_12%*%sig_22_inv%*%y
sig_delt[[j]] <- diag(sig_11 - sig_12%*%sig_22_inv%*%sig_21)
if(save_pics)pdf(paste0(save_path,"discrep_",dset_labels[j],save_suffix,".pdf"))
plot(x_pred,mu_delt[[j]],type = 'l',
# ylim = c(min(mu_delt[[j]] - 2*sqrt(sig_delt[[j]])),
# max(mu_delt[[j]] + 2*sqrt(sig_delt[[j]]))))
ylim = c(-.23,.23),
xlab = expression(p[T]~"(GeV)"),
#ylab = expression(delta[j]),
main = paste0("Discrepancy for ",dset_labels[j]),
cex.lab = 2,
cex.main = 2,
ylab = "")
title(ylab = expression(delta[j]),cex.lab = 2,mgp=c(2,1,0))
lines(x_pred,mu_delt[[j]] - 2*sqrt(sig_delt[[j]]),col = 'blue',
lty = 2)
lines(x_pred,mu_delt[[j]] + 2*sqrt(sig_delt[[j]]),col = 'blue',
lty = 2)
abline(h=0)
if(include_pts){
points(x_train,y)
}
if(save_pics) dev.off()
}
invisible(list(mu_delt = mu_delt,sig_delt = sig_delt))
}
###########
##Validation Plot
##########
##Requires:
#Holdout point
#Design
#Train dset
# V
# y_sd
# y_mean
##Ugh...should change this to use the new prediction function
predict_holdout <- function(holdout,
design = comp_mod$all_data$scaled_d,
Y_scaled = comp_mod$Y_final,
#Y_orig = Y,
y_sd_cur = comp_mod$y_sd,
y_mean_cur = comp_mod$y_means,
q = length(comp_mod$train_mods), plotit = FALSE,
verbose = FALSE,
cover_level = 95){
train_d <- design[-holdout, ]
test_d <- design[holdout, ]
train_Y <- Y_scaled[-holdout, ]
Y_orig <- sweep(Y_scaled,2,y_sd_cur,"*")%>%
sweep(2,y_mean_cur, "+")
test_Y <- Y_orig[holdout, ]
V_train <- svd(train_Y)$v[ , 1:q]
train_Z = as.matrix(train_Y)%*%V_train
sink("NUL")
train_mod <- lapply(as.data.frame(train_Z),rgasp,design = train_d,
kernel_type = 'pow_exp')
sink()
test_mod <- lapply(train_mod,RobustGaSP::predict,testing_input = test_d)
pred_Z <- lapply(test_mod,function(x)x$mean) %>%
do.call(c,.) %>%
t()
pred_err_Z <- lapply(test_mod,function(x)x$sd^2) %>%
do.call(c,.)
pred_Y <- pred_Z %*% t(V_train) %*% diag(y_sd_cur) + y_mean_cur
pred_err_Y <- diag(y_sd_cur) %*% V_train %*% diag(pred_err_Z) %*% t(V_train) %*% diag(y_sd_cur) %>%
diag()
if(cover_level == 95){
sd_mult = 2
}else if(cover_level == 60){
sd_mult = 1
}else{
stop('Must pick 95% or 60% for cover level')
}
if(plotit){
plot(as.numeric(test_Y),as.numeric(pred_Y),pch = 19,cex = .5,
xlab = 'Holdout Values',
ylab = 'Predicted Values',
main = paste0('Emulator Prediction, Holdout ',holdout),
cex.lab = 2,
cex.axis = 1.3,
cex.main = 1.4,
mgp = c(2.4,1,0),
ylim = c(min(as.numeric(pred_Y) - sd_mult*sqrt(pred_err_Y)),
max(as.numeric(pred_Y) + sd_mult*sqrt(pred_err_Y))))
arrows(as.numeric(test_Y), as.numeric(pred_Y) - sd_mult*sqrt(pred_err_Y),
as.numeric(test_Y), as.numeric(pred_Y) + sd_mult*sqrt(pred_err_Y),
length=0, angle=90, code=3)
abline(a = 0,b = 1)
}
good_pred_95 <- test_Y < as.numeric(pred_Y) + 2*sqrt(pred_err_Y) &
test_Y > as.numeric(pred_Y) - 2*sqrt(pred_err_Y)
good_pred_60 <- test_Y < as.numeric(pred_Y) + sqrt(pred_err_Y) &
test_Y > as.numeric(pred_Y) - sqrt(pred_err_Y)
return(list(mean_cover_95 = mean(good_pred_95), mean_cover_60 = mean(good_pred_60),
mean_width = mean(4*sqrt(pred_err_Y))))
}
collect_all_holdouts <- function(D_c_theta = comp_mod$all_data$scaled_d,
Y_scaled = comp_mod$Y_final,
#Y_orig = Y,
y_sd_cur = comp_mod$y_sd,
y_mean_cur = comp_mod$y_means,
q = length(comp_mod$train_mods)){
n_holdouts <- nrow(D_c_theta)
cover_95 <- cover_60 <- widths <- numeric(n_holdouts)
for(h in 1:n_holdouts){
invisible(pred_hold_h <- predict_holdout(holdout = h,
design = D_c_theta,
Y_scaled = Y_scaled,
y_sd_cur = y_sd_cur,
y_mean_cur = y_mean_cur,
q = q))
cover_95[h] <- pred_hold_h$mean_cover_95
cover_60[h] <- pred_hold_h$mean_cover_60
widths[h] <- pred_hold_h$mean_width
flush.console()
cat("\r FINISHED HOLDOUT ", h ,'/',n_holdouts)
}
return(list(cover_95 = cover_95, cover_60 = cover_60, widths = widths))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sc_workflow.R
\name{create_report}
\alias{create_report}
\title{create_report}
\usage{
create_report(sample_name, outdir, r1 = "NA", r2 = "NA", outfq = "NA",
read_structure = list(bs1 = 0, bl1 = 0, bs2 = 0, bl2 = 0, us = 0, ul = 0),
filter_settings = list(rmlow = TRUE, rmN = TRUE, minq = 20, numbq = 2),
align_bam = "NA", genome_index = "NA", map_bam = "NA",
exon_anno = "NA", stnd = TRUE, fix_chr = FALSE, barcode_anno = "NA",
max_mis = 1, UMI_cor = 1, gene_fl = FALSE, organism, gene_id_type)
}
\arguments{
\item{sample_name}{sample name}
\item{outdir}{output folder}
\item{r1}{file path of read1}
\item{r2}{file path of read2 default to be NULL}
\item{outfq}{file path of the output of \code{sc_trim_barcode}}
\item{read_structure}{a list contains read structure configuration. For more help see `?sc_trim_barcode`}
\item{filter_settings}{a list contains read filter settings for more help see `?sc_trim_barcode`}
\item{align_bam}{the aligned bam file}
\item{genome_index}{genome index used for alignment}
\item{map_bam}{the mapped bam file}
\item{exon_anno}{the gff exon annotation used. Can have multiple files}
\item{stnd}{whether to perform strand specific mapping}
\item{fix_chr}{add `chr` to chromosome names, fix inconsistant names.}
\item{barcode_anno}{cell barcode annotation file path.}
\item{max_mis}{maximum mismatch allowed in barcode. Default to be 1}
\item{UMI_cor}{correct UMI sequence error: 0 means no correction, 1 means simple correction and merge UMI with distance 1.}
\item{gene_fl}{whether to remove low abundant gene count. Low abundant is defined as only one copy of one UMI for this gene}
\item{organism}{the organism of the data. List of possible names can be retrieved using the function
`listDatasets`from `biomaRt` package. (i.e `mmusculus_gene_ensembl` or `hsapiens_gene_ensembl`)}
\item{gene_id_type}{gene id type of the data A possible list of ids can be retrieved using the function `listAttributes` from `biomaRt` package.
the commonly used id types are `external_gene_name`, `ensembl_gene_id` or `entrezgene`}
}
\value{
no return
}
\description{
create an HTML report using data generated by proprocessing step.
}
\examples{
\dontrun{
create_report(sample_name="sample_001",
outdir="output_dir_of_scPipe",
r1="read1.fq",
r2="read2.fq",
outfq="trim.fq",
read_structure=list(bs1=-1, bl1=2, bs2=6, bl2=8, us=0, ul=6),
filter_settings=list(rmlow=TRUE, rmN=TRUE, minq=20, numbq=2),
align_bam="align.bam",
genome_index="mouse.index",
map_bam="aligned.mapped.bam",
exon_anno="exon_anno.gff3",
stnd=TRUE,
fix_chr=FALSE,
barcode_anno="cell_barcode.csv",
max_mis=1,
UMI_cor=1,
gene_fl=FALSE,
organism="mmusculus_gene_ensembl",
gene_id_type="ensembl_gene_id")
}
}
|
/man/create_report.Rd
|
no_license
|
Bioinfomatics/scPipe
|
R
| false | true | 2,928 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sc_workflow.R
\name{create_report}
\alias{create_report}
\title{create_report}
\usage{
create_report(sample_name, outdir, r1 = "NA", r2 = "NA", outfq = "NA",
read_structure = list(bs1 = 0, bl1 = 0, bs2 = 0, bl2 = 0, us = 0, ul = 0),
filter_settings = list(rmlow = TRUE, rmN = TRUE, minq = 20, numbq = 2),
align_bam = "NA", genome_index = "NA", map_bam = "NA",
exon_anno = "NA", stnd = TRUE, fix_chr = FALSE, barcode_anno = "NA",
max_mis = 1, UMI_cor = 1, gene_fl = FALSE, organism, gene_id_type)
}
\arguments{
\item{sample_name}{sample name}
\item{outdir}{output folder}
\item{r1}{file path of read1}
\item{r2}{file path of read2 default to be NULL}
\item{outfq}{file path of the output of \code{sc_trim_barcode}}
\item{read_structure}{a list contains read structure configuration. For more help see `?sc_trim_barcode`}
\item{filter_settings}{a list contains read filter settings for more help see `?sc_trim_barcode`}
\item{align_bam}{the aligned bam file}
\item{genome_index}{genome index used for alignment}
\item{map_bam}{the mapped bam file}
\item{exon_anno}{the gff exon annotation used. Can have multiple files}
\item{stnd}{whether to perform strand specific mapping}
\item{fix_chr}{add `chr` to chromosome names, fix inconsistant names.}
\item{barcode_anno}{cell barcode annotation file path.}
\item{max_mis}{maximum mismatch allowed in barcode. Default to be 1}
\item{UMI_cor}{correct UMI sequence error: 0 means no correction, 1 means simple correction and merge UMI with distance 1.}
\item{gene_fl}{whether to remove low abundant gene count. Low abundant is defined as only one copy of one UMI for this gene}
\item{organism}{the organism of the data. List of possible names can be retrieved using the function
`listDatasets`from `biomaRt` package. (i.e `mmusculus_gene_ensembl` or `hsapiens_gene_ensembl`)}
\item{gene_id_type}{gene id type of the data A possible list of ids can be retrieved using the function `listAttributes` from `biomaRt` package.
the commonly used id types are `external_gene_name`, `ensembl_gene_id` or `entrezgene`}
}
\value{
no return
}
\description{
create an HTML report using data generated by proprocessing step.
}
\examples{
\dontrun{
create_report(sample_name="sample_001",
outdir="output_dir_of_scPipe",
r1="read1.fq",
r2="read2.fq",
outfq="trim.fq",
read_structure=list(bs1=-1, bl1=2, bs2=6, bl2=8, us=0, ul=6),
filter_settings=list(rmlow=TRUE, rmN=TRUE, minq=20, numbq=2),
align_bam="align.bam",
genome_index="mouse.index",
map_bam="aligned.mapped.bam",
exon_anno="exon_anno.gff3",
stnd=TRUE,
fix_chr=FALSE,
barcode_anno="cell_barcode.csv",
max_mis=1,
UMI_cor=1,
gene_fl=FALSE,
organism="mmusculus_gene_ensembl",
gene_id_type="ensembl_gene_id")
}
}
|
# analysis of cortex transcripts
# 2017-06-06
# load data ####
# load libraries
library(tidyverse)
library(tidytext)
library(stringr)
library(igraph)
library(ggraph)
# load transcript data
cortex <- read_rds("data/cortex.rda")
# clean data ####
# get count of words by episode
cortex_words <- cortex %>%
unnest_tokens(word, line) %>%
anti_join(stop_words) %>%
count(ep_num, ep_title, word) %>%
ungroup()
# count total words per podcast
total_words <- cortex_words %>%
group_by(ep_num) %>%
summarise(total = sum(n))
# join individual word count and total word count
# get tf_idf by podcast
cortex_words <- left_join(cortex_words, total_words) %>%
bind_tf_idf(word, ep_num, n)
cortex_word_plot <- cortex_words %>%
arrange(desc(tf_idf)) %>%
mutate(word = factor(word, levels = rev(unique(word))),
ep_title = factor(ep_title, levels = ep_title))
cortex_word_plot %>%
group_by(ep_num) %>%
top_n(10) %>%
ungroup() %>%
ggplot(aes(x = word, y=tf_idf)) +
geom_col(show.legend=FALSE) +
coord_flip() +
labs(x = "tf-idf",
title = "Most Important Words by Cortex Episode",
subtitle = "Measured by tf-idf") +
facet_wrap(~ep_title, scales = "free_y")+
theme(legend.position = "none",
axis.title.y = element_blank())
# sentiment analysis ####
cortex_ep <- cortex %>%
group_by(ep_num, ep_title) %>%
unnest_tokens(word, line) %>%
ungroup() %>%
select(-line_num)
bingnegative <- get_sentiments("bing") %>%
filter(sentiment == "negative")
bingpositive <- get_sentiments("bing") %>%
filter(sentiment == "positive")
cortex_ep_wordcounts <- cortex_ep %>%
group_by(ep_num, ep_title) %>%
summarise(words = n())
cortex_negative <- cortex_ep %>%
semi_join(bingnegative) %>%
group_by(ep_num, ep_title) %>%
summarize(negativewords = n()) %>%
left_join(cortex_ep_wordcounts, by = c("ep_num", "ep_title")) %>%
ungroup() %>%
mutate(ratio = negativewords/words,
relative_neg = mean(ratio) - ratio) %>%
ungroup()
cortex_positive <- cortex_ep %>%
semi_join(bingpositive) %>%
group_by(ep_num, ep_title) %>%
summarize(positivewords = n()) %>%
left_join(cortex_ep_wordcounts, by = c("ep_num", "ep_title")) %>%
ungroup() %>%
mutate(ratio = positivewords/words,
relative_pos = mean(ratio) - ratio) %>%
ungroup()
ggplot(cortex_negative, aes(x = ep_num, y = ratio))+
geom_bar(stat = "identity", fill = "firebrick")+
geom_smooth(span = .3, se = FALSE, color = "grey64")
ggplot(cortex_positive, aes(x = ep_num, y = ratio))+
geom_bar(stat = "identity", fill = "green4")+
geom_smooth(span = .3, se = FALSE, color = "grey64")
# alternative sentiment #####
cortex_sentiment <- cortex %>%
unnest_tokens(word, line) %>%
inner_join(get_sentiments("bing")) %>%
group_by(ep_num, ep_title, line_num, sentiment) %>%
summarise(total = n()) %>%
spread(sentiment, total, fill = 0) %>%
ungroup() %>%
group_by(ep_num, ep_title) %>%
mutate(sentiment = positive - negative,
relative = sentiment - mean(sentiment),
line_group = ntile(line_num, 100)) %>%
group_by(ep_num, ep_title, line_group) %>%
summarise(sentiment = sum(sentiment)) %>%
ungroup() %>%
mutate(index = row_number(),
ep_title = factor(ep_title, levels = cortex_ep_wordcounts$ep_title))
ggplot(cortex_sentiment, aes(x = index, y = sentiment, fill = ep_title))+
geom_col()+
#geom_smooth(se = FALSE, span = .3)+
theme(legend.position = "none") +
facet_wrap(~ep_title, scales = "free_x")
# ngrams ####
cortex_bigrams <- cortex %>%
group_by(ep_num, ep_title) %>%
summarise(text = paste(line, collapse = "")) %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
separate(bigram, c("word1", "word2"), sep = " ") %>%
filter(!word1 %in% stop_words$word) %>%
filter(!word2 %in% stop_words$word) %>%
filter(word1 != "yeah" & word2 != "yeah") %>%
filter(word1 != "code" & word2 != "cortex") %>%
filter(word1 != "blue" & word2 != "apron") %>%
filter(word1 != "ten" & word2 != "percent") %>%
unite(bigram, word1, word2, sep = " ") %>%
mutate(ep_title = factor(ep_title, levels = cortex_ep_wordcounts$ep_title)) %>%
count(ep_title, bigram, sort = TRUE)
total_bigrams <- cortex_bigrams %>%
group_by(ep_title) %>%
summarise(total = sum(n))
# join individual word count and total word count
# get tf_idf by podcast
cortex_bigram_tf_idf <- left_join(cortex_bigrams, total_bigrams) %>%
bind_tf_idf(bigram, ep_title, n)
cortex_bigram_plot <- cortex_bigrams_tf_idf %>%
arrange(desc(tf_idf)) %>%
mutate(bigram = factor(bigram, levels = rev(unique(bigram))))
cortex_bigram_plot %>%
group_by(ep_title) %>%
top_n(10) %>%
ungroup() %>%
ggplot(aes(x = bigram, y=tf_idf)) +
geom_col(show.legend=FALSE) +
coord_flip() +
labs(x = "tf-idf",
title = "Most Important Bigrams by Cortex Episode",
subtitle = "Measured by tf-idf") +
facet_wrap(~ep_title, scales = "free_y")+
theme(legend.position = "none",
axis.title.y = element_blank())
bigram_graph <- cortex %>%
group_by(ep_num, ep_title) %>%
summarise(text = paste(line, collapse = "")) %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
separate(bigram, c("word1", "word2"), sep = " ") %>%
filter(!word1 %in% stop_words$word) %>%
filter(!word2 %in% stop_words$word) %>%
filter(word1 != "yeah" & word2 != "yeah") %>%
filter(word1 != "code" & word2 != "cortex") %>%
filter(word1 != "blue" & word2 != "apron") %>%
filter(word1 != "ten" & word2 != "percent") %>%
filter(word1 != "credit" & word2 != "card") %>%
filter(word1 != "card" & word2 != "required") %>%
filter(word1 != "real" & word2 != "afm") %>%
filter(word1 != "text" & word2 != "expander") %>%
filter(word1 != "pdf" & word2 != "pen") %>%
filter(word1 != "ten" & word2 != "percent") %>%
filter(word1 != "30" & word2 != "day") %>%
filter(word1 != "offer" & word2 != "code") %>%
filter(word1 != "fresh" & word2 != "books") %>%
filter(word1 != "free" & word2 != "trial") %>%
filter(word1 != "uni" & word2 != "box") %>%
filter(word1 != "risk" & word2 != "free") %>%
filter(word1 != "completely" & word2 != "risk") %>%
filter(word1 != "movement" & word2 != "watches") %>%
filter(word1 != "incredible" & word2 != "home") %>%
filter(word1 != "home" & word2 != "cooked") %>%
filter(word1 != "cooked" & word2 != "meals") %>%
filter(word1 != "super" & word2 != "fast") %>%
filter(word1 != "super" & word2 != "easy") %>%
filter(word1 != "super" & word2 != "simple") %>%
filter(word1 != "freshbooks" & word2 != "customers") %>%
filter(word1 != "conditions" & word2 != "apply") %>%
filter(word1 != "professionally" & word2 != "designed") %>%
filter(word1 != "start" & word2 != "building") %>%
filter(word1 != "live" & word2 != "chat") %>%
filter(word1 != "continued" & word2 != "support") %>%
filter(word1 != "fifty" & word2 != "dollars") %>%
filter(word1 != "hundred" & word2 != "dollars") %>%
filter(word1 != "perfect" & word2 != "domain") %>%
filter(word1 != "domain" & word2 != "dames") %>%
filter(word2 != "minutes") %>%
filter(word1 != "10" & word2 != "people") %>%
filter(word1 != "week's" & word2 != "episode") %>%
filter(word1 != "today's" & word2 != "episode") %>%
filter(word1 != "highly" & word2 != "recommend") %>%
filter(word1 != "commerce" & word2 != "platform") %>%
filter(word1 != "relay" & word2 != "fm") %>%
count(word1, word2, sort = TRUE) %>%
filter(n > 10) %>%
graph_from_data_frame()
set.seed(51)
a <- grid::arrow(type = "closed", length = unit(.15, "inches"))
ggraph(bigram_graph, layout = "fr") +
geom_edge_link(aes(edge_alpha = n), show.legend = FALSE,
arrow = a, end_cap = circle(.03, 'inches')) +
geom_node_point(how.legend = FALSE) +
geom_node_point(aes(size = n), color = "lightblue", size = 3) +
geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
theme_void()
|
/R/cortex.R
|
no_license
|
alspur/tidy_pod
|
R
| false | false | 7,935 |
r
|
# analysis of cortex transcripts
# 2017-06-06
# load data ####
# load libraries
library(tidyverse)
library(tidytext)
library(stringr)
library(igraph)
library(ggraph)
# load transcript data
cortex <- read_rds("data/cortex.rda")
# clean data ####
# get count of words by episode
cortex_words <- cortex %>%
unnest_tokens(word, line) %>%
anti_join(stop_words) %>%
count(ep_num, ep_title, word) %>%
ungroup()
# count total words per podcast
total_words <- cortex_words %>%
group_by(ep_num) %>%
summarise(total = sum(n))
# join individual word count and total word count
# get tf_idf by podcast
cortex_words <- left_join(cortex_words, total_words) %>%
bind_tf_idf(word, ep_num, n)
cortex_word_plot <- cortex_words %>%
arrange(desc(tf_idf)) %>%
mutate(word = factor(word, levels = rev(unique(word))),
ep_title = factor(ep_title, levels = ep_title))
cortex_word_plot %>%
group_by(ep_num) %>%
top_n(10) %>%
ungroup() %>%
ggplot(aes(x = word, y=tf_idf)) +
geom_col(show.legend=FALSE) +
coord_flip() +
labs(x = "tf-idf",
title = "Most Important Words by Cortex Episode",
subtitle = "Measured by tf-idf") +
facet_wrap(~ep_title, scales = "free_y")+
theme(legend.position = "none",
axis.title.y = element_blank())
# sentiment analysis ####
cortex_ep <- cortex %>%
group_by(ep_num, ep_title) %>%
unnest_tokens(word, line) %>%
ungroup() %>%
select(-line_num)
bingnegative <- get_sentiments("bing") %>%
filter(sentiment == "negative")
bingpositive <- get_sentiments("bing") %>%
filter(sentiment == "positive")
cortex_ep_wordcounts <- cortex_ep %>%
group_by(ep_num, ep_title) %>%
summarise(words = n())
cortex_negative <- cortex_ep %>%
semi_join(bingnegative) %>%
group_by(ep_num, ep_title) %>%
summarize(negativewords = n()) %>%
left_join(cortex_ep_wordcounts, by = c("ep_num", "ep_title")) %>%
ungroup() %>%
mutate(ratio = negativewords/words,
relative_neg = mean(ratio) - ratio) %>%
ungroup()
cortex_positive <- cortex_ep %>%
semi_join(bingpositive) %>%
group_by(ep_num, ep_title) %>%
summarize(positivewords = n()) %>%
left_join(cortex_ep_wordcounts, by = c("ep_num", "ep_title")) %>%
ungroup() %>%
mutate(ratio = positivewords/words,
relative_pos = mean(ratio) - ratio) %>%
ungroup()
ggplot(cortex_negative, aes(x = ep_num, y = ratio))+
geom_bar(stat = "identity", fill = "firebrick")+
geom_smooth(span = .3, se = FALSE, color = "grey64")
ggplot(cortex_positive, aes(x = ep_num, y = ratio))+
geom_bar(stat = "identity", fill = "green4")+
geom_smooth(span = .3, se = FALSE, color = "grey64")
# alternative sentiment #####
cortex_sentiment <- cortex %>%
unnest_tokens(word, line) %>%
inner_join(get_sentiments("bing")) %>%
group_by(ep_num, ep_title, line_num, sentiment) %>%
summarise(total = n()) %>%
spread(sentiment, total, fill = 0) %>%
ungroup() %>%
group_by(ep_num, ep_title) %>%
mutate(sentiment = positive - negative,
relative = sentiment - mean(sentiment),
line_group = ntile(line_num, 100)) %>%
group_by(ep_num, ep_title, line_group) %>%
summarise(sentiment = sum(sentiment)) %>%
ungroup() %>%
mutate(index = row_number(),
ep_title = factor(ep_title, levels = cortex_ep_wordcounts$ep_title))
ggplot(cortex_sentiment, aes(x = index, y = sentiment, fill = ep_title))+
geom_col()+
#geom_smooth(se = FALSE, span = .3)+
theme(legend.position = "none") +
facet_wrap(~ep_title, scales = "free_x")
# ngrams ####
cortex_bigrams <- cortex %>%
group_by(ep_num, ep_title) %>%
summarise(text = paste(line, collapse = "")) %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
separate(bigram, c("word1", "word2"), sep = " ") %>%
filter(!word1 %in% stop_words$word) %>%
filter(!word2 %in% stop_words$word) %>%
filter(word1 != "yeah" & word2 != "yeah") %>%
filter(word1 != "code" & word2 != "cortex") %>%
filter(word1 != "blue" & word2 != "apron") %>%
filter(word1 != "ten" & word2 != "percent") %>%
unite(bigram, word1, word2, sep = " ") %>%
mutate(ep_title = factor(ep_title, levels = cortex_ep_wordcounts$ep_title)) %>%
count(ep_title, bigram, sort = TRUE)
total_bigrams <- cortex_bigrams %>%
group_by(ep_title) %>%
summarise(total = sum(n))
# join individual word count and total word count
# get tf_idf by podcast
cortex_bigram_tf_idf <- left_join(cortex_bigrams, total_bigrams) %>%
bind_tf_idf(bigram, ep_title, n)
cortex_bigram_plot <- cortex_bigrams_tf_idf %>%
arrange(desc(tf_idf)) %>%
mutate(bigram = factor(bigram, levels = rev(unique(bigram))))
cortex_bigram_plot %>%
group_by(ep_title) %>%
top_n(10) %>%
ungroup() %>%
ggplot(aes(x = bigram, y=tf_idf)) +
geom_col(show.legend=FALSE) +
coord_flip() +
labs(x = "tf-idf",
title = "Most Important Bigrams by Cortex Episode",
subtitle = "Measured by tf-idf") +
facet_wrap(~ep_title, scales = "free_y")+
theme(legend.position = "none",
axis.title.y = element_blank())
bigram_graph <- cortex %>%
group_by(ep_num, ep_title) %>%
summarise(text = paste(line, collapse = "")) %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
separate(bigram, c("word1", "word2"), sep = " ") %>%
filter(!word1 %in% stop_words$word) %>%
filter(!word2 %in% stop_words$word) %>%
filter(word1 != "yeah" & word2 != "yeah") %>%
filter(word1 != "code" & word2 != "cortex") %>%
filter(word1 != "blue" & word2 != "apron") %>%
filter(word1 != "ten" & word2 != "percent") %>%
filter(word1 != "credit" & word2 != "card") %>%
filter(word1 != "card" & word2 != "required") %>%
filter(word1 != "real" & word2 != "afm") %>%
filter(word1 != "text" & word2 != "expander") %>%
filter(word1 != "pdf" & word2 != "pen") %>%
filter(word1 != "ten" & word2 != "percent") %>%
filter(word1 != "30" & word2 != "day") %>%
filter(word1 != "offer" & word2 != "code") %>%
filter(word1 != "fresh" & word2 != "books") %>%
filter(word1 != "free" & word2 != "trial") %>%
filter(word1 != "uni" & word2 != "box") %>%
filter(word1 != "risk" & word2 != "free") %>%
filter(word1 != "completely" & word2 != "risk") %>%
filter(word1 != "movement" & word2 != "watches") %>%
filter(word1 != "incredible" & word2 != "home") %>%
filter(word1 != "home" & word2 != "cooked") %>%
filter(word1 != "cooked" & word2 != "meals") %>%
filter(word1 != "super" & word2 != "fast") %>%
filter(word1 != "super" & word2 != "easy") %>%
filter(word1 != "super" & word2 != "simple") %>%
filter(word1 != "freshbooks" & word2 != "customers") %>%
filter(word1 != "conditions" & word2 != "apply") %>%
filter(word1 != "professionally" & word2 != "designed") %>%
filter(word1 != "start" & word2 != "building") %>%
filter(word1 != "live" & word2 != "chat") %>%
filter(word1 != "continued" & word2 != "support") %>%
filter(word1 != "fifty" & word2 != "dollars") %>%
filter(word1 != "hundred" & word2 != "dollars") %>%
filter(word1 != "perfect" & word2 != "domain") %>%
filter(word1 != "domain" & word2 != "dames") %>%
filter(word2 != "minutes") %>%
filter(word1 != "10" & word2 != "people") %>%
filter(word1 != "week's" & word2 != "episode") %>%
filter(word1 != "today's" & word2 != "episode") %>%
filter(word1 != "highly" & word2 != "recommend") %>%
filter(word1 != "commerce" & word2 != "platform") %>%
filter(word1 != "relay" & word2 != "fm") %>%
count(word1, word2, sort = TRUE) %>%
filter(n > 10) %>%
graph_from_data_frame()
set.seed(51)
a <- grid::arrow(type = "closed", length = unit(.15, "inches"))
ggraph(bigram_graph, layout = "fr") +
geom_edge_link(aes(edge_alpha = n), show.legend = FALSE,
arrow = a, end_cap = circle(.03, 'inches')) +
geom_node_point(how.legend = FALSE) +
geom_node_point(aes(size = n), color = "lightblue", size = 3) +
geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
theme_void()
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{sumboxmktCnt_trade}
\alias{sumboxmktCnt_trade}
\title{Number of Monte Carlo Simulations Performed in "Summary" Tab for Tariffs}
\format{
A data frame with 24 rows and 3 variables
\describe{
\item{Outcome}{Consumer Harm, Domestic Firm Benefit, Foreign Firm Harm, Industry Price Change, Net Domestic Harm, Net Total Harm, Domestic Firm Price Change, Foreign Firm Price Change}
\item{Cnt}{number of tariffs simulated}
\item{tariffThresh}{tariff threshold in percent (10--30)}
}
}
\usage{
sumboxmktCnt_trade
}
\description{
A dataset containing the information necessary to calculate the number of tariffs
used to generate the plots for the Summary tab of Numerical Simulations for Tariffs.
}
\references{
Taragin, C., & Loudermilk, M. (2019). Using measures of competitive harm for optimal screening of horizontal mergers. mimeo.\doi{10.13140/RG.2.2.30872.85760/1}.
}
\keyword{datasets}
|
/man/sumboxmktCnt_trade.Rd
|
no_license
|
cran/competitiontoolbox
|
R
| false | true | 1,021 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{sumboxmktCnt_trade}
\alias{sumboxmktCnt_trade}
\title{Number of Monte Carlo Simulations Performed in "Summary" Tab for Tariffs}
\format{
A data frame with 24 rows and 3 variables
\describe{
\item{Outcome}{Consumer Harm, Domestic Firm Benefit, Foreign Firm Harm, Industry Price Change, Net Domestic Harm, Net Total Harm, Domestic Firm Price Change, Foreign Firm Price Change}
\item{Cnt}{number of tariffs simulated}
\item{tariffThresh}{tariff threshold in percent (10--30)}
}
}
\usage{
sumboxmktCnt_trade
}
\description{
A dataset containing the information necessary to calculate the number of tariffs
used to generate the plots for the Summary tab of Numerical Simulations for Tariffs.
}
\references{
Taragin, C., & Loudermilk, M. (2019). Using measures of competitive harm for optimal screening of horizontal mergers. mimeo.\doi{10.13140/RG.2.2.30872.85760/1}.
}
\keyword{datasets}
|
## File Name: plot.lsdm.R
## File Version: 0.02
plot.lsdm <- function(x, ...)
{
graphics::matplot( x=x$theta, y=t(x$attr.curves), xlab=expression(theta),
ylab="Attribute response curve", ylim=c(0,1), ... )
}
|
/R/plot.lsdm.R
|
no_license
|
cran/sirt
|
R
| false | false | 231 |
r
|
## File Name: plot.lsdm.R
## File Version: 0.02
plot.lsdm <- function(x, ...)
{
graphics::matplot( x=x$theta, y=t(x$attr.curves), xlab=expression(theta),
ylab="Attribute response curve", ylim=c(0,1), ... )
}
|
#for loop for changing MDA coverage in the first village
#MDA_eff_hm
#MDA success on homogeniety vs coverage
#20190405
#outcome is the achievement of <1/1000/year in a year starting with the end of the 3rd MDA round
#see #scenario tag for things to change in each scenario
#x axis variable: homogen, [0 to 100] %
#y axis variable: cmda_2, [0 to 80] %, coverage of MDA in second village
#z: cmda_1, [70, 80, 90] %
setwd("~/OneDrive/MORU/Projects/TCE_MDA effect/MDA_eff_hm/") #mac
library(deSolve)
library(shiny)
library(TSA)
library(Rcpp)
library(stringr)
library(lattice)
#new formula with Ricardo 20190805
sourceCpp("functions_latest/modGMS_seas.cpp", rebuild = TRUE)
source("functions_latest/no longer app.R")
# sourceCpp("functions/modGMS_seas.cpp")
# source("functions/no longer app.R")
timeVector <- read.csv('parameters/times.csv') #to figure out when the MDA finishes
#scenario
##initialize input and output storage####
testfor2j <- rep(0:100,100) #homogen
testfor2i <- rep(0:99,each=101) #cmda_2
testfor2 <- cbind(testfor2j,testfor2i)
# colnames(testfor2) <- c('homogen','cmda_2')
colnames(testfor2) <- NULL
#scenario
####for template####
# for(i in 1:81){
# for(j in 1:101){
# homogen <- testfor2[((i-1)*101)+j,1]
# cmda_2 <- testfor2[((i-1)*101)+j,2]
# ###other codes for running the model
# result[[((i-1)*101)+j]] <- successMDA
# }
# }
####non-reactive parameters####
####interventions####
EDATon = TRUE
ITNon = TRUE
IRSon = FALSE
MDAon = TRUE
primon = TRUE #FALSE
MSATon = TRUE
VACon = FALSE
####non-reactive functions####
#got from the "parameters" folder #scenario
#cmda_1Loop <- seq(70, by=10, to=90) #1st batch 20190407
# cmda_1Loop <- seq(30, by=10, to=60) #2nd batch 20190409
#cmda_1Loop <- seq(10, by=10, to=20) #3rd batch 20190409
#cmda_1Loop <- seq(70, by=10, to=90) #20190522
cmda_1Loop <- 81.56 #TOT
for(loop in 1:length(cmda_1Loop)){
result <- list()
API <- 2.5
eta <- 30
covEDAT0 <- 25
covITN0 <- 70
effITN <- 30
covIRS0 <- 0
effIRS <- 15
muC <- 1
muA <- 1
muU <- 1
percfail2018 <- 5
percfail2019 <- 15
percfail2020 <- 30
bh_max0 <- 16
bh_max1 <- 16 #20 #12 #20 is next #8 #24 #16
rhoa <- 55
rhou <- 17
EDATscale <- 1
covEDATi <- 70
ITNscale <- 1
covITNi <- 90
IRSscale <- 1
covIRSi <- 90
lossd <- 30
dm0 <- 3
dm1 <- 3
cmda_1 <- cmda_1Loop[loop]#80 #90
#cmda_2 <- 50 #scenario
#homogen <- 0 #scenario
tm_1 <- 9
tm_2 <- 9
p1v <- 0.5
effv_1 <- 75
effv_2 <- 80
vh <- 90
MSATscale <- 1
covMSATi <- 90
MSATsensC <- 99
MSATsensA <- 87
MSATsensU <- 44
#non-reactive parameters
# define the number of weeks to run the model
dt<-1/12
startyear<-2007
stopyear<-2023
maxt<-stopyear-startyear
times <- seq(0, maxt, by = dt)
tsteps<-length(times)
# initial prevalence
initprevR <- (0.001*API)
#ParLabel <- read.table('functions/ParLabel.csv', sep=",", as.is=TRUE)
# scenario_0<-c(EDATon = 0,
# ITNon = 0,
# IRSon = 0,
# MDAon = 0,
# primon = 0,
# MSATon = 0,
# VACon = 0)
####for loop#####
for(i in 1:100){
for(j in 1:101){
homogen <- testfor2[((i-1)*101)+j,1]
cmda_2 <- testfor2[((i-1)*101)+j,2]
###other codes for running the model
scenario_iR<-(c(EDATon = EDATon,
ITNon = ITNon,
IRSon = IRSon,
MDAon = MDAon,
primon = primon,
MSATon = MSATon,
VACon = as.numeric(VACon)))
parametersR <- (c(
bh_max0 = bh_max0, # bites per human per night
bh_max1 = bh_max1,
eta = eta,
covEDAT0 = covEDAT0,
covITN0 = covITN0,
effITN = effITN,
covIRS0 = covIRS0,
effIRS = effIRS,
muC = muC,
muA = muA,
muU = muU,
percfail2018 = percfail2018,
percfail2019 = percfail2019,
percfail2020 = percfail2020,
EDATscale = EDATscale,
covEDATi = covEDATi,
ITNscale = ITNscale,
covITNi = covITNi,
IRSscale = IRSscale,
covIRSi = covIRSi,
cmda_1 = cmda_1,
cmda_2 = cmda_2,
tm_1 = tm_1, # timing of 1st round [2018 to 2021 - 1 month steps]
tm_2 = tm_2, # timing of 2nd round [2018+(1/12) to 2021 - 1 month steps]
dm0 = dm0,
dm1 = dm1,
lossd = lossd,
MSATscale = MSATscale,
covMSATi = covMSATi,
MSATsensC = MSATsensC,
MSATsensA = MSATsensA,
MSATsensU = MSATsensU,
effv_1 = effv_1,
effv_2 = effv_2,
vh = vh,
homogen = homogen,
p1v = p1v,
rhoa=rhoa,
rhou=rhou
))
#GMSout0R <- (runGMS(initprevR, scenario_0,parametersR))
GMSoutiR <- (runGMS(initprevR, scenario_iR,parametersR))
#labeling the columns
outLab <- c("year","detectedIncidence1","totalIncidence1","prevalence1","detectedIncidence2","totalIncidence2","prevalence2")
colnames(GMSoutiR) <- outLab
#grabbing the time of MDA success
#GMSoutiR[GMSoutiR[,3]<(1/12),1]
# MDAsuccessV1 <- GMSoutiR[,3]<(1/12)
# MDAsuccessV2 <- GMSoutiR[,6]<(1/12)
# successMDA <- cbind(MDAsuccessV1, MDAsuccessV2)
#calculating one year incidence per 1000 immediately after the end of MDA
MDAendsV1 <- which(timeVector==(2018+(tm_1+dm0)/12))
MDAendsV2 <- which(timeVector==(2018+(tm_2+dm1)/12))
DecOneYrIncV1 <- sum(GMSoutiR[MDAendsV1:(MDAendsV1+12),2])
TotOneYrIncV1 <- sum(GMSoutiR[MDAendsV1:(MDAendsV1+12),3])
DecOneYrIncV2 <- sum(GMSoutiR[MDAendsV2:(MDAendsV2+12),5])
TotOneYrIncV2 <- sum(GMSoutiR[MDAendsV2:(MDAendsV2+12),6])
OneYrInc <- cbind(DecOneYrIncV1, TotOneYrIncV1, DecOneYrIncV2, TotOneYrIncV2)
result[[((i-1)*101)+j]] <- OneYrInc #successMDA
}
}
#time component #scenario
#outside of 'for' loop
#write.table(GMSoutiR[,1],'parameters/times.csv', col.names = 'time', row.names = FALSE)
#saveRDS(result, paste('results_homo_cov/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep=''))
#saveRDS(result, paste('results_homo_cov_start0_seas/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #default HBR_MAX: 16
#saveRDS(result, paste('results_homo_cov_start0_seas_village2highAPI/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #hbr_max2: 24, highAPI
#saveRDS(result, paste('results_homo_cov_start0_seas_village2lowAPI/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #hbr_max2: 8, lowAPI
#with seasonality on [switch is inside modGMS.cpp]
#saveRDS(result, paste('results_homo_cov_start0_seas/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep=''))
saveRDS(result, paste('results_TOT/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #hbr_max2: 24, highAPI
#scenario
#Analysing the data list 'results_.rds'####
#in different plotting file
}
|
/new versions/TOT.R
|
no_license
|
SaiTheinThanTun/MDA_eff_hm
|
R
| false | false | 7,224 |
r
|
#for loop for changing MDA coverage in the first village
#MDA_eff_hm
#MDA success on homogeniety vs coverage
#20190405
#outcome is the achievement of <1/1000/year in a year starting with the end of the 3rd MDA round
#see #scenario tag for things to change in each scenario
#x axis variable: homogen, [0 to 100] %
#y axis variable: cmda_2, [0 to 80] %, coverage of MDA in second village
#z: cmda_1, [70, 80, 90] %
setwd("~/OneDrive/MORU/Projects/TCE_MDA effect/MDA_eff_hm/") #mac
library(deSolve)
library(shiny)
library(TSA)
library(Rcpp)
library(stringr)
library(lattice)
#new formula with Ricardo 20190805
sourceCpp("functions_latest/modGMS_seas.cpp", rebuild = TRUE)
source("functions_latest/no longer app.R")
# sourceCpp("functions/modGMS_seas.cpp")
# source("functions/no longer app.R")
timeVector <- read.csv('parameters/times.csv') #to figure out when the MDA finishes
#scenario
##initialize input and output storage####
testfor2j <- rep(0:100,100) #homogen
testfor2i <- rep(0:99,each=101) #cmda_2
testfor2 <- cbind(testfor2j,testfor2i)
# colnames(testfor2) <- c('homogen','cmda_2')
colnames(testfor2) <- NULL
#scenario
####for template####
# for(i in 1:81){
# for(j in 1:101){
# homogen <- testfor2[((i-1)*101)+j,1]
# cmda_2 <- testfor2[((i-1)*101)+j,2]
# ###other codes for running the model
# result[[((i-1)*101)+j]] <- successMDA
# }
# }
####non-reactive parameters####
####interventions####
EDATon = TRUE
ITNon = TRUE
IRSon = FALSE
MDAon = TRUE
primon = TRUE #FALSE
MSATon = TRUE
VACon = FALSE
####non-reactive functions####
#got from the "parameters" folder #scenario
#cmda_1Loop <- seq(70, by=10, to=90) #1st batch 20190407
# cmda_1Loop <- seq(30, by=10, to=60) #2nd batch 20190409
#cmda_1Loop <- seq(10, by=10, to=20) #3rd batch 20190409
#cmda_1Loop <- seq(70, by=10, to=90) #20190522
cmda_1Loop <- 81.56 #TOT
for(loop in 1:length(cmda_1Loop)){
result <- list()
API <- 2.5
eta <- 30
covEDAT0 <- 25
covITN0 <- 70
effITN <- 30
covIRS0 <- 0
effIRS <- 15
muC <- 1
muA <- 1
muU <- 1
percfail2018 <- 5
percfail2019 <- 15
percfail2020 <- 30
bh_max0 <- 16
bh_max1 <- 16 #20 #12 #20 is next #8 #24 #16
rhoa <- 55
rhou <- 17
EDATscale <- 1
covEDATi <- 70
ITNscale <- 1
covITNi <- 90
IRSscale <- 1
covIRSi <- 90
lossd <- 30
dm0 <- 3
dm1 <- 3
cmda_1 <- cmda_1Loop[loop]#80 #90
#cmda_2 <- 50 #scenario
#homogen <- 0 #scenario
tm_1 <- 9
tm_2 <- 9
p1v <- 0.5
effv_1 <- 75
effv_2 <- 80
vh <- 90
MSATscale <- 1
covMSATi <- 90
MSATsensC <- 99
MSATsensA <- 87
MSATsensU <- 44
#non-reactive parameters
# define the number of weeks to run the model
dt<-1/12
startyear<-2007
stopyear<-2023
maxt<-stopyear-startyear
times <- seq(0, maxt, by = dt)
tsteps<-length(times)
# initial prevalence
initprevR <- (0.001*API)
#ParLabel <- read.table('functions/ParLabel.csv', sep=",", as.is=TRUE)
# scenario_0<-c(EDATon = 0,
# ITNon = 0,
# IRSon = 0,
# MDAon = 0,
# primon = 0,
# MSATon = 0,
# VACon = 0)
####for loop#####
for(i in 1:100){
for(j in 1:101){
homogen <- testfor2[((i-1)*101)+j,1]
cmda_2 <- testfor2[((i-1)*101)+j,2]
###other codes for running the model
scenario_iR<-(c(EDATon = EDATon,
ITNon = ITNon,
IRSon = IRSon,
MDAon = MDAon,
primon = primon,
MSATon = MSATon,
VACon = as.numeric(VACon)))
parametersR <- (c(
bh_max0 = bh_max0, # bites per human per night
bh_max1 = bh_max1,
eta = eta,
covEDAT0 = covEDAT0,
covITN0 = covITN0,
effITN = effITN,
covIRS0 = covIRS0,
effIRS = effIRS,
muC = muC,
muA = muA,
muU = muU,
percfail2018 = percfail2018,
percfail2019 = percfail2019,
percfail2020 = percfail2020,
EDATscale = EDATscale,
covEDATi = covEDATi,
ITNscale = ITNscale,
covITNi = covITNi,
IRSscale = IRSscale,
covIRSi = covIRSi,
cmda_1 = cmda_1,
cmda_2 = cmda_2,
tm_1 = tm_1, # timing of 1st round [2018 to 2021 - 1 month steps]
tm_2 = tm_2, # timing of 2nd round [2018+(1/12) to 2021 - 1 month steps]
dm0 = dm0,
dm1 = dm1,
lossd = lossd,
MSATscale = MSATscale,
covMSATi = covMSATi,
MSATsensC = MSATsensC,
MSATsensA = MSATsensA,
MSATsensU = MSATsensU,
effv_1 = effv_1,
effv_2 = effv_2,
vh = vh,
homogen = homogen,
p1v = p1v,
rhoa=rhoa,
rhou=rhou
))
#GMSout0R <- (runGMS(initprevR, scenario_0,parametersR))
GMSoutiR <- (runGMS(initprevR, scenario_iR,parametersR))
#labeling the columns
outLab <- c("year","detectedIncidence1","totalIncidence1","prevalence1","detectedIncidence2","totalIncidence2","prevalence2")
colnames(GMSoutiR) <- outLab
#grabbing the time of MDA success
#GMSoutiR[GMSoutiR[,3]<(1/12),1]
# MDAsuccessV1 <- GMSoutiR[,3]<(1/12)
# MDAsuccessV2 <- GMSoutiR[,6]<(1/12)
# successMDA <- cbind(MDAsuccessV1, MDAsuccessV2)
#calculating one year incidence per 1000 immediately after the end of MDA
MDAendsV1 <- which(timeVector==(2018+(tm_1+dm0)/12))
MDAendsV2 <- which(timeVector==(2018+(tm_2+dm1)/12))
DecOneYrIncV1 <- sum(GMSoutiR[MDAendsV1:(MDAendsV1+12),2])
TotOneYrIncV1 <- sum(GMSoutiR[MDAendsV1:(MDAendsV1+12),3])
DecOneYrIncV2 <- sum(GMSoutiR[MDAendsV2:(MDAendsV2+12),5])
TotOneYrIncV2 <- sum(GMSoutiR[MDAendsV2:(MDAendsV2+12),6])
OneYrInc <- cbind(DecOneYrIncV1, TotOneYrIncV1, DecOneYrIncV2, TotOneYrIncV2)
result[[((i-1)*101)+j]] <- OneYrInc #successMDA
}
}
#time component #scenario
#outside of 'for' loop
#write.table(GMSoutiR[,1],'parameters/times.csv', col.names = 'time', row.names = FALSE)
#saveRDS(result, paste('results_homo_cov/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep=''))
#saveRDS(result, paste('results_homo_cov_start0_seas/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #default HBR_MAX: 16
#saveRDS(result, paste('results_homo_cov_start0_seas_village2highAPI/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #hbr_max2: 24, highAPI
#saveRDS(result, paste('results_homo_cov_start0_seas_village2lowAPI/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #hbr_max2: 8, lowAPI
#with seasonality on [switch is inside modGMS.cpp]
#saveRDS(result, paste('results_homo_cov_start0_seas/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep=''))
saveRDS(result, paste('results_TOT/results_loop_',loop,"_",gsub("\\:","",Sys.time()),'.rds',sep='')) #hbr_max2: 24, highAPI
#scenario
#Analysing the data list 'results_.rds'####
#in different plotting file
}
|
# R code no2
#set working directory EN
setwd("/Users/samuelepapiccio/lab/EN/")
library(raster)
library(RStoolbox)
# Import first image (single band)
# We will select band 1, but the raster function enables to select other single band
EN01<- raster("EN_0001.png")
# Plot the first image with the preferred Color Ramp Palette
cls<- colorRampPalette(c("red","pink","orange","yellow"))(200)
plot(EN01,col=cls)
# Import the last image and plot it with the previous color ramp palette
EN13<- raster("EN_0013.png")
cls<- colorRampPalette(c("red","pink","orange","yellow"))(200)
plot(EN13,col=cls)
# Make the difference between the two images and plot it
ENdif<- EN01-EN13
plot(ENdif,col=cls)
#plot everything altoghether
par(mfrow=c(3,1))
plot(EN01,col=cls, main="NO2 in January")
plot(EN13,col=cls, main="NO2 in March")
plot(ENdif,col=cls, main="NO2 difference (January - March)")
# Import the whole set
#list of files
rlist<- list.files(pattern="EN")
rlist
import<-lapply(rlist,raster)
import
EN<- stack(import)
plot(EN, col=cls)
# Replicate the plot of images 01 and 13 using the stack
par(mfrow=c(3,1))
plot(EN$EN_0001,col=cls,main="NO2 in January")
plot(EN$EN_0013,col=cls, main="NO2 in March")
# Compute a PCA over the 13 images
ENpca<- rasterPCA(EN)
summary(ENpca$model)
dev.off()
plotRGB(ENpca$map, r=1, g=2, b=3, stretch="lin")
# Compute the local variability (local SD) of the first PC
PC1sd<- focal(ENpca$map$PC1, w=matrix(1/9, nrow=3, ncol=3), fun=sd)
plot(PC1sd, col=cls)
|
/R_code_no2.r
|
no_license
|
samuelepapiccio/telerilevamento_2021
|
R
| false | false | 1,504 |
r
|
# R code no2
#set working directory EN
setwd("/Users/samuelepapiccio/lab/EN/")
library(raster)
library(RStoolbox)
# Import first image (single band)
# We will select band 1, but the raster function enables to select other single band
EN01<- raster("EN_0001.png")
# Plot the first image with the preferred Color Ramp Palette
cls<- colorRampPalette(c("red","pink","orange","yellow"))(200)
plot(EN01,col=cls)
# Import the last image and plot it with the previous color ramp palette
EN13<- raster("EN_0013.png")
cls<- colorRampPalette(c("red","pink","orange","yellow"))(200)
plot(EN13,col=cls)
# Make the difference between the two images and plot it
ENdif<- EN01-EN13
plot(ENdif,col=cls)
#plot everything altoghether
par(mfrow=c(3,1))
plot(EN01,col=cls, main="NO2 in January")
plot(EN13,col=cls, main="NO2 in March")
plot(ENdif,col=cls, main="NO2 difference (January - March)")
# Import the whole set
#list of files
rlist<- list.files(pattern="EN")
rlist
import<-lapply(rlist,raster)
import
EN<- stack(import)
plot(EN, col=cls)
# Replicate the plot of images 01 and 13 using the stack
par(mfrow=c(3,1))
plot(EN$EN_0001,col=cls,main="NO2 in January")
plot(EN$EN_0013,col=cls, main="NO2 in March")
# Compute a PCA over the 13 images
ENpca<- rasterPCA(EN)
summary(ENpca$model)
dev.off()
plotRGB(ENpca$map, r=1, g=2, b=3, stretch="lin")
# Compute the local variability (local SD) of the first PC
PC1sd<- focal(ENpca$map$PC1, w=matrix(1/9, nrow=3, ncol=3), fun=sd)
plot(PC1sd, col=cls)
|
# Munge student and mailer data
student_addr<-stus %>%
select(first=first_name,
last=last_name,
grade=grade_level,
address=street,
lat=lat.x,
long=lon.x
) %>%
mutate(type="KIPPster",
cohort=NA)
mailer_addr_selected<-mailer_addr %>%
select(first,
last,
address,
lat,
long) %>%
mutate(grade=NA,
cohort=NA,
type="Postcard")
alumni_addr_selected<-alumni_addr %>%
select(first=FirstName,
last=LastName,
address=complete_address,
lat,
long,
cohort=Cohort) %>%
mutate(grade=NA,
type="Alumni")
combined_addresses<-rbind_list(student_addr, mailer_addr_selected, alumni_addr_selected) %>%
filter(!is.na(lat), !is.na(long))
# load shapefiles ####
# community areas ####
# get cummunity areas ####
community_areas_shapefile<-readOGR("shapefiles/CommAreas/",
"CommAreas")
community_areas_shapefile<-spTransform(community_areas_shapefile,
CRS("+proj=longlat +datum=WGS84"))
# prep community areas for ggplot
community_areas_shapefile@data$id <- rownames(community_areas_shapefile@data)
community_areas <- fortify(community_areas_shapefile, region="id")
community_areas.df<-merge(community_areas,
community_areas_shapefile,
by="id") %>%
arrange(id, order) %>%
as.data.frame
# add_municipalities
municipalities_shapefile<-readOGR("shapefiles/Municipalities/",
"Municipalities")
municipalities_shapefile<-spTransform(municipalities_shapefile,
CRS("+proj=longlat +datum=WGS84"))
# prep community areas for ggplot
municipalities_shapefile@data$id <- rownames(municipalities_shapefile@data)
municipalities <- fortify(municipalities_shapefile, region="id")
municipalities.df<-merge(municipalities,
municipalities_shapefile,
by="id") %>%
arrange(id, order) %>%
as.data.frame
# assign addresses to community areas to aid in subsetting
combined_sp <- combined_addresses %>% select(long, lat)%>% as.data.frame
coordinates(combined_sp) <- ~long+lat
proj4string(combined_sp)<- CRS("+proj=longlat +datum=WGS84")
cas_overlaid<-over(combined_sp, community_areas_shapefile)
combined_addresses$community_area<- cas_overlaid$COMMUNITY
|
/Student Recruiting/munge/01-A.R
|
no_license
|
kippchicago/Data_Analysis
|
R
| false | false | 2,463 |
r
|
# Munge student and mailer data
student_addr<-stus %>%
select(first=first_name,
last=last_name,
grade=grade_level,
address=street,
lat=lat.x,
long=lon.x
) %>%
mutate(type="KIPPster",
cohort=NA)
mailer_addr_selected<-mailer_addr %>%
select(first,
last,
address,
lat,
long) %>%
mutate(grade=NA,
cohort=NA,
type="Postcard")
alumni_addr_selected<-alumni_addr %>%
select(first=FirstName,
last=LastName,
address=complete_address,
lat,
long,
cohort=Cohort) %>%
mutate(grade=NA,
type="Alumni")
combined_addresses<-rbind_list(student_addr, mailer_addr_selected, alumni_addr_selected) %>%
filter(!is.na(lat), !is.na(long))
# load shapefiles ####
# community areas ####
# get cummunity areas ####
community_areas_shapefile<-readOGR("shapefiles/CommAreas/",
"CommAreas")
community_areas_shapefile<-spTransform(community_areas_shapefile,
CRS("+proj=longlat +datum=WGS84"))
# prep community areas for ggplot
community_areas_shapefile@data$id <- rownames(community_areas_shapefile@data)
community_areas <- fortify(community_areas_shapefile, region="id")
community_areas.df<-merge(community_areas,
community_areas_shapefile,
by="id") %>%
arrange(id, order) %>%
as.data.frame
# add_municipalities
municipalities_shapefile<-readOGR("shapefiles/Municipalities/",
"Municipalities")
municipalities_shapefile<-spTransform(municipalities_shapefile,
CRS("+proj=longlat +datum=WGS84"))
# prep community areas for ggplot
municipalities_shapefile@data$id <- rownames(municipalities_shapefile@data)
municipalities <- fortify(municipalities_shapefile, region="id")
municipalities.df<-merge(municipalities,
municipalities_shapefile,
by="id") %>%
arrange(id, order) %>%
as.data.frame
# assign addresses to community areas to aid in subsetting
combined_sp <- combined_addresses %>% select(long, lat)%>% as.data.frame
coordinates(combined_sp) <- ~long+lat
proj4string(combined_sp)<- CRS("+proj=longlat +datum=WGS84")
cas_overlaid<-over(combined_sp, community_areas_shapefile)
combined_addresses$community_area<- cas_overlaid$COMMUNITY
|
# plot
#' outer2
#' The outer product of the arrays `X` and `Y` is the array `A` with dimension
#' `c(dim(X), dim(Y))` where element `A[c(arrayindex.x, arrayindex.y)] =
#' FUN(X[arrayindex.x], Y[arrayindex.y], ...)`. This is a patch to the [outer]
#' function that can handle non-vectorized functions as well as vectorized ones.
#' @param X,Y First and second arguments for function `FUN.`
#' Typically a vector or array.
#' @param FUN a function to use on the outer products, found via [match.fun]
#' (except for the special case "`*`").
#' @param ... optional arguments to be passed to `FUN`.
#' @param Vectorized
#' @return A matrix
#' @seealso [outer]
#' @source https://tolstoy.newcastle.edu.au/R/help/05/10/14725.html
#' @author Tony Plate
#' @examples
outer2 <- function(X, Y, FUN = "*", ..., Vectorized = FALSE) {
no.nx <- is.null(nx <- dimnames(X <- as.array(X)))
dX <- dim(X)
no.ny <- is.null(ny <- dimnames(Y <- as.array(Y)))
dY <- dim(Y)
if (is.character(FUN) && FUN == "*") {
robj <- as.vector(X) %*% t(as.vector(Y))
dim(robj) <- c(dX, dY)
} else {
FUN <- match.fun(FUN)
Y <- rep(Y, rep.int(length(X), length(Y)))
if (length(X) > 0)
X <- rep(X, times = ceiling(length(Y)/length(X)))
if (Vectorized)
robj <- FUN(X, Y, ...)
else
robj <- mapply(FUN, X, Y, MoreArgs=list(...))
dim(robj) <- c(dX, dY)
}
if (no.nx)
nx <- vector("list", length(dX))
else if (no.ny)
ny <- vector("list", length(dY))
if (!(no.nx && no.ny))
dimnames(robj) <- c(nx, ny)
robj
}
#'plotf1
#'
#' @param f
#' @param from
#' @param to
#' @param ...
#'
#' @return Directly plots the function results
#' @export
#' @examples
plotf1 <- function(f, from = -5, to = 5, ...) {
steps <- 200
#
se <- c(from, to)
dim(se) <- c(length(from), 2)
# Create a n-dim plane
x <- apply(se, 1, function(i) seq(i[1], i[2], length.out = steps))
# Feed the plane into the function
fx <- apply(x, 1, f, ...)
# Plot the results
plot(1:length(fx), fx, type = "l")
}
# source("./R/Haystack.R")
# p <- plotf1(function(x) 10*length(x) + sum((x)^2 - 10*cos(1*pi*(x))),
# from = rep(-10,2), to = rep(10,2))
#' plotf2
#'
#' @param f
#' @param from Numeric vector with 2 positions
#' @param to Numeric vector with 2 positions
#' @param ...
#'
#' @return
#' @export
#'
#' @examples
plotf2 <- function(f, from = c(-5, -5), to = c(5, 5), ...) {
# PRECONDITIONS
require(plot3D)
steps <- 200
# Run
x <- seq(from[1], to[1], length.out = steps)
y <- seq(from[2], to[2], length.out = steps)
z <- outer2(x, y, function(a, b) f(c(a, b)), ...)
persp3D(x, y, z = z)
}
p <- plotf2(function(x) 10*length(x) + sum((x)^2 - 10*cos(1*pi*(x))))
plotfc <- function(f, from = c(-5, -5), to = c(5, 5), ...) {
# PRECONDITIONS
require(plot3D)
steps <- 200
# Run
x <- seq(from[1], to[1], length.out = steps)
y <- seq(from[2], to[2], length.out = steps)
z <- outer2(x, y, function(a, b) f(c(a, b)), ...)
contour(z = z)
}
#p <- plotfc(function(x) 10*length(x) + sum((x)^2 - 10*cos(1*pi*(x))))
plotf <- function(f, type = c("one", "two", "contour"), plane = NULL,
range = 5, center = 0,
...) {
type <- match.arg(type)
switch(type,
one = plotf1(x, ...),
two = plotf2(x, ...),
contour = plotfc(x, ...))
}
|
/R/plotf.R
|
permissive
|
SigurdJanson/OptimTestLib
|
R
| false | false | 3,368 |
r
|
# plot
#' outer2
#' The outer product of the arrays `X` and `Y` is the array `A` with dimension
#' `c(dim(X), dim(Y))` where element `A[c(arrayindex.x, arrayindex.y)] =
#' FUN(X[arrayindex.x], Y[arrayindex.y], ...)`. This is a patch to the [outer]
#' function that can handle non-vectorized functions as well as vectorized ones.
#' @param X,Y First and second arguments for function `FUN.`
#' Typically a vector or array.
#' @param FUN a function to use on the outer products, found via [match.fun]
#' (except for the special case "`*`").
#' @param ... optional arguments to be passed to `FUN`.
#' @param Vectorized
#' @return A matrix
#' @seealso [outer]
#' @source https://tolstoy.newcastle.edu.au/R/help/05/10/14725.html
#' @author Tony Plate
#' @examples
outer2 <- function(X, Y, FUN = "*", ..., Vectorized = FALSE) {
no.nx <- is.null(nx <- dimnames(X <- as.array(X)))
dX <- dim(X)
no.ny <- is.null(ny <- dimnames(Y <- as.array(Y)))
dY <- dim(Y)
if (is.character(FUN) && FUN == "*") {
robj <- as.vector(X) %*% t(as.vector(Y))
dim(robj) <- c(dX, dY)
} else {
FUN <- match.fun(FUN)
Y <- rep(Y, rep.int(length(X), length(Y)))
if (length(X) > 0)
X <- rep(X, times = ceiling(length(Y)/length(X)))
if (Vectorized)
robj <- FUN(X, Y, ...)
else
robj <- mapply(FUN, X, Y, MoreArgs=list(...))
dim(robj) <- c(dX, dY)
}
if (no.nx)
nx <- vector("list", length(dX))
else if (no.ny)
ny <- vector("list", length(dY))
if (!(no.nx && no.ny))
dimnames(robj) <- c(nx, ny)
robj
}
#'plotf1
#'
#' @param f
#' @param from
#' @param to
#' @param ...
#'
#' @return Directly plots the function results
#' @export
#' @examples
plotf1 <- function(f, from = -5, to = 5, ...) {
steps <- 200
#
se <- c(from, to)
dim(se) <- c(length(from), 2)
# Create a n-dim plane
x <- apply(se, 1, function(i) seq(i[1], i[2], length.out = steps))
# Feed the plane into the function
fx <- apply(x, 1, f, ...)
# Plot the results
plot(1:length(fx), fx, type = "l")
}
# source("./R/Haystack.R")
# p <- plotf1(function(x) 10*length(x) + sum((x)^2 - 10*cos(1*pi*(x))),
# from = rep(-10,2), to = rep(10,2))
#' plotf2
#'
#' @param f
#' @param from Numeric vector with 2 positions
#' @param to Numeric vector with 2 positions
#' @param ...
#'
#' @return
#' @export
#'
#' @examples
plotf2 <- function(f, from = c(-5, -5), to = c(5, 5), ...) {
# PRECONDITIONS
require(plot3D)
steps <- 200
# Run
x <- seq(from[1], to[1], length.out = steps)
y <- seq(from[2], to[2], length.out = steps)
z <- outer2(x, y, function(a, b) f(c(a, b)), ...)
persp3D(x, y, z = z)
}
p <- plotf2(function(x) 10*length(x) + sum((x)^2 - 10*cos(1*pi*(x))))
plotfc <- function(f, from = c(-5, -5), to = c(5, 5), ...) {
# PRECONDITIONS
require(plot3D)
steps <- 200
# Run
x <- seq(from[1], to[1], length.out = steps)
y <- seq(from[2], to[2], length.out = steps)
z <- outer2(x, y, function(a, b) f(c(a, b)), ...)
contour(z = z)
}
#p <- plotfc(function(x) 10*length(x) + sum((x)^2 - 10*cos(1*pi*(x))))
plotf <- function(f, type = c("one", "two", "contour"), plane = NULL,
range = 5, center = 0,
...) {
type <- match.arg(type)
switch(type,
one = plotf1(x, ...),
two = plotf2(x, ...),
contour = plotfc(x, ...))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/merTools-package.r
\docType{data}
\name{hsb}
\alias{hsb}
\title{A subset of data from the 1982 High School and Beyond survey used as examples for HLM software}
\format{A data frame with 7,185 observations on the following 8 variables.
\describe{
\item{\code{schid}}{a numeric vector, 160 unique values}
\item{\code{mathach}}{a numeric vector for the performance on a standardized math assessment}
\item{\code{female}}{a numeric vector coded 0 for male and 1 for female}
\item{\code{ses}}{a numeric measure of student socio-economic status}
\item{\code{minority}}{a numeric vector coded 0 for white and 1 for non-white students}
\item{\code{schtype}}{a numeric vector coded 0 for public and 1 for private schools}
\item{\code{meanses}}{a numeric, the average SES for each school in the data set}
\item{\code{size}}{a numeric for the number of students in the school}
}}
\source{
Data made available by UCLA Institute for Digital Research and Education
(IDRE) online: \url{http://www.ats.ucla.edu/stat/hlm/seminars/hlm6/mlm_hlm6_seminar.htm}
}
\usage{
hsb
}
\description{
A key example dataset used for examples in the HLM software manual.
Included here for use in replicating HLM analyses in R.
}
\details{
The data file used for this presentation is a subsample from the
1982 High School and Beyond Survey and is used extensively in
Hierarchical Linear Models by Raudenbush and Bryk. It consists of 7,185 students
nested in 160 schools.
}
\examples{
data(hsb)
head(hsb)
}
\references{
Stephen W. Raudenbush and Anthony S. Bryk (2002). Hierarchical
Linear Models: Applications and Data Analysis Methods (2nd ed.). SAGE.
}
\keyword{datasets}
|
/man/hsb.Rd
|
no_license
|
jamesonquinn/merTools
|
R
| false | true | 1,727 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/merTools-package.r
\docType{data}
\name{hsb}
\alias{hsb}
\title{A subset of data from the 1982 High School and Beyond survey used as examples for HLM software}
\format{A data frame with 7,185 observations on the following 8 variables.
\describe{
\item{\code{schid}}{a numeric vector, 160 unique values}
\item{\code{mathach}}{a numeric vector for the performance on a standardized math assessment}
\item{\code{female}}{a numeric vector coded 0 for male and 1 for female}
\item{\code{ses}}{a numeric measure of student socio-economic status}
\item{\code{minority}}{a numeric vector coded 0 for white and 1 for non-white students}
\item{\code{schtype}}{a numeric vector coded 0 for public and 1 for private schools}
\item{\code{meanses}}{a numeric, the average SES for each school in the data set}
\item{\code{size}}{a numeric for the number of students in the school}
}}
\source{
Data made available by UCLA Institute for Digital Research and Education
(IDRE) online: \url{http://www.ats.ucla.edu/stat/hlm/seminars/hlm6/mlm_hlm6_seminar.htm}
}
\usage{
hsb
}
\description{
A key example dataset used for examples in the HLM software manual.
Included here for use in replicating HLM analyses in R.
}
\details{
The data file used for this presentation is a subsample from the
1982 High School and Beyond Survey and is used extensively in
Hierarchical Linear Models by Raudenbush and Bryk. It consists of 7,185 students
nested in 160 schools.
}
\examples{
data(hsb)
head(hsb)
}
\references{
Stephen W. Raudenbush and Anthony S. Bryk (2002). Hierarchical
Linear Models: Applications and Data Analysis Methods (2nd ed.). SAGE.
}
\keyword{datasets}
|
#Nested looping
for(i in seq(1,3)){
#for every single run in outside loop inside loop gets executed 10 times
for(j in seq(i,i+10L)){
cat(j," ")
}
}
|
/DAY - 2/Assignment/Q5 - NestedLoops.R
|
no_license
|
Sajeth-s-a/Data-Science---R-programming-
|
R
| false | false | 173 |
r
|
#Nested looping
for(i in seq(1,3)){
#for every single run in outside loop inside loop gets executed 10 times
for(j in seq(i,i+10L)){
cat(j," ")
}
}
|
# Loading Data RDS
require(ggplot2)
NEI <- readRDS("data/summarySCC_PM25.rds")
SCC <- readRDS("data/Source_Classification_Code.rds")
# Coal-related SCC
SCC.coal = SCC[grepl("coal", SCC$Short.Name, ignore.case = TRUE), ]
# Merges two data sets
merge <- merge(x = NEI, y = SCC.coal, by = 'SCC')
merge.sum <- aggregate(merge[, 'Emissions'], by = list(merge$year), sum)
colnames(merge.sum) <- c('Year', 'Emissions')
# Generating Graph
png(filename = 'plot4.png')
ggplot(data = merge.sum, aes(x = Year, y = Emissions / 1000)) + geom_line(aes(group = 1, col = Emissions)) + geom_point(aes(size = 2, col = Emissions)) + ggtitle(expression('Total Emissions of PM'[2.5])) + ylab(expression(paste('PM', ''[2.5], ' in kilotons'))) + geom_text(aes(label = round(Emissions / 1000, digits = 2), size = 2, hjust = 1.5, vjust = 1.5)) + theme(legend.position = 'none') + scale_colour_gradient(low = 'black', high = 'red')
dev.off()
|
/plot4.R
|
no_license
|
coolbhatt/Project-2
|
R
| false | false | 918 |
r
|
# Loading Data RDS
require(ggplot2)
NEI <- readRDS("data/summarySCC_PM25.rds")
SCC <- readRDS("data/Source_Classification_Code.rds")
# Coal-related SCC
SCC.coal = SCC[grepl("coal", SCC$Short.Name, ignore.case = TRUE), ]
# Merges two data sets
merge <- merge(x = NEI, y = SCC.coal, by = 'SCC')
merge.sum <- aggregate(merge[, 'Emissions'], by = list(merge$year), sum)
colnames(merge.sum) <- c('Year', 'Emissions')
# Generating Graph
png(filename = 'plot4.png')
ggplot(data = merge.sum, aes(x = Year, y = Emissions / 1000)) + geom_line(aes(group = 1, col = Emissions)) + geom_point(aes(size = 2, col = Emissions)) + ggtitle(expression('Total Emissions of PM'[2.5])) + ylab(expression(paste('PM', ''[2.5], ' in kilotons'))) + geom_text(aes(label = round(Emissions / 1000, digits = 2), size = 2, hjust = 1.5, vjust = 1.5)) + theme(legend.position = 'none') + scale_colour_gradient(low = 'black', high = 'red')
dev.off()
|
context("query_building - prep")
mysql_cred <- function(){
json_string <- Sys.getenv("DBEZR_TEST_MYSQL")
if (json_string != ""){
tryCatch({
.cred <- cred_json(json_string)
tryCatch({
disconnect_con(create_con(.cred))
},
error = function(e){
skip(
paste0("Unable to connect. ", capture.output(print(.cred)))
)
})
},
error = function(e){
skip("Malformed JSON, can't extract credentials")
})
} else{
skip("No MySQL test database provided")
}
.cred
}
pgsql_cred <- function(){
json_string <- Sys.getenv("DBEZR_TEST_POSTGRES")
if (json_string != ""){
tryCatch({
.cred <- cred_json(json_string)
tryCatch({
disconnect_con(create_con(.cred))
},
error = function(e){
skip(
paste0("Unable to connect. ", capture.output(print(.cred)))
)
})
},
error = function(e){
skip("Malformed JSON, can't extract credentials")
})
} else{
skip("No Postgres test database provided")
}
.cred
}
test_that("Character column is cleaned", {
rm_db_all()
db_cred(pgsql_cred())
# Single Value
expect_equal(prep("Bob"), "'Bob'")
# Vector
expect_equal(prep(c("Bob", "George")), c("'Bob'", "'George'"))
})
test_that("Character column is cleaned properly with NULL values", {
rm_db_all()
db_cred(pgsql_cred())
# Single Null Values
expect_equal(prep(c(NA, "George", "Fred")), c("NULL", "'George'", "'Fred'"))
expect_equal(prep(c("Bob", NA, "Fred")), c("'Bob'", "NULL", "'Fred'"))
expect_equal(prep(c("Bob", "George", NA)), c("'Bob'", "'George'", "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
test_that("Character column is cleaned for possible Injection attacks", {
rm_db_all()
db_cred(pgsql_cred())
expect_equal(prep("Robert'); DROP TABLE Students;--"),
"'Robert''); DROP TABLE Students;--'")
})
test_that("Date column is cleaned", {
today <- parse_date("2016-01-02")
today_s <- "'2016-01-02 00:00:00'"
now <- parse_date_time("2016-01-03 04:05:06")
now_s <- "'2016-01-03 04:05:06'"
# Single Value
expect_equal(prep(today), today_s)
# Vector
t_vect <- lubridate::with_tz(c(today, now), "UTC")
expect_equal(prep(t_vect), c(today_s, now_s))
})
test_that("Date column is cleaned properly with NULL values", {
today <- parse_date("2016-01-02")
today_s <- "'2016-01-02 00:00:00'"
now <- parse_date_time("2016-01-03 04:05:06")
now_s <- "'2016-01-03 04:05:06'"
# Single Null Values
first_val <- lubridate::with_tz(c(now, today, now), "UTC")
first_val[1] <- NA
secnd_val <- lubridate::with_tz(c(today, NA, now), "UTC")
third_val <- lubridate::with_tz(c(today, now, NA), "UTC")
expect_equal(prep(first_val), c("NULL", today_s, now_s))
expect_equal(prep(secnd_val), c(today_s, "NULL", now_s))
expect_equal(prep(third_val), c(today_s, now_s, "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
test_that("Numeric column is cleaned", {
# Single Value
expect_equal(prep(1), "1")
# Vector
expect_equal(prep(c(1, 2, 3)), c("1", "2", "3"))
})
test_that("Double column is cleaned", {
# Single Value
expect_equal(prep(as.double(1)), "1")
# Vector
expect_equal(prep(as.double(c(1, 2, 3))), c("1", "2", "3"))
})
test_that("Integer column is cleaned", {
# Single Value
expect_equal(prep(1L), "1")
# Vector
expect_equal(prep(c(1L, 2L, 3L)), c("1", "2", "3"))
})
test_that("Numeric column is cleaned properly with NULL values", {
# Single Null Values
expect_equal(prep(c(NA, 2, 3)), c("NULL", "2", "3"))
expect_equal(prep(c(1, NA, 3)), c("1", "NULL", "3"))
expect_equal(prep(c(1, 2, NA)), c("1", "2", "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
test_that("Logical column is cleaned", {
# Single Value
expect_equal(prep(TRUE), "1")
expect_equal(prep(FALSE), "0")
# Vector
expect_equal(prep(c(TRUE, FALSE)), c("1", "0"))
})
test_that("Logical column is cleaned properly with NULL values", {
# Single Null Values
expect_equal(prep(c(NA, FALSE)), c("NULL", "0"))
expect_equal(prep(c(TRUE, NA)), c("1", "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
|
/tests/testthat/test_prep.R
|
permissive
|
acjackman/dbezr
|
R
| false | false | 4,641 |
r
|
context("query_building - prep")
mysql_cred <- function(){
json_string <- Sys.getenv("DBEZR_TEST_MYSQL")
if (json_string != ""){
tryCatch({
.cred <- cred_json(json_string)
tryCatch({
disconnect_con(create_con(.cred))
},
error = function(e){
skip(
paste0("Unable to connect. ", capture.output(print(.cred)))
)
})
},
error = function(e){
skip("Malformed JSON, can't extract credentials")
})
} else{
skip("No MySQL test database provided")
}
.cred
}
pgsql_cred <- function(){
json_string <- Sys.getenv("DBEZR_TEST_POSTGRES")
if (json_string != ""){
tryCatch({
.cred <- cred_json(json_string)
tryCatch({
disconnect_con(create_con(.cred))
},
error = function(e){
skip(
paste0("Unable to connect. ", capture.output(print(.cred)))
)
})
},
error = function(e){
skip("Malformed JSON, can't extract credentials")
})
} else{
skip("No Postgres test database provided")
}
.cred
}
test_that("Character column is cleaned", {
rm_db_all()
db_cred(pgsql_cred())
# Single Value
expect_equal(prep("Bob"), "'Bob'")
# Vector
expect_equal(prep(c("Bob", "George")), c("'Bob'", "'George'"))
})
test_that("Character column is cleaned properly with NULL values", {
rm_db_all()
db_cred(pgsql_cred())
# Single Null Values
expect_equal(prep(c(NA, "George", "Fred")), c("NULL", "'George'", "'Fred'"))
expect_equal(prep(c("Bob", NA, "Fred")), c("'Bob'", "NULL", "'Fred'"))
expect_equal(prep(c("Bob", "George", NA)), c("'Bob'", "'George'", "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
test_that("Character column is cleaned for possible Injection attacks", {
rm_db_all()
db_cred(pgsql_cred())
expect_equal(prep("Robert'); DROP TABLE Students;--"),
"'Robert''); DROP TABLE Students;--'")
})
test_that("Date column is cleaned", {
today <- parse_date("2016-01-02")
today_s <- "'2016-01-02 00:00:00'"
now <- parse_date_time("2016-01-03 04:05:06")
now_s <- "'2016-01-03 04:05:06'"
# Single Value
expect_equal(prep(today), today_s)
# Vector
t_vect <- lubridate::with_tz(c(today, now), "UTC")
expect_equal(prep(t_vect), c(today_s, now_s))
})
test_that("Date column is cleaned properly with NULL values", {
today <- parse_date("2016-01-02")
today_s <- "'2016-01-02 00:00:00'"
now <- parse_date_time("2016-01-03 04:05:06")
now_s <- "'2016-01-03 04:05:06'"
# Single Null Values
first_val <- lubridate::with_tz(c(now, today, now), "UTC")
first_val[1] <- NA
secnd_val <- lubridate::with_tz(c(today, NA, now), "UTC")
third_val <- lubridate::with_tz(c(today, now, NA), "UTC")
expect_equal(prep(first_val), c("NULL", today_s, now_s))
expect_equal(prep(secnd_val), c(today_s, "NULL", now_s))
expect_equal(prep(third_val), c(today_s, now_s, "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
test_that("Numeric column is cleaned", {
# Single Value
expect_equal(prep(1), "1")
# Vector
expect_equal(prep(c(1, 2, 3)), c("1", "2", "3"))
})
test_that("Double column is cleaned", {
# Single Value
expect_equal(prep(as.double(1)), "1")
# Vector
expect_equal(prep(as.double(c(1, 2, 3))), c("1", "2", "3"))
})
test_that("Integer column is cleaned", {
# Single Value
expect_equal(prep(1L), "1")
# Vector
expect_equal(prep(c(1L, 2L, 3L)), c("1", "2", "3"))
})
test_that("Numeric column is cleaned properly with NULL values", {
# Single Null Values
expect_equal(prep(c(NA, 2, 3)), c("NULL", "2", "3"))
expect_equal(prep(c(1, NA, 3)), c("1", "NULL", "3"))
expect_equal(prep(c(1, 2, NA)), c("1", "2", "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
test_that("Logical column is cleaned", {
# Single Value
expect_equal(prep(TRUE), "1")
expect_equal(prep(FALSE), "0")
# Vector
expect_equal(prep(c(TRUE, FALSE)), c("1", "0"))
})
test_that("Logical column is cleaned properly with NULL values", {
# Single Null Values
expect_equal(prep(c(NA, FALSE)), c("NULL", "0"))
expect_equal(prep(c(TRUE, NA)), c("1", "NULL"))
# Whole Vector NULL
expect_equal(prep(c(NA, NA)), c("NULL", "NULL"))
})
|
# Server Output Functions for Visualize Tab
#### Main Tab Output Functions ####
# Controls for the whole set of tabs
output$Visualize_Tab_Controls_1 <- renderUI({
selectizeInput(
"VisualizeEventMapInputID",
label = h4("Choose POV:"),
get_POV_names()
)
})
output$Visualize_Tab_Controls_2 <- renderUI({
req(input$VisualizeEventMapInputID)
zoom_limit = zoom_upper_limit(get_POV(input$VisualizeEventMapInputID))
if(zoom_limit == 1) {
tags$h4("Zooming not available for this POV")
} else {
tags$div(
sliderInput(
"VisualizeTabZoomID",
label = h4("Zoom in and out by event similarity:"),
1, zoom_limit, zoom_limit, step = 1, ticks = FALSE
),
helpText('Zooming does not apply to some visualizations.'))
}
})
output$Visualize_Tab_Controls_3 = renderUI({
nThreads = numThreads(threadedEventsViz_ALL(),'threadNum')
sliderInput("VisualizeRangeID",
label=h4("Range of threads to include:"),
1, nThreads, c(1,nThreads),step = 1, ticks=FALSE)
})
#### N-Grams sub-tab ####
# controls for ngrams display
output$nGramControls <- renderUI({
tagList(
sliderInput("nGramLengthID","nGram Size", 1,10,2,step = 1,ticks = FALSE),
sliderInput("nGramDisplayThresholdID","Display threshold", 1,50,1,step = 1,ticks = FALSE),
radioButtons(
"Label_or_Zoom_3",
"Do you prefer:",
choices = c('Labels','Zooming'),
selected = 'Labels',
inline = TRUE)
)
})
# NGRAMdisplay
output$nGramBarchart <- renderPlotly({
req(input$nGramLengthID)
if (input$Label_or_Zoom_3 == 'Labels')
ng_bar_chart(
threadedEventsViz(),
"threadNum",
'label',
input$nGramLengthID,
input$nGramDisplayThresholdID)
else
ng_bar_chart(
threadedEventsViz(),
"threadNum",
get_Zoom_VIZ(),
input$nGramLengthID,
input$nGramDisplayThresholdID)
})
#### Whole Sequences sub-tab ####
# Whole sequence display -- allow alternatives
output$WholeSequenceThreadMap_Sequence <- renderPlotly({ threadMap(threadedEventsViz(), "threadNum", "seqNum", get_Zoom_VIZ(), 15)})
output$WholeSequenceThreadMap_ActualTime <- renderPlotly({ threadMap(threadedEventsViz(), "threadNum", "tStamp", get_Zoom_VIZ(), 15)})
output$WholeSequenceThreadMap_RelativeTime <- renderPlotly({ threadMap(threadedEventsViz(), "threadNum", "relativeTime", get_Zoom_VIZ(), 15)})
#### Event Network (circle) sub-tab ####
# use this to select how to color the nodes in force layout
output$Circle_Network_Tab_Controls <- renderUI({
tags$div(
downloadButton('downloadNetwork', 'Export this Network', class="dlButton"),
sliderInput("circleEdgeTheshold","Display edges above", 0,1,0,step = 0.01,ticks = FALSE ),
radioButtons(
"Label_or_Zoom_1",
"Do you prefer:",
choices = c('Labels','Zooming'),
selected = 'Labels',
inline = TRUE)
)
})
# Create the network to be exported and also displayed
viz_net <<- reactive({
req(input$circleEdgeTheshold)
# first convert the threads to the network
if (input$Label_or_Zoom_1 == 'Labels')
{ n <- threads_to_network_original(threadedEventsViz(), "threadNum", 'label') }
else
{ n <- threads_to_network_original(threadedEventsViz(), "threadNum", get_Zoom_VIZ()) }
# filter out the edges if desired
n <- filter_network_edges(n,input$circleEdgeTheshold)
n
})
output$circleVisNetwork <- renderVisNetwork({
req(input$circleEdgeTheshold)
circleVisNetwork(viz_net(), 'directed', TRUE)
})
# output$circleVisNetwork <- renderVisNetwork({
# req(input$circleEdgeTheshold)
#
# # first convert the threads to the network
# if (input$Label_or_Zoom_1 == 'Labels')
# { n <- threads_to_network_original(threadedEventsViz(), "threadNum", 'label') }
# else
# { n <- threads_to_network_original(threadedEventsViz(), "threadNum", get_Zoom_VIZ()) }
#
# # filter out the edges if desired
# n <- filter_network_edges(n,input$circleEdgeTheshold)
# circleVisNetwork(n, 'directed', TRUE)
# })
#### Other Networks sub-tab ####
# use this to select how to color the nodes in force layout
output$Other_Network_Tab_Controls <- renderUI({
button_choices <- get_POV_EVENT_CF( input$VisualizeEventMapInputID )
tags$div(
radioButtons(
"OtherNetworkCF",
"Graph co-occurrence relation between:",
choices = button_choices,
selected = button_choices[1], # always start with the first one
inline = TRUE
),
sliderInput("otherEdgeTheshold","Display edges above",0,1,0,step = 0.01,ticks = FALSE)
)
})
output$otherVisNetwork <- renderVisNetwork({
req(input$otherEdgeTheshold)
# first convert the threads to the network
n <- normalNetwork(threadedEventsViz(), selectOccFilter(), input$OtherNetworkCF)
n <- filter_network_edges(n,input$otherEdgeTheshold)
circleVisNetwork(n, 'nondirected')
})
#### Event Network (force) sub-tab ####
# use this to select how to color the nodes in force layout
output$Force_Network_Tab_Controls <- renderUI({
button_choices <- intersect(colnames(threadedEventsViz()), cfnames(selectOccFilter()))
tags$div(
radioButtons(
"NetworkGroupID",
"Select a dimension for coloring nodes:",
choices = button_choices,
selected = button_choices[1], # always start with the first one
inline=TRUE
),
sliderInput("forceEdgeTheshold","Display edges above",0,1,0,step = 0.01,ticks = FALSE),
radioButtons(
"Label_or_Zoom_2",
"Do you prefer:",
choices = c('Labels','Zooming'),
selected = 'Labels',
inline = TRUE)
)
})
output$forceNetworkD3 <- renderForceNetwork({
req(input$forceEdgeTheshold)
if (input$Label_or_Zoom_2 == 'Labels')
{ n <- threads_to_network_original(threadedEventsViz(), 'threadNum', 'label', input$NetworkGroupID) }
else
{ n <- threads_to_network_original(threadedEventsViz(), 'threadNum', get_Zoom_VIZ(), input$NetworkGroupID) }
n <- filter_network_edges(n,input$forceEdgeTheshold)
forceNetworkD3(n)
})
output$networkPie <- renderPlotly({
req(input$Group)
get_group <- input$Group
CF_multi_pie_event(threadedOcc(), threadedEventsViz(), get_POV_EVENT_CF( input$VisualizeEventMapInputID ), get_group, get_Zoom_VIZ())
})
#### View Events sub-tab ####
output$VisualizeCustomNetwork_Controls_0 <- renderUI({
radioButtons("Timesplit2", "Time Measure:", choices = c('seqNum'='seqNum','timeGap'='timeGap'), selected = "seqNum", inline = TRUE)
})
output$VisualizeCustomNetwork_Controls_1 <- renderUI({
selectizeInput("Event",label = "Choose Event:",get_POV_EVENT_CF( input$VisualizeEventMapInputID ) )
})
output$VisualizeCustomNetwork <- renderPlotly({
req(input$Timesplit2, input$Event)
eventNetwork(threadedEventsViz(), "threadNum", input$Event, input$Timesplit2)
})
output$hover <- renderPrint({
d <- event_data("plotly_hover")
if (is.null(d)) "Hover events appear here (unhover to clear)" else d
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (is.null(d)) "Click events appear here" else d
})
#### Role Maps sub-tab ####
output$Role_map_controls <- renderUI({checkboxGroupInput("Role_map_CFs","Pick Two:", get_POV_EVENT_CF( input$VisualizeEventMapInputID ) )})
output$Role_map_output <- renderPlotly({role_map(threadedEventsViz(), selectOccFilter(), input$Role_map_CFs)})
#### Thread Trajectories sub-tab ####
output$ThreadTrajectoriesOutput <- renderPlotly({threadTrajectory(threadedEventsViz())})
##### pie chart display #####
output$visualizePieCharts = renderPlotly({
CF_multi_pie(threadedEventsViz(), get_POV_EVENT_CF( input$VisualizeEventMapInputID ) )
})
# provide a data table view, as well
output$visualizePOVData <-DT::renderDataTable(
threadedEventsViz(),
options = list(autoWidth = TRUE))
|
/Inst/ThreadNet/server/visualize.R
|
no_license
|
noelcarroll1/ThreadNet
|
R
| false | false | 7,594 |
r
|
# Server Output Functions for Visualize Tab
#### Main Tab Output Functions ####
# Controls for the whole set of tabs
output$Visualize_Tab_Controls_1 <- renderUI({
selectizeInput(
"VisualizeEventMapInputID",
label = h4("Choose POV:"),
get_POV_names()
)
})
output$Visualize_Tab_Controls_2 <- renderUI({
req(input$VisualizeEventMapInputID)
zoom_limit = zoom_upper_limit(get_POV(input$VisualizeEventMapInputID))
if(zoom_limit == 1) {
tags$h4("Zooming not available for this POV")
} else {
tags$div(
sliderInput(
"VisualizeTabZoomID",
label = h4("Zoom in and out by event similarity:"),
1, zoom_limit, zoom_limit, step = 1, ticks = FALSE
),
helpText('Zooming does not apply to some visualizations.'))
}
})
output$Visualize_Tab_Controls_3 = renderUI({
nThreads = numThreads(threadedEventsViz_ALL(),'threadNum')
sliderInput("VisualizeRangeID",
label=h4("Range of threads to include:"),
1, nThreads, c(1,nThreads),step = 1, ticks=FALSE)
})
#### N-Grams sub-tab ####
# controls for ngrams display
output$nGramControls <- renderUI({
tagList(
sliderInput("nGramLengthID","nGram Size", 1,10,2,step = 1,ticks = FALSE),
sliderInput("nGramDisplayThresholdID","Display threshold", 1,50,1,step = 1,ticks = FALSE),
radioButtons(
"Label_or_Zoom_3",
"Do you prefer:",
choices = c('Labels','Zooming'),
selected = 'Labels',
inline = TRUE)
)
})
# NGRAMdisplay
output$nGramBarchart <- renderPlotly({
req(input$nGramLengthID)
if (input$Label_or_Zoom_3 == 'Labels')
ng_bar_chart(
threadedEventsViz(),
"threadNum",
'label',
input$nGramLengthID,
input$nGramDisplayThresholdID)
else
ng_bar_chart(
threadedEventsViz(),
"threadNum",
get_Zoom_VIZ(),
input$nGramLengthID,
input$nGramDisplayThresholdID)
})
#### Whole Sequences sub-tab ####
# Whole sequence display -- allow alternatives
output$WholeSequenceThreadMap_Sequence <- renderPlotly({ threadMap(threadedEventsViz(), "threadNum", "seqNum", get_Zoom_VIZ(), 15)})
output$WholeSequenceThreadMap_ActualTime <- renderPlotly({ threadMap(threadedEventsViz(), "threadNum", "tStamp", get_Zoom_VIZ(), 15)})
output$WholeSequenceThreadMap_RelativeTime <- renderPlotly({ threadMap(threadedEventsViz(), "threadNum", "relativeTime", get_Zoom_VIZ(), 15)})
#### Event Network (circle) sub-tab ####
# use this to select how to color the nodes in force layout
output$Circle_Network_Tab_Controls <- renderUI({
tags$div(
downloadButton('downloadNetwork', 'Export this Network', class="dlButton"),
sliderInput("circleEdgeTheshold","Display edges above", 0,1,0,step = 0.01,ticks = FALSE ),
radioButtons(
"Label_or_Zoom_1",
"Do you prefer:",
choices = c('Labels','Zooming'),
selected = 'Labels',
inline = TRUE)
)
})
# Create the network to be exported and also displayed
viz_net <<- reactive({
req(input$circleEdgeTheshold)
# first convert the threads to the network
if (input$Label_or_Zoom_1 == 'Labels')
{ n <- threads_to_network_original(threadedEventsViz(), "threadNum", 'label') }
else
{ n <- threads_to_network_original(threadedEventsViz(), "threadNum", get_Zoom_VIZ()) }
# filter out the edges if desired
n <- filter_network_edges(n,input$circleEdgeTheshold)
n
})
output$circleVisNetwork <- renderVisNetwork({
req(input$circleEdgeTheshold)
circleVisNetwork(viz_net(), 'directed', TRUE)
})
# output$circleVisNetwork <- renderVisNetwork({
# req(input$circleEdgeTheshold)
#
# # first convert the threads to the network
# if (input$Label_or_Zoom_1 == 'Labels')
# { n <- threads_to_network_original(threadedEventsViz(), "threadNum", 'label') }
# else
# { n <- threads_to_network_original(threadedEventsViz(), "threadNum", get_Zoom_VIZ()) }
#
# # filter out the edges if desired
# n <- filter_network_edges(n,input$circleEdgeTheshold)
# circleVisNetwork(n, 'directed', TRUE)
# })
#### Other Networks sub-tab ####
# use this to select how to color the nodes in force layout
output$Other_Network_Tab_Controls <- renderUI({
button_choices <- get_POV_EVENT_CF( input$VisualizeEventMapInputID )
tags$div(
radioButtons(
"OtherNetworkCF",
"Graph co-occurrence relation between:",
choices = button_choices,
selected = button_choices[1], # always start with the first one
inline = TRUE
),
sliderInput("otherEdgeTheshold","Display edges above",0,1,0,step = 0.01,ticks = FALSE)
)
})
output$otherVisNetwork <- renderVisNetwork({
req(input$otherEdgeTheshold)
# first convert the threads to the network
n <- normalNetwork(threadedEventsViz(), selectOccFilter(), input$OtherNetworkCF)
n <- filter_network_edges(n,input$otherEdgeTheshold)
circleVisNetwork(n, 'nondirected')
})
#### Event Network (force) sub-tab ####
# use this to select how to color the nodes in force layout
output$Force_Network_Tab_Controls <- renderUI({
button_choices <- intersect(colnames(threadedEventsViz()), cfnames(selectOccFilter()))
tags$div(
radioButtons(
"NetworkGroupID",
"Select a dimension for coloring nodes:",
choices = button_choices,
selected = button_choices[1], # always start with the first one
inline=TRUE
),
sliderInput("forceEdgeTheshold","Display edges above",0,1,0,step = 0.01,ticks = FALSE),
radioButtons(
"Label_or_Zoom_2",
"Do you prefer:",
choices = c('Labels','Zooming'),
selected = 'Labels',
inline = TRUE)
)
})
output$forceNetworkD3 <- renderForceNetwork({
req(input$forceEdgeTheshold)
if (input$Label_or_Zoom_2 == 'Labels')
{ n <- threads_to_network_original(threadedEventsViz(), 'threadNum', 'label', input$NetworkGroupID) }
else
{ n <- threads_to_network_original(threadedEventsViz(), 'threadNum', get_Zoom_VIZ(), input$NetworkGroupID) }
n <- filter_network_edges(n,input$forceEdgeTheshold)
forceNetworkD3(n)
})
output$networkPie <- renderPlotly({
req(input$Group)
get_group <- input$Group
CF_multi_pie_event(threadedOcc(), threadedEventsViz(), get_POV_EVENT_CF( input$VisualizeEventMapInputID ), get_group, get_Zoom_VIZ())
})
#### View Events sub-tab ####
output$VisualizeCustomNetwork_Controls_0 <- renderUI({
radioButtons("Timesplit2", "Time Measure:", choices = c('seqNum'='seqNum','timeGap'='timeGap'), selected = "seqNum", inline = TRUE)
})
output$VisualizeCustomNetwork_Controls_1 <- renderUI({
selectizeInput("Event",label = "Choose Event:",get_POV_EVENT_CF( input$VisualizeEventMapInputID ) )
})
output$VisualizeCustomNetwork <- renderPlotly({
req(input$Timesplit2, input$Event)
eventNetwork(threadedEventsViz(), "threadNum", input$Event, input$Timesplit2)
})
output$hover <- renderPrint({
d <- event_data("plotly_hover")
if (is.null(d)) "Hover events appear here (unhover to clear)" else d
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (is.null(d)) "Click events appear here" else d
})
#### Role Maps sub-tab ####
output$Role_map_controls <- renderUI({checkboxGroupInput("Role_map_CFs","Pick Two:", get_POV_EVENT_CF( input$VisualizeEventMapInputID ) )})
output$Role_map_output <- renderPlotly({role_map(threadedEventsViz(), selectOccFilter(), input$Role_map_CFs)})
#### Thread Trajectories sub-tab ####
output$ThreadTrajectoriesOutput <- renderPlotly({threadTrajectory(threadedEventsViz())})
##### pie chart display #####
output$visualizePieCharts = renderPlotly({
CF_multi_pie(threadedEventsViz(), get_POV_EVENT_CF( input$VisualizeEventMapInputID ) )
})
# provide a data table view, as well
output$visualizePOVData <-DT::renderDataTable(
threadedEventsViz(),
options = list(autoWidth = TRUE))
|
library(shiny)
library(r2d3)
ui <- fluidPage(
inputPanel(
shiny::selectInput("category", label = "Category:",
choices = c("A","B"), selected = "A")
),
d3Output("d3")
)
server <- function(input, output) {
output$d3 <- renderD3({
test_data <- data.frame(colour = c("red","red","blue","blue"), category = c("A","B","A","B"), number = c(1,2,3,4))
r2d3(
test_data[test_data$category==input$category,],
script = "bars.js",
options = list(x = 'colour', y = 'number')
)
})
}
shinyApp(ui = ui, server = server)
|
/app.R
|
no_license
|
willpratt/r2d3practice
|
R
| false | false | 564 |
r
|
library(shiny)
library(r2d3)
ui <- fluidPage(
inputPanel(
shiny::selectInput("category", label = "Category:",
choices = c("A","B"), selected = "A")
),
d3Output("d3")
)
server <- function(input, output) {
output$d3 <- renderD3({
test_data <- data.frame(colour = c("red","red","blue","blue"), category = c("A","B","A","B"), number = c(1,2,3,4))
r2d3(
test_data[test_data$category==input$category,],
script = "bars.js",
options = list(x = 'colour', y = 'number')
)
})
}
shinyApp(ui = ui, server = server)
|
## ━━━━━━━━━━━━━━━━━━━
## INTRODUCTION TO R
## Ista Zahn
## ━━━━━━━━━━━━━━━━━━━
## Table of Contents
## ─────────────────
## Workshop Materials and Introduction
## Graphical User Interfaces
## Data and Functions
## R packages
## Getting data into R
## Asking R for help
## Data Manipulation
## Basic Statistics and Graphs
## Wrap-up
## Exercise solutions
## Workshop Materials and Introduction
## ═══════════════════════════════════
## Materials and setup
## ───────────────────
## Lab computer users: Log in using the user name and password on the
## board to your left.
## Laptop users: You should have R installed –if not:
## • Open a web browser and go to [http://cran.r-project.org] and
## download and install it
## • Also helpful to install RStudio (download from [http://rstudio.com])
## Everyone: Download workshop materials:
## • Download materials from
## [http://tutorials.iq.harvard.edu/R/Rintro.zip]
## • Extract the zip file containing the materials to your desktop
## What is R?
## ──────────
## R is a /programming language designed for statistical computing/.
## Notable characteristics include:
## • Vast capabilities, wide range of statistical and graphical
## techniques
## • Very popular in academia, growing popularity in business:
## [http://r4stats.com/articles/popularity/]
## • Written primarily by statisticians
## • FREE (no cost, open source)
## • Excellent community support: mailing list, blogs, tutorials
## • Easy to extend by writing new functions
## InspiRation
## ───────────
## OK, it's free and popular, but what makes R worth learning? In a word,
## "packages". If you have a data manipulation, analysis or visualization
## task, chances are good that there is an R package for that. For
## example:
## • Want to interactively explore the shape of the Churyumov–Gerasimenko
## comet?
library(rgl)
open3d()
comet <- readOBJ(url("http://sci.esa.int/science-e/www/object/doc.cfm?fobjectid=54726"))
shade3d(comet, col="gray")
writeWebGL(dir="images", filename = "images/comet.html")
## • Want to find out where we are?
library(ggmap)
nwbuilding <- geocode("52 Oxford Street, Cambridge, MA")
ggmap(get_map("Cambridge, MA", zoom = 15)) +
geom_point(data=nwbuilding, size = 7, shape = 13, color = "red")
## • Want to forecast the population of Australia?
library(forecast)
fit <- auto.arima(austres)
## Projected numbers (in thousands) of Australian residents
plot(forecast(fit))
## Whatever you're trying to do, you're probably not the first to try
## doing it R. Chances are good that someone has already written a
## package for that.
## Coming to R
## ───────────
## Coming from…
## Stata: [http://www.princeton.edu/~otorres/RStata.pdf]
## SAS/SPSS: [http://www.et.bs.ehu.es/~etptupaf/pub/R/RforSAS&SPSSusers.pdf]
## matlab: [http://www.math.umaine.edu/~hiebeler/comp/matlabR.pdf]
## Python: [http://mathesaurus.sourceforge.net/matlab-python-xref.pdf]
## Graphical User Interfaces
## ═════════════════════════
## R GUI alternatives (no GUI)
## ───────────────────────────
## The old-school way is to run R directly in a terminal
## But hardly anybody does it that way anymore!
## R GUI alternatives (Windows default)
## ────────────────────────────────────
## The default windows GUI is not very good
## • No parentheses matching or syntax highlighting
## • No work-space browser
## R GUI Alternatives (Rstudio on Mac)
## ───────────────────────────────────
## Rstudio has many useful features, including parentheses matching and
## auto-completion
## R GUI Alternatives (Emacs with ESS)
## ───────────────────────────────────
## Emacs + ESS is a very powerful combination, but can be difficult to
## set up
## Launch RStudio :labsetup:
## ──────────────
## • Open the RStudio program
## • Open up today's R script
## • In RStudio, Go to *File => Open Script*
## • Locate and open the `Rintro.R' script in the Rintro folder on your
## desktop
## • Go to *Tools => Set working directory => To source file location*
## (more on the working directory later)
## • I encourage you to add your own notes to this file! Every line that
## starts with `#' is a comment that will be ignored by R. My comments
## all start with `##'; you can add your own, possibly using `#' or
## `###' to distinguish your comments from mine.
## Exercise 0
## ──────────
## The purpose of this exercise is mostly to give you an opportunity to
## explore the interface provided by RStudio (or whichever GUI you've
## decided to use). You may not know how to do these things; that's fine!
## This is an opportunity to learn. If you don't know how to do something
## you can can use internet search engines, search on [StackOverflow], or
## ask the person next to you.
## Also keep in mind that we are living in a golden age of tab
## completion. If you don't know the name of an R function, try guessing
## the first two or three letters and pressing TAB. If you guessed
## correctly the function you are looking for should appear in a pop up!
## 1. Try to get R to add 2 plus 2.
## 2. Try to calculate the square root of 10.
## 3. There is an R package named `car' (Companion to Applied
## Regression). Try to install this package.
## 4. R includes extensive documentation, including a file named "An
## introduction to R". Try to find this help file.
## 5. Go to [http://cran.r-project.org/web/views/] and skim the topic
## closest to your field/interests.
## [StackOverflow] http:stackoverflow.com
## Data and Functions
## ══════════════════
## Assignment
## ──────────
## Values can be assigned names and used in subsequent operations
## • The `<-' operator (less than followed by a dash) is used to save
## values
## • The name on the left gets the value on the right.
x <- 10 # Assign the value 10 to a variable named x
x + 1 # Add 1 to x
y <- x + 1 # Assign y the value x + 1
y
## Saved variables can be listed, overwritten and deleted
ls() # List variables in workspace
x # Print the value of x
x <- 100 # Overwrite x. Note that no warning is given!
x
rm(x) # Delete x
ls()
## Functions
## ─────────
## Using R is mostly about applying *functions* to *variables*. Functions
## • take *variable(s)* as input *argument(s)*
## • perform operations
## • *return* values which can be *assigned*
## • optionally perform side-effects such as writing a file to disk or
## opening a graphics window
## The general form for calling R functions is `FunctionName(arg.1,
## arg.2, ... arg.n)'
## Arguments can be matched by position or name
## Examples:
#?sqrt
a <- sqrt(y) # Call the sqrt function with argument x=y
round(a, digits = 2) # Call round() with arguments x=x and digits=2
# Functions can be nested so an alternative is
round(sqrt(y), digits = 5) # Take sqrt of a and round
## R packages
## ══════════
## There are thousands of R packages that extend R's capabilities.
## • To see what packages are loaded:
## `search()'
## • To view available packages:
## `library()'
## • To load a package:
## `library("car")'
## • Install new package:
## `install.packages("stringdist")'
## Getting data into R
## ═══════════════════
## The gss dataset
## ───────────────
## The next few examples use a subset of the General Social Survey data
## set. The variables in this subset include
head(read.csv("dataSets/gssInfo.csv"))
#see gssInfo.csv for rest of the variable descriptions
## The "working directory" and listing files
## ─────────────────────────────────────────
## R knows the directory it was started in, and refers to this as the
## "working directory". Since our workshop examples are in the Rintro
## folder on the desktop, we should all take a moment to set that as our
## working directory:
setwd("~/Desktop/Rintro")
## We can also set the working directory using paths relative to the
## current working directory:
getwd() # get the current working directory
setwd("dataSets") # set wd to the dataSets folder
getwd()
setwd("..") # set wd to enclosing folder ("up")
## It can be convenient to list files in a directory without leaving R
list.files("dataSets") # list files in the dataSets folder
# list.files("dataSets", pattern = ".csv") # restrict to .csv files
## Importing data from files the easy way
## ──────────────────────────────────────
## In order to read data from a file, you usually have to know what kind
## of file it is. The table below lists some common data types.
## ━━━━━━━━━━━━━━━━━━━━━━━━
## Common data types
## ────────────────────────
## comma separated (.csv)
## Stata (.dta)
## SPSS (.sav)
## SAS (.sas7bdat)
## Excel (.xls, .xlsx)
## ━━━━━━━━━━━━━━━━━━━━━━━━
## R is smart enough to recognize most common file formats for us using
## the `import()' function. To use this functionality we first need to
## install and attache the `rio' package.
## install and load the rio package
# install.packages("rio")
library(rio)
## import data from a variety of formats
# read gss data from the gss.rds R file
datGSS <- import("dataSets/gss.rds")
# read gss data from the gss.csv comma separated file
gss.data <- import("dataSets/gss.csv")
# read a Stata dataset from gss.dta
datGSS <- import("dataSets/gss.dta")
## Importing data from files the hard way
## ──────────────────────────────────────
## In order to read data from a file, you have to know what kind of file
## it is. The table below lists the functions needed to import data from
## common file formats.
## ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## data type function package
## ──────────────────────────────────────────────────────────────────────
## comma separated (.csv) read.csv() utils (default)
## other delimited formats read.table() utils (default)
## Stata version 7-12 (.dta) read.dta() foreign
## Stata version 13-14 (.dta) read_dta() haven
## SPSS (.sav) read.spss() foreign
## SAS (.sas7bdat) read.sas7bdat() sas7bdat
## Excel (.xls, .xlsx) readWorksheetFromFile() XLConnect
## ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## Examples:
# read gss data from the gss.rds R file
datGSS <- readRDS("dataSets/gss.rds")
# read gss data from the gss.csv comma separated file
gss.data <- read.csv("dataSets/gss.csv") # read gss data
# read a Stata dataset from gss.dta
library(foreign) # load foreign data functions
datGSS <- read.dta(file="dataSets/gss.dta")
## Checking imported data
## ──────────────────────
## Always a good idea to examine the imported data set–usually we want
## the results to be a `data.frame'
class(datGSS) # check to see that test is what we expect it to be
dim(datGSS) # how many rows and columns?
names(datGSS) # or colnames(datGSS)
str(datGSS[1:10]) # more details about the first 10 columns
## Saving and loading R workspaces
## ────────────────────────────────
## In addition to importing individual datasets, R can save and load
## entire workspaces
## • Save our entire workspace
ls() # list objects in our workspace
save.image(file="myWorkspace.RData") # save workspace
rm(list=ls()) # remove all objects from our workspace
ls() # list stored objects to make sure they are deleted
## • Load the "myWorkspace.RData" file and check that it is restored
load("myWorkspace.RData") # load myWorkspace.RData
ls() # list objects
## When you close R you will be asked if you want to save your workspace
## – if you choose yes then your workspace will be restored next time you
## start R
## Exercise 1
## ──────────
## 1. Install and attach the `rio' package if you haven't already done so
## 2. Read the SPSS data set in dataSets/gss.sav and assign the result to
## an R data object named GSS.sav
## 3. Make sure that the data loaded in step 2 is a data.frame
## 4. Display the dimensions of the GSS.sav
## 5. BONUS: figure out how to read the Excel file "gss.xlsx" into R
## Asking R for help
## ═════════════════
## R has extensive built-in documentation that can be accessed through R
## commands or through the GUI.
## • Start html help, search/browse using web browser
## • at the R console:
## `help.start()'
## • or use the help menu from you GUI
## • Look up the documentation for a function
## `help(plot)'
## `?kmeans'
## • Look up documentation for a package
## `help(package="stats")'
## • Search documentation from R (not always the best way… google often
## works better)
## `help.search("classification")'
## Data Manipulation
## ═════════════════
## data.frame objects
## ──────────────────
## • Usually data read into R will be stored as a *data.frame*
## • A data.frame is a list of vectors of equal length
## • Each vector in the list forms a column
## • Each column can be a differnt type of vector
## • Often the columns are variables and the rows are observations
## • A data.frame has two dimensions corresponding the number of rows and
## the number of columns (in that order)
## Extracting subsets of data.frames
## ─────────────────────────────────
## You can extract subsets of data.frames using the `subset()'
## function[1]. Use the `select' argument to select columns:
# selecting specifig columns
head(# first n rows
subset(datGSS,
select = 1:4 # column 1 to 5
),
n = 10# show first 10 rows
)
## and the `subset' argument to select rows:
subset(datGSS,
# rows where age > 90
subset = age > 90,
## sex and age columns
select = c("sex", "age"))
## the $ operator can be used to extract a single column
str(datGSS$age)
## In the previous example we used `>' to select rows where age was
## greater than 90. Other relational and logical operators are listed
## below.
## ==: equal to
## !=: not equal to
## >: greater than
## <: less than
## >=: greater than or equal to
## <=: less than or equal to
## &: and
## |: or
## Transforming data.frames
## ────────────────────────
## You can modify data.frames using the `transform()' function.
# creating new variable mean centered age
datGSS <- transform(datGSS,
ageC = age - mean(age))
#education difference between wifes and husbands
datGSS <- transform(datGSS,
educ.diff = wifeduc - husbeduc)
datGSS$wifeduc_comp <- ifelse(
is.na(datGSS$wifeduc), #condition
mean(datGSS$wifeduc, na.rm=TRUE), # value if condition met
datGSS$wifeduc) # value otherwise
## examine our newly created variables
head(subset(datGSS,
select = c("age", "ageC", "wifeduc", "wifeduc_comp",
"husbeduc", "educ.diff")), n = 8)
## Note that `transform' is a convenience function; see `?Extract' for a
## more powerful way to modify data.frames.
## Exporting Data
## ──────────────
## Now that we have made some changes to our GSS data set, we might want
## to save those changes to a file. Everything we have done so far has
## only modified the data in R; the files have remained unchanged.
# write data to a .csv file
write.csv(datGSS, file = "gss.csv")
# write data to a Stata file
write.dta(datGSS, file = "gss.dta")
# write data to an R file
saveRDS(datGSS, file = "gss.rds")
## Exercise 2: Data manipulation
## ─────────────────────────────
## Use the gss.rds data set
## 1. Generate the following variables:
## • "rich" equal to 0 if rincdol is less than 100000, and 1 otherwise
## • "sinc" equal to incomdol - rincdol
## 2. Create a subset of the data containing only rows where "usecomp" =
## "Yes"
## 3. Examine the data.frame created in step 2, and answer the following
## questions:
## • How many rows does it have?
## • How many columns does it have?
## • What is the class of the "satjob" variable?
## 4. BONUS (hard): Generate a variable named "dual.earn" equal to 1 if
## both wkftwife = 1 and wkfthusb = 1, and zero otherwise
## Basic Statistics and Graphs
## ═══════════════════════════
## Basic statistics
## ────────────────
## Descriptive statistics of single variables are straightforward:
mean(datGSS$educ) # calculate mean value of education
sd(datGSS$educ) # calculate standard deviation of x
# calculate min, max, quantiles, mean of educ, age, and ageC
summary(subset(datGSS, select = c("educ", "age", "ageC")))
## Some of these functions (e.g., summary) will also work with
## data.frames and other types of objects, others (such as `sd') will
## not.
## Counts and proportions
## ──────────────────────
## Start by using the `table()' function to tabulate counts, then perform
## additional computations if needed
sex.counts <- table(datGSS$sex) # tabulate sex categories
sex.counts
prop.table(sex.counts) # convert to proportions
## Add variables for crosstabs
table(subset(datGSS, select = c("sex", "happy"))) # crosstab marital X happy
## Statistics by classification factors
## ────────────────────────────────────
## The `by()' function can be used to perform a calculation separately
## for each level of a classifying variable
by(subset(datGSS, select = c("income", "educ")),
INDICES=datGSS["sex"],
FUN=summary)
## Correlations
## ────────────
## Let's look at correlations among between age, income, and education
cor(subset(datGSS, select = c("age", "incomdol", "educ")))
## For significance tests, use cor.test()
with(datGSS,
cor.test(age, educ))
## Multiple regression
## ───────────────────
## Modeling functions generally use the /formula/ interface whith DV on
## left followed by "~" followed by predictors–for details see
## `help("formula")'
## • Predict the number of hours individuals spend on email (emailhrs)
m1 <- lm(educ ~ sex + age, data = datGSS)
summary(m1)
## Save R output to a file
## ───────────────────────
## Earlier we learned how to write a data set to a file. But what if we
## want to write something that isn't in a nice rectangular format, like
## the results of our regression model? For that we can use the `sink()'
## function:
sink(file="output.txt", split=TRUE) # start logging
print("This is the result from model 1\n")
print(summary(m1))
sink() ## sink with no arguments turns logging off
## Basic graphics: Frequency bars
## ──────────────────────────────
## Thanks to classes and methods, you can `plot()' many kinds of objects:
plot(datGSS$marital) # Plot a factor
## Basic graphics: Boxplots by group
## ─────────────────────────────────
## Thanks to classes and methods, you can `plot()' many kinds of objects:
with(datGSS,
plot(marital, educ)) # Plot ordinal by numeric
## Basic graphics: Mosaic chart
## ────────────────────────────
## Thanks to classes and methods, you can `plot()' many kinds of objects:
with(datGSS, # Plot factor X factor
plot(marital, happy))
## Exercise 3
## ──────────
## Using the datGSS data.frame
## 1. Cross-tabulate sex and emailhrs
## 2. Calculate the mean and standard deviation of incomdol by sex
## 3. Save the results of the previous two calculations to a file
## 4. Create a scatter plot with educ on the x-axis and incomdol on the
## y-axis
## Wrap-up
## ═══════
## Help us make this workshop better!
## ──────────────────────────────────
## • Please take a moment to fill out a very short feedback form
## • These workshops exist for you – tell us what you need!
## • [http://tinyurl.com/R-intro-feedback]
## Additional resources
## ────────────────────
## • IQSS workshops:
## [http://projects.iq.harvard.edu/rtc/filter_by/workshops]
## • IQSS statistical consulting: [http://rtc.iq.harvard.edu]
## • Software (all free!):
## • R and R package download: [http://cran.r-project.org]
## • Rstudio download: [http://rstudio.org]
## • ESS (emacs R package): [http://ess.r-project.org/]
## • Online tutorials
## • [http://www.codeschool.com/courses/try-r]
## • [http://www.datamind.org]
## • Getting help:
## • Documentation and tutorials:
## [http://cran.r-project.org/other-docs.html]
## • Recommended R packages by topic:
## [http://cran.r-project.org/web/views/]
## • Mailing list: [https://stat.ethz.ch/mailman/listinfo/r-help]
## • StackOverflow: [http://stackoverflow.com/questions/tagged/r]
## Exercise solutions
## ══════════════════
## Exercise 0 solution :prototype:
## ───────────────────
## 1) ] Try to get R to add 2 plus 2.
2 + 2
## 2) Try to figure out how evaluate lines directly from your R script.
## `In Rstudo this is 'Control-Enter'; may be different in another GUI'
## 3) R includes extensive documentation, including a file named "An
## introduction to R". Try to find this help file.
## `Go to the main help page by running 'help.start() or using the GUI
## menu, find and click on the link to "An Introduction to R".'
## 4) Go to [http://cran.r-project.org/web/views/] and skim the topic
## closest to your field/interests.
## `I like the machine learning topic!'
## Exercise 1 solution :prototype:
## ───────────────────
## 1) Attach the `rio' package if you haven't already done so
## install.packages("rio")
library(rio)
## 2) Read the SPSS data set in dataSets/gss.sav and assign the result to
## an R data object named GSS.sav
gss.data <- import("dataSets/gss.sav")
## 3) Make sure that the data loaded in step 2 is a data.frame (hint:
## check the arguments documented in the help page)
class(gss.data)
## 4) Display the dimensions of the GSS.sav.
dim(gss.data)
nrow(gss.data)
ncol(gss.data)
## 6) BONUS: figure out how to read the Excel file "gss.xlsx" into R
dat <- import("dataSets/gss.xlsx")
class(dat); dim(dat)
## Exercise 2 solution :prototype:
## ───────────────────
## Use the gss.rds data set
gss <- import("dataSets/gss.rds")
## 1) Create a subset of the data containing only rows where "usecomp" =
## "Yes". How many computer users are there?
gss.usecomp <- subset(gss, usecomp == "Yes")
nrow(gss.usecomp)
## 2) Generate the following variables:
## • "rich" equal to 0 if rincdol is less than 100000, and 1 otherwise
## • "sinc" equal to incomdol - rincdol
gss <- transform(gss,
rich = ifelse(rincdol < 100000, 0, 1),
sinc = incomdol - rincdol)
head(subset(gss, select = c("rincdol", "incomdol", "rich", "sinc")))
## 3) Generate a variable named "dual.earn" equal to 1 if both wkftwife =
## 1 and wkfthusb = 1, and zero otherwise. How many dual earners are
## there?
gss$dual.earn <- ifelse(gss$wkftwife == 1 & gss$wkfthusb == 1, 1, 0)
nrow(subset(gss, dual.earn == 1))
## Exercise 3 solution :prototype:
## ───────────────────
## Using the datGSS data.frame
## 1) Cross-tabulate sex and emailhrs
with(datGSS, table(emailhrs, sex))
## 2) Calculate the mean and standard deviation of incomdol by sex
by(datGSS$incomdol, datGSS$sex, mean)
by(datGSS$incomdol, datGSS$sex, sd)
## 3) Create a scatter plot with educ on the x-axis and incomdol on the
## y-axis
plot(subset(datGSS, select = c("educ", "incomdol")))
## `That first attempt is pretty ugly, let's clean it up.'
plot(log(incomdol) ~ jitter(educ, 8), # formula interface with log an jitter
data = subset(datGSS, # subsetting data as part of the plot call
subset = educ < 97),
cex = .6 # make points smaller
)
## Footnotes
## ─────────
## [1] Note that `subset()' is a convenience function; see `?Extract' for a
## more powerful (and complicated) way to subset data.
|
/R/Rintro/Rintro.R
|
no_license
|
Iblouse/workshops
|
R
| false | false | 27,622 |
r
|
## ━━━━━━━━━━━━━━━━━━━
## INTRODUCTION TO R
## Ista Zahn
## ━━━━━━━━━━━━━━━━━━━
## Table of Contents
## ─────────────────
## Workshop Materials and Introduction
## Graphical User Interfaces
## Data and Functions
## R packages
## Getting data into R
## Asking R for help
## Data Manipulation
## Basic Statistics and Graphs
## Wrap-up
## Exercise solutions
## Workshop Materials and Introduction
## ═══════════════════════════════════
## Materials and setup
## ───────────────────
## Lab computer users: Log in using the user name and password on the
## board to your left.
## Laptop users: You should have R installed –if not:
## • Open a web browser and go to [http://cran.r-project.org] and
## download and install it
## • Also helpful to install RStudio (download from [http://rstudio.com])
## Everyone: Download workshop materials:
## • Download materials from
## [http://tutorials.iq.harvard.edu/R/Rintro.zip]
## • Extract the zip file containing the materials to your desktop
## What is R?
## ──────────
## R is a /programming language designed for statistical computing/.
## Notable characteristics include:
## • Vast capabilities, wide range of statistical and graphical
## techniques
## • Very popular in academia, growing popularity in business:
## [http://r4stats.com/articles/popularity/]
## • Written primarily by statisticians
## • FREE (no cost, open source)
## • Excellent community support: mailing list, blogs, tutorials
## • Easy to extend by writing new functions
## InspiRation
## ───────────
## OK, it's free and popular, but what makes R worth learning? In a word,
## "packages". If you have a data manipulation, analysis or visualization
## task, chances are good that there is an R package for that. For
## example:
## • Want to interactively explore the shape of the Churyumov–Gerasimenko
## comet?
library(rgl)
open3d()
comet <- readOBJ(url("http://sci.esa.int/science-e/www/object/doc.cfm?fobjectid=54726"))
shade3d(comet, col="gray")
writeWebGL(dir="images", filename = "images/comet.html")
## • Want to find out where we are?
library(ggmap)
nwbuilding <- geocode("52 Oxford Street, Cambridge, MA")
ggmap(get_map("Cambridge, MA", zoom = 15)) +
geom_point(data=nwbuilding, size = 7, shape = 13, color = "red")
## • Want to forecast the population of Australia?
library(forecast)
fit <- auto.arima(austres)
## Projected numbers (in thousands) of Australian residents
plot(forecast(fit))
## Whatever you're trying to do, you're probably not the first to try
## doing it R. Chances are good that someone has already written a
## package for that.
## Coming to R
## ───────────
## Coming from…
## Stata: [http://www.princeton.edu/~otorres/RStata.pdf]
## SAS/SPSS: [http://www.et.bs.ehu.es/~etptupaf/pub/R/RforSAS&SPSSusers.pdf]
## matlab: [http://www.math.umaine.edu/~hiebeler/comp/matlabR.pdf]
## Python: [http://mathesaurus.sourceforge.net/matlab-python-xref.pdf]
## Graphical User Interfaces
## ═════════════════════════
## R GUI alternatives (no GUI)
## ───────────────────────────
## The old-school way is to run R directly in a terminal
## But hardly anybody does it that way anymore!
## R GUI alternatives (Windows default)
## ────────────────────────────────────
## The default windows GUI is not very good
## • No parentheses matching or syntax highlighting
## • No work-space browser
## R GUI Alternatives (Rstudio on Mac)
## ───────────────────────────────────
## Rstudio has many useful features, including parentheses matching and
## auto-completion
## R GUI Alternatives (Emacs with ESS)
## ───────────────────────────────────
## Emacs + ESS is a very powerful combination, but can be difficult to
## set up
## Launch RStudio :labsetup:
## ──────────────
## • Open the RStudio program
## • Open up today's R script
## • In RStudio, Go to *File => Open Script*
## • Locate and open the `Rintro.R' script in the Rintro folder on your
## desktop
## • Go to *Tools => Set working directory => To source file location*
## (more on the working directory later)
## • I encourage you to add your own notes to this file! Every line that
## starts with `#' is a comment that will be ignored by R. My comments
## all start with `##'; you can add your own, possibly using `#' or
## `###' to distinguish your comments from mine.
## Exercise 0
## ──────────
## The purpose of this exercise is mostly to give you an opportunity to
## explore the interface provided by RStudio (or whichever GUI you've
## decided to use). You may not know how to do these things; that's fine!
## This is an opportunity to learn. If you don't know how to do something
## you can can use internet search engines, search on [StackOverflow], or
## ask the person next to you.
## Also keep in mind that we are living in a golden age of tab
## completion. If you don't know the name of an R function, try guessing
## the first two or three letters and pressing TAB. If you guessed
## correctly the function you are looking for should appear in a pop up!
## 1. Try to get R to add 2 plus 2.
## 2. Try to calculate the square root of 10.
## 3. There is an R package named `car' (Companion to Applied
## Regression). Try to install this package.
## 4. R includes extensive documentation, including a file named "An
## introduction to R". Try to find this help file.
## 5. Go to [http://cran.r-project.org/web/views/] and skim the topic
## closest to your field/interests.
## [StackOverflow] http:stackoverflow.com
## Data and Functions
## ══════════════════
## Assignment
## ──────────
## Values can be assigned names and used in subsequent operations
## • The `<-' operator (less than followed by a dash) is used to save
## values
## • The name on the left gets the value on the right.
x <- 10 # Assign the value 10 to a variable named x
x + 1 # Add 1 to x
y <- x + 1 # Assign y the value x + 1
y
## Saved variables can be listed, overwritten and deleted
ls() # List variables in workspace
x # Print the value of x
x <- 100 # Overwrite x. Note that no warning is given!
x
rm(x) # Delete x
ls()
## Functions
## ─────────
## Using R is mostly about applying *functions* to *variables*. Functions
## • take *variable(s)* as input *argument(s)*
## • perform operations
## • *return* values which can be *assigned*
## • optionally perform side-effects such as writing a file to disk or
## opening a graphics window
## The general form for calling R functions is `FunctionName(arg.1,
## arg.2, ... arg.n)'
## Arguments can be matched by position or name
## Examples:
#?sqrt
a <- sqrt(y) # Call the sqrt function with argument x=y
round(a, digits = 2) # Call round() with arguments x=x and digits=2
# Functions can be nested so an alternative is
round(sqrt(y), digits = 5) # Take sqrt of a and round
## R packages
## ══════════
## There are thousands of R packages that extend R's capabilities.
## • To see what packages are loaded:
## `search()'
## • To view available packages:
## `library()'
## • To load a package:
## `library("car")'
## • Install new package:
## `install.packages("stringdist")'
## Getting data into R
## ═══════════════════
## The gss dataset
## ───────────────
## The next few examples use a subset of the General Social Survey data
## set. The variables in this subset include
head(read.csv("dataSets/gssInfo.csv"))
#see gssInfo.csv for rest of the variable descriptions
## The "working directory" and listing files
## ─────────────────────────────────────────
## R knows the directory it was started in, and refers to this as the
## "working directory". Since our workshop examples are in the Rintro
## folder on the desktop, we should all take a moment to set that as our
## working directory:
setwd("~/Desktop/Rintro")
## We can also set the working directory using paths relative to the
## current working directory:
getwd() # get the current working directory
setwd("dataSets") # set wd to the dataSets folder
getwd()
setwd("..") # set wd to enclosing folder ("up")
## It can be convenient to list files in a directory without leaving R
list.files("dataSets") # list files in the dataSets folder
# list.files("dataSets", pattern = ".csv") # restrict to .csv files
## Importing data from files the easy way
## ──────────────────────────────────────
## In order to read data from a file, you usually have to know what kind
## of file it is. The table below lists some common data types.
## ━━━━━━━━━━━━━━━━━━━━━━━━
## Common data types
## ────────────────────────
## comma separated (.csv)
## Stata (.dta)
## SPSS (.sav)
## SAS (.sas7bdat)
## Excel (.xls, .xlsx)
## ━━━━━━━━━━━━━━━━━━━━━━━━
## R is smart enough to recognize most common file formats for us using
## the `import()' function. To use this functionality we first need to
## install and attache the `rio' package.
## install and load the rio package
# install.packages("rio")
library(rio)
## import data from a variety of formats
# read gss data from the gss.rds R file
datGSS <- import("dataSets/gss.rds")
# read gss data from the gss.csv comma separated file
gss.data <- import("dataSets/gss.csv")
# read a Stata dataset from gss.dta
datGSS <- import("dataSets/gss.dta")
## Importing data from files the hard way
## ──────────────────────────────────────
## In order to read data from a file, you have to know what kind of file
## it is. The table below lists the functions needed to import data from
## common file formats.
## ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## data type function package
## ──────────────────────────────────────────────────────────────────────
## comma separated (.csv) read.csv() utils (default)
## other delimited formats read.table() utils (default)
## Stata version 7-12 (.dta) read.dta() foreign
## Stata version 13-14 (.dta) read_dta() haven
## SPSS (.sav) read.spss() foreign
## SAS (.sas7bdat) read.sas7bdat() sas7bdat
## Excel (.xls, .xlsx) readWorksheetFromFile() XLConnect
## ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## Examples:
# read gss data from the gss.rds R file
datGSS <- readRDS("dataSets/gss.rds")
# read gss data from the gss.csv comma separated file
gss.data <- read.csv("dataSets/gss.csv") # read gss data
# read a Stata dataset from gss.dta
library(foreign) # load foreign data functions
datGSS <- read.dta(file="dataSets/gss.dta")
## Checking imported data
## ──────────────────────
## Always a good idea to examine the imported data set–usually we want
## the results to be a `data.frame'
class(datGSS) # check to see that test is what we expect it to be
dim(datGSS) # how many rows and columns?
names(datGSS) # or colnames(datGSS)
str(datGSS[1:10]) # more details about the first 10 columns
## Saving and loading R workspaces
## ────────────────────────────────
## In addition to importing individual datasets, R can save and load
## entire workspaces
## • Save our entire workspace
ls() # list objects in our workspace
save.image(file="myWorkspace.RData") # save workspace
rm(list=ls()) # remove all objects from our workspace
ls() # list stored objects to make sure they are deleted
## • Load the "myWorkspace.RData" file and check that it is restored
load("myWorkspace.RData") # load myWorkspace.RData
ls() # list objects
## When you close R you will be asked if you want to save your workspace
## – if you choose yes then your workspace will be restored next time you
## start R
## Exercise 1
## ──────────
## 1. Install and attach the `rio' package if you haven't already done so
## 2. Read the SPSS data set in dataSets/gss.sav and assign the result to
## an R data object named GSS.sav
## 3. Make sure that the data loaded in step 2 is a data.frame
## 4. Display the dimensions of the GSS.sav
## 5. BONUS: figure out how to read the Excel file "gss.xlsx" into R
## Asking R for help
## ═════════════════
## R has extensive built-in documentation that can be accessed through R
## commands or through the GUI.
## • Start html help, search/browse using web browser
## • at the R console:
## `help.start()'
## • or use the help menu from you GUI
## • Look up the documentation for a function
## `help(plot)'
## `?kmeans'
## • Look up documentation for a package
## `help(package="stats")'
## • Search documentation from R (not always the best way… google often
## works better)
## `help.search("classification")'
## Data Manipulation
## ═════════════════
## data.frame objects
## ──────────────────
## • Usually data read into R will be stored as a *data.frame*
## • A data.frame is a list of vectors of equal length
## • Each vector in the list forms a column
## • Each column can be a differnt type of vector
## • Often the columns are variables and the rows are observations
## • A data.frame has two dimensions corresponding the number of rows and
## the number of columns (in that order)
## Extracting subsets of data.frames
## ─────────────────────────────────
## You can extract subsets of data.frames using the `subset()'
## function[1]. Use the `select' argument to select columns:
# selecting specifig columns
head(# first n rows
subset(datGSS,
select = 1:4 # column 1 to 5
),
n = 10# show first 10 rows
)
## and the `subset' argument to select rows:
subset(datGSS,
# rows where age > 90
subset = age > 90,
## sex and age columns
select = c("sex", "age"))
## the $ operator can be used to extract a single column
str(datGSS$age)
## In the previous example we used `>' to select rows where age was
## greater than 90. Other relational and logical operators are listed
## below.
## ==: equal to
## !=: not equal to
## >: greater than
## <: less than
## >=: greater than or equal to
## <=: less than or equal to
## &: and
## |: or
## Transforming data.frames
## ────────────────────────
## You can modify data.frames using the `transform()' function.
# creating new variable mean centered age
datGSS <- transform(datGSS,
ageC = age - mean(age))
#education difference between wifes and husbands
datGSS <- transform(datGSS,
educ.diff = wifeduc - husbeduc)
datGSS$wifeduc_comp <- ifelse(
is.na(datGSS$wifeduc), #condition
mean(datGSS$wifeduc, na.rm=TRUE), # value if condition met
datGSS$wifeduc) # value otherwise
## examine our newly created variables
head(subset(datGSS,
select = c("age", "ageC", "wifeduc", "wifeduc_comp",
"husbeduc", "educ.diff")), n = 8)
## Note that `transform' is a convenience function; see `?Extract' for a
## more powerful way to modify data.frames.
## Exporting Data
## ──────────────
## Now that we have made some changes to our GSS data set, we might want
## to save those changes to a file. Everything we have done so far has
## only modified the data in R; the files have remained unchanged.
# write data to a .csv file
write.csv(datGSS, file = "gss.csv")
# write data to a Stata file
write.dta(datGSS, file = "gss.dta")
# write data to an R file
saveRDS(datGSS, file = "gss.rds")
## Exercise 2: Data manipulation
## ─────────────────────────────
## Use the gss.rds data set
## 1. Generate the following variables:
## • "rich" equal to 0 if rincdol is less than 100000, and 1 otherwise
## • "sinc" equal to incomdol - rincdol
## 2. Create a subset of the data containing only rows where "usecomp" =
## "Yes"
## 3. Examine the data.frame created in step 2, and answer the following
## questions:
## • How many rows does it have?
## • How many columns does it have?
## • What is the class of the "satjob" variable?
## 4. BONUS (hard): Generate a variable named "dual.earn" equal to 1 if
## both wkftwife = 1 and wkfthusb = 1, and zero otherwise
## Basic Statistics and Graphs
## ═══════════════════════════
## Basic statistics
## ────────────────
## Descriptive statistics of single variables are straightforward:
mean(datGSS$educ) # calculate mean value of education
sd(datGSS$educ) # calculate standard deviation of x
# calculate min, max, quantiles, mean of educ, age, and ageC
summary(subset(datGSS, select = c("educ", "age", "ageC")))
## Some of these functions (e.g., summary) will also work with
## data.frames and other types of objects, others (such as `sd') will
## not.
## Counts and proportions
## ──────────────────────
## Start by using the `table()' function to tabulate counts, then perform
## additional computations if needed
sex.counts <- table(datGSS$sex) # tabulate sex categories
sex.counts
prop.table(sex.counts) # convert to proportions
## Add variables for crosstabs
table(subset(datGSS, select = c("sex", "happy"))) # crosstab marital X happy
## Statistics by classification factors
## ────────────────────────────────────
## The `by()' function can be used to perform a calculation separately
## for each level of a classifying variable
by(subset(datGSS, select = c("income", "educ")),
INDICES=datGSS["sex"],
FUN=summary)
## Correlations
## ────────────
## Let's look at correlations among between age, income, and education
cor(subset(datGSS, select = c("age", "incomdol", "educ")))
## For significance tests, use cor.test()
with(datGSS,
cor.test(age, educ))
## Multiple regression
## ───────────────────
## Modeling functions generally use the /formula/ interface whith DV on
## left followed by "~" followed by predictors–for details see
## `help("formula")'
## • Predict the number of hours individuals spend on email (emailhrs)
m1 <- lm(educ ~ sex + age, data = datGSS)
summary(m1)
## Save R output to a file
## ───────────────────────
## Earlier we learned how to write a data set to a file. But what if we
## want to write something that isn't in a nice rectangular format, like
## the results of our regression model? For that we can use the `sink()'
## function:
sink(file="output.txt", split=TRUE) # start logging
print("This is the result from model 1\n")
print(summary(m1))
sink() ## sink with no arguments turns logging off
## Basic graphics: Frequency bars
## ──────────────────────────────
## Thanks to classes and methods, you can `plot()' many kinds of objects:
plot(datGSS$marital) # Plot a factor
## Basic graphics: Boxplots by group
## ─────────────────────────────────
## Thanks to classes and methods, you can `plot()' many kinds of objects:
with(datGSS,
plot(marital, educ)) # Plot ordinal by numeric
## Basic graphics: Mosaic chart
## ────────────────────────────
## Thanks to classes and methods, you can `plot()' many kinds of objects:
with(datGSS, # Plot factor X factor
plot(marital, happy))
## Exercise 3
## ──────────
## Using the datGSS data.frame
## 1. Cross-tabulate sex and emailhrs
## 2. Calculate the mean and standard deviation of incomdol by sex
## 3. Save the results of the previous two calculations to a file
## 4. Create a scatter plot with educ on the x-axis and incomdol on the
## y-axis
## Wrap-up
## ═══════
## Help us make this workshop better!
## ──────────────────────────────────
## • Please take a moment to fill out a very short feedback form
## • These workshops exist for you – tell us what you need!
## • [http://tinyurl.com/R-intro-feedback]
## Additional resources
## ────────────────────
## • IQSS workshops:
## [http://projects.iq.harvard.edu/rtc/filter_by/workshops]
## • IQSS statistical consulting: [http://rtc.iq.harvard.edu]
## • Software (all free!):
## • R and R package download: [http://cran.r-project.org]
## • Rstudio download: [http://rstudio.org]
## • ESS (emacs R package): [http://ess.r-project.org/]
## • Online tutorials
## • [http://www.codeschool.com/courses/try-r]
## • [http://www.datamind.org]
## • Getting help:
## • Documentation and tutorials:
## [http://cran.r-project.org/other-docs.html]
## • Recommended R packages by topic:
## [http://cran.r-project.org/web/views/]
## • Mailing list: [https://stat.ethz.ch/mailman/listinfo/r-help]
## • StackOverflow: [http://stackoverflow.com/questions/tagged/r]
## Exercise solutions
## ══════════════════
## Exercise 0 solution :prototype:
## ───────────────────
## 1) ] Try to get R to add 2 plus 2.
2 + 2
## 2) Try to figure out how evaluate lines directly from your R script.
## `In Rstudo this is 'Control-Enter'; may be different in another GUI'
## 3) R includes extensive documentation, including a file named "An
## introduction to R". Try to find this help file.
## `Go to the main help page by running 'help.start() or using the GUI
## menu, find and click on the link to "An Introduction to R".'
## 4) Go to [http://cran.r-project.org/web/views/] and skim the topic
## closest to your field/interests.
## `I like the machine learning topic!'
## Exercise 1 solution :prototype:
## ───────────────────
## 1) Attach the `rio' package if you haven't already done so
## install.packages("rio")
library(rio)
## 2) Read the SPSS data set in dataSets/gss.sav and assign the result to
## an R data object named GSS.sav
gss.data <- import("dataSets/gss.sav")
## 3) Make sure that the data loaded in step 2 is a data.frame (hint:
## check the arguments documented in the help page)
class(gss.data)
## 4) Display the dimensions of the GSS.sav.
dim(gss.data)
nrow(gss.data)
ncol(gss.data)
## 6) BONUS: figure out how to read the Excel file "gss.xlsx" into R
dat <- import("dataSets/gss.xlsx")
class(dat); dim(dat)
## Exercise 2 solution :prototype:
## ───────────────────
## Use the gss.rds data set
gss <- import("dataSets/gss.rds")
## 1) Create a subset of the data containing only rows where "usecomp" =
## "Yes". How many computer users are there?
gss.usecomp <- subset(gss, usecomp == "Yes")
nrow(gss.usecomp)
## 2) Generate the following variables:
## • "rich" equal to 0 if rincdol is less than 100000, and 1 otherwise
## • "sinc" equal to incomdol - rincdol
gss <- transform(gss,
rich = ifelse(rincdol < 100000, 0, 1),
sinc = incomdol - rincdol)
head(subset(gss, select = c("rincdol", "incomdol", "rich", "sinc")))
## 3) Generate a variable named "dual.earn" equal to 1 if both wkftwife =
## 1 and wkfthusb = 1, and zero otherwise. How many dual earners are
## there?
gss$dual.earn <- ifelse(gss$wkftwife == 1 & gss$wkfthusb == 1, 1, 0)
nrow(subset(gss, dual.earn == 1))
## Exercise 3 solution :prototype:
## ───────────────────
## Using the datGSS data.frame
## 1) Cross-tabulate sex and emailhrs
with(datGSS, table(emailhrs, sex))
## 2) Calculate the mean and standard deviation of incomdol by sex
by(datGSS$incomdol, datGSS$sex, mean)
by(datGSS$incomdol, datGSS$sex, sd)
## 3) Create a scatter plot with educ on the x-axis and incomdol on the
## y-axis
plot(subset(datGSS, select = c("educ", "incomdol")))
## `That first attempt is pretty ugly, let's clean it up.'
plot(log(incomdol) ~ jitter(educ, 8), # formula interface with log an jitter
data = subset(datGSS, # subsetting data as part of the plot call
subset = educ < 97),
cex = .6 # make points smaller
)
## Footnotes
## ─────────
## [1] Note that `subset()' is a convenience function; see `?Extract' for a
## more powerful (and complicated) way to subset data.
|
#' Plot predictions produced with predict_DO
#'
#' Plots modeled values as lines, observed values as points
#'
#' @param DO_preds a data.frame of predictions such as that returned by
#' predict_DO()
#' @param y_var character. Should the plot display predicted & observed values
#' in concentration (conc) or as percent of saturation (pctsat)? The default
#' is to plot both.
#' @param style character indicating which graphics package to use
#' @param y_lim list of named vectors, each of which has length 2 and is numeric
#' and has a name in the possible values of y_var. NA within a vector
#' indicates that the data range should be used. for ggplot2, y_lim is only
#' used to exclude values outside that range and is ignored if the data span a
#' narrower range
#' @examples
#' \dontrun{
#' mm <- metab_night(specs(mm_name('night')), data=data_metab('3', day_start=12, day_end=36))
#' plot_DO_preds(predict_DO(mm))
#' plot_DO_preds(predict_DO(mm), style='dygraphs', y_var='pctsat')
#' }
#' @import dplyr
#' @importFrom unitted v
#' @export
plot_DO_preds <- function(DO_preds, y_var=c('conc','pctsat','ddodt'),
style=c('ggplot2','dygraphs'),
y_lim=list(conc=c(NA,NA), pctsat=c(NA,NA), ddodt=c(NA,NA))) {
style <- match.arg(style)
y_var <- match.arg(y_var, several.ok=TRUE)
params <- list(
xlab='Local time',
ylab='Predictions (lines) and observations (points)',
colors=list(conc=c('#A64B00','#FF7400'), pctsat=c('#007929','#23BC47'), ddodt=c('#05326D','#4282D3'))
)
DO.obs <- DO.mod <- DO.sat <- '.dplyr.var'
DO_preds_conc <- mutate(
DO_preds, as='conc', var='DO (mg/L)', col1=params$colors$conc[1], col2=params$colors$conc[2], lab='DO (mg/L)',
mod=DO.mod,
obs=DO.obs)
DO_preds_pctsat <- mutate(
DO_preds, as='pctsat', var='DO (% sat)', col1=params$colors$pctsat[1], col2=params$colors$pctsat[2], lab='DO (% sat)',
mod=100*DO.mod/DO.sat,
obs=100*DO.obs/DO.sat)
DO_preds_ddodt <-
mutate(
DO_preds[-1,], as='ddodt', var='dDO/dt (mg/L/d)', col1=params$colors$ddodt[1], col2=params$colors$ddodt[2], lab='dDO/dt~(mg~L^-1~d^-1)',
mod = diff(DO_preds$DO.mod)/as.numeric(diff(DO_preds$solar.time), units="days"),
obs = diff(DO_preds$DO.obs)/as.numeric(diff(DO_preds$solar.time), units="days")) %>%
mutate(
mod = ifelse(diff(DO_preds$date)==0, mod, NA),
obs = ifelse(diff(DO_preds$date)==0, obs, NA))
DO_preds_all <- bind_rows(DO_preds_conc, DO_preds_pctsat, DO_preds_ddodt) %>%
mutate(var=ordered(var, c(conc='DO (mg/L)', pctsat='DO (% sat)', ddodt='dDO/dt (mg/L/d)')[y_var]))
plot_out <- switch(
style,
'ggplot2' = {
if(!requireNamespace("ggplot2", quietly=TRUE))
stop("call install.packages('ggplot2') before plotting with style='ggplot2'")
. <- solar.time <- mod <- date <- col1 <- col2 <- obs <- '.ggplot.var'
preds_ggplot <- v(DO_preds_all) %>%
filter(as %in% y_var)
if('conc' %in% names(y_lim)) {
lim <- y_lim[['conc']][1]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'conc' | (mod >= lim & obs >= lim))
lim <- y_lim[['conc']][2]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'conc' | (mod <= lim & obs <= lim))
}
if('pctsat' %in% names(y_lim)) {
lim <- y_lim[['pctsat']][1]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'pctsat' | (mod >= lim & obs >= lim))
lim <- y_lim[['pctsat']][2]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'pctsat' | (mod <= lim & obs <= lim))
}
if('ddodt' %in% names(y_lim)) {
lim <- y_lim[['ddodt']][1]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'ddodt' | (mod >= lim & obs >= lim))
lim <- y_lim[['ddodt']][2]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'ddodt' | (mod <= lim & obs <= lim))
}
g <- ggplot2::ggplot(preds_ggplot, ggplot2::aes(x=solar.time, group=date)) +
ggplot2::geom_point(ggplot2::aes(y=obs, color=col2), alpha=0.6) +
ggplot2::geom_line(ggplot2::aes(y=mod, color=col1), size=0.8) +
ggplot2::scale_color_identity(guide='none') +
ggplot2::theme_bw() +
ggplot2::facet_grid(var ~ ., scales="free_y") +
ggplot2::xlab(params$xlab) + ggplot2::ylab(params$ylab)
suppressWarnings(print(g))
},
'dygraphs' = {
if(!requireNamespace("dygraphs", quietly=TRUE))
stop("call install.packages(dygraphs') before plotting with style='dygraphs'")
if(!requireNamespace("xts", quietly=TRUE))
stop("call install.packages(dygraphs') before plotting with style='dygraphs'")
. <- '.dplyr.var'
preds_xts <- v(DO_preds_all) %>%
filter(as %in% y_var) %>%
arrange(solar.time) %>%
group_by(date) %>%
do(., {
out <- .[c(seq_len(nrow(.)),nrow(.)),]
out[nrow(.)+1,c('mod','obs')] <- NA
out
}) %>%
ungroup()
prep_dygraph <- function(y_var) {
preds_xts %>%
filter(as==y_var) %>%
select(mod,obs,solar.time) %>%
mutate(solar.time=lubridate::force_tz(solar.time, Sys.getenv("TZ"))) %>% # dygraphs makes some funky tz assumptions. this seems to help.
xts::xts(x=select(., -solar.time), order.by=.$solar.time, unique=FALSE, tzone=Sys.getenv("TZ"))
}
if(length(y_var) > 1) warning("can only plot one dygraph y_var at a time for now; plotting y_vars in succession")
sapply(y_var, function(yvar) {
y_var_long <- preds_xts %>% filter(as==yvar) %>% slice(1) %>% .[['var']] %>% as.character()
y_var_col <- params$colors[[yvar]]
dat <- prep_dygraph(yvar)
ymin <- max(c(min(c(dat[,1], dat[,2]), na.rm=TRUE), y_lim[[yvar]][1]), na.rm=TRUE)
ymax <- min(c(max(c(dat[,1], dat[,2]), na.rm=TRUE), y_lim[[yvar]][2]), na.rm=TRUE)
dygraphs::dygraph(dat, xlab=params$xlab, ylab=y_var_long, group='plot_DO_preds') %>%
dygraphs::dySeries('mod', drawPoints = FALSE, label=paste0("Modeled ", y_var_long), color=y_var_col[1]) %>%
dygraphs::dySeries('obs', drawPoints = TRUE, strokeWidth=0, label=paste0("Observed ", y_var_long), color=y_var_col[2]) %>%
dygraphs::dyAxis('y', valueRange=(c(ymin,ymax)+(ymax-ymin)*c(-0.05,0.15))) %>%
dygraphs::dyOptions(colorSaturation=1) %>%
dygraphs::dyLegend(labelsSeparateLines = TRUE, width=300) %>%
dygraphs::dyRangeSelector(height = 20) %>%
print()
})
}
)
invisible(plot_out)
}
|
/R/plot_DO_preds.R
|
permissive
|
Arroita/streamMetabolizer
|
R
| false | false | 6,630 |
r
|
#' Plot predictions produced with predict_DO
#'
#' Plots modeled values as lines, observed values as points
#'
#' @param DO_preds a data.frame of predictions such as that returned by
#' predict_DO()
#' @param y_var character. Should the plot display predicted & observed values
#' in concentration (conc) or as percent of saturation (pctsat)? The default
#' is to plot both.
#' @param style character indicating which graphics package to use
#' @param y_lim list of named vectors, each of which has length 2 and is numeric
#' and has a name in the possible values of y_var. NA within a vector
#' indicates that the data range should be used. for ggplot2, y_lim is only
#' used to exclude values outside that range and is ignored if the data span a
#' narrower range
#' @examples
#' \dontrun{
#' mm <- metab_night(specs(mm_name('night')), data=data_metab('3', day_start=12, day_end=36))
#' plot_DO_preds(predict_DO(mm))
#' plot_DO_preds(predict_DO(mm), style='dygraphs', y_var='pctsat')
#' }
#' @import dplyr
#' @importFrom unitted v
#' @export
plot_DO_preds <- function(DO_preds, y_var=c('conc','pctsat','ddodt'),
style=c('ggplot2','dygraphs'),
y_lim=list(conc=c(NA,NA), pctsat=c(NA,NA), ddodt=c(NA,NA))) {
style <- match.arg(style)
y_var <- match.arg(y_var, several.ok=TRUE)
params <- list(
xlab='Local time',
ylab='Predictions (lines) and observations (points)',
colors=list(conc=c('#A64B00','#FF7400'), pctsat=c('#007929','#23BC47'), ddodt=c('#05326D','#4282D3'))
)
DO.obs <- DO.mod <- DO.sat <- '.dplyr.var'
DO_preds_conc <- mutate(
DO_preds, as='conc', var='DO (mg/L)', col1=params$colors$conc[1], col2=params$colors$conc[2], lab='DO (mg/L)',
mod=DO.mod,
obs=DO.obs)
DO_preds_pctsat <- mutate(
DO_preds, as='pctsat', var='DO (% sat)', col1=params$colors$pctsat[1], col2=params$colors$pctsat[2], lab='DO (% sat)',
mod=100*DO.mod/DO.sat,
obs=100*DO.obs/DO.sat)
DO_preds_ddodt <-
mutate(
DO_preds[-1,], as='ddodt', var='dDO/dt (mg/L/d)', col1=params$colors$ddodt[1], col2=params$colors$ddodt[2], lab='dDO/dt~(mg~L^-1~d^-1)',
mod = diff(DO_preds$DO.mod)/as.numeric(diff(DO_preds$solar.time), units="days"),
obs = diff(DO_preds$DO.obs)/as.numeric(diff(DO_preds$solar.time), units="days")) %>%
mutate(
mod = ifelse(diff(DO_preds$date)==0, mod, NA),
obs = ifelse(diff(DO_preds$date)==0, obs, NA))
DO_preds_all <- bind_rows(DO_preds_conc, DO_preds_pctsat, DO_preds_ddodt) %>%
mutate(var=ordered(var, c(conc='DO (mg/L)', pctsat='DO (% sat)', ddodt='dDO/dt (mg/L/d)')[y_var]))
plot_out <- switch(
style,
'ggplot2' = {
if(!requireNamespace("ggplot2", quietly=TRUE))
stop("call install.packages('ggplot2') before plotting with style='ggplot2'")
. <- solar.time <- mod <- date <- col1 <- col2 <- obs <- '.ggplot.var'
preds_ggplot <- v(DO_preds_all) %>%
filter(as %in% y_var)
if('conc' %in% names(y_lim)) {
lim <- y_lim[['conc']][1]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'conc' | (mod >= lim & obs >= lim))
lim <- y_lim[['conc']][2]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'conc' | (mod <= lim & obs <= lim))
}
if('pctsat' %in% names(y_lim)) {
lim <- y_lim[['pctsat']][1]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'pctsat' | (mod >= lim & obs >= lim))
lim <- y_lim[['pctsat']][2]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'pctsat' | (mod <= lim & obs <= lim))
}
if('ddodt' %in% names(y_lim)) {
lim <- y_lim[['ddodt']][1]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'ddodt' | (mod >= lim & obs >= lim))
lim <- y_lim[['ddodt']][2]; if(!is.na(lim)) preds_ggplot <- filter(preds_ggplot, as != 'ddodt' | (mod <= lim & obs <= lim))
}
g <- ggplot2::ggplot(preds_ggplot, ggplot2::aes(x=solar.time, group=date)) +
ggplot2::geom_point(ggplot2::aes(y=obs, color=col2), alpha=0.6) +
ggplot2::geom_line(ggplot2::aes(y=mod, color=col1), size=0.8) +
ggplot2::scale_color_identity(guide='none') +
ggplot2::theme_bw() +
ggplot2::facet_grid(var ~ ., scales="free_y") +
ggplot2::xlab(params$xlab) + ggplot2::ylab(params$ylab)
suppressWarnings(print(g))
},
'dygraphs' = {
if(!requireNamespace("dygraphs", quietly=TRUE))
stop("call install.packages(dygraphs') before plotting with style='dygraphs'")
if(!requireNamespace("xts", quietly=TRUE))
stop("call install.packages(dygraphs') before plotting with style='dygraphs'")
. <- '.dplyr.var'
preds_xts <- v(DO_preds_all) %>%
filter(as %in% y_var) %>%
arrange(solar.time) %>%
group_by(date) %>%
do(., {
out <- .[c(seq_len(nrow(.)),nrow(.)),]
out[nrow(.)+1,c('mod','obs')] <- NA
out
}) %>%
ungroup()
prep_dygraph <- function(y_var) {
preds_xts %>%
filter(as==y_var) %>%
select(mod,obs,solar.time) %>%
mutate(solar.time=lubridate::force_tz(solar.time, Sys.getenv("TZ"))) %>% # dygraphs makes some funky tz assumptions. this seems to help.
xts::xts(x=select(., -solar.time), order.by=.$solar.time, unique=FALSE, tzone=Sys.getenv("TZ"))
}
if(length(y_var) > 1) warning("can only plot one dygraph y_var at a time for now; plotting y_vars in succession")
sapply(y_var, function(yvar) {
y_var_long <- preds_xts %>% filter(as==yvar) %>% slice(1) %>% .[['var']] %>% as.character()
y_var_col <- params$colors[[yvar]]
dat <- prep_dygraph(yvar)
ymin <- max(c(min(c(dat[,1], dat[,2]), na.rm=TRUE), y_lim[[yvar]][1]), na.rm=TRUE)
ymax <- min(c(max(c(dat[,1], dat[,2]), na.rm=TRUE), y_lim[[yvar]][2]), na.rm=TRUE)
dygraphs::dygraph(dat, xlab=params$xlab, ylab=y_var_long, group='plot_DO_preds') %>%
dygraphs::dySeries('mod', drawPoints = FALSE, label=paste0("Modeled ", y_var_long), color=y_var_col[1]) %>%
dygraphs::dySeries('obs', drawPoints = TRUE, strokeWidth=0, label=paste0("Observed ", y_var_long), color=y_var_col[2]) %>%
dygraphs::dyAxis('y', valueRange=(c(ymin,ymax)+(ymax-ymin)*c(-0.05,0.15))) %>%
dygraphs::dyOptions(colorSaturation=1) %>%
dygraphs::dyLegend(labelsSeparateLines = TRUE, width=300) %>%
dygraphs::dyRangeSelector(height = 20) %>%
print()
})
}
)
invisible(plot_out)
}
|
testlist <- list(A = structure(c(2.32784507357645e-308, 9.53818252170362e+295, 4.0343042887248e-305, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L)), B = structure(0, .Dim = c(1L, 1L)))
result <- do.call(multivariance:::match_rows,testlist)
str(result)
|
/multivariance/inst/testfiles/match_rows/AFL_match_rows/match_rows_valgrind_files/1613107581-test.R
|
no_license
|
akhikolla/updatedatatype-list3
|
R
| false | false | 343 |
r
|
testlist <- list(A = structure(c(2.32784507357645e-308, 9.53818252170362e+295, 4.0343042887248e-305, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 7L)), B = structure(0, .Dim = c(1L, 1L)))
result <- do.call(multivariance:::match_rows,testlist)
str(result)
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/Policy.R
\name{Policy.rate.limit}
\alias{Policy.rate.limit}
\title{Create a Policy.rate.limit object enforcing the namesake access policy}
\usage{
Policy.rate.limit(rate.limit, last.access = NULL)
}
\arguments{
\item{rate.limit}{The rate limit, in accesses per second.}
\item{last.access}{The date and time of the last access. This should always be left at default}
}
\value{
The newly minted Policy.rate.limit object
}
\description{
A rate limit policy prescribes a minimum interval between accesses to a resource
}
\details{
This is used to provide the \code{.policy} argument to \code{\link{make.web.call}}.
}
|
/man/Policy.rate.limit.Rd
|
no_license
|
wulixin/webapi
|
R
| false | false | 701 |
rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/Policy.R
\name{Policy.rate.limit}
\alias{Policy.rate.limit}
\title{Create a Policy.rate.limit object enforcing the namesake access policy}
\usage{
Policy.rate.limit(rate.limit, last.access = NULL)
}
\arguments{
\item{rate.limit}{The rate limit, in accesses per second.}
\item{last.access}{The date and time of the last access. This should always be left at default}
}
\value{
The newly minted Policy.rate.limit object
}
\description{
A rate limit policy prescribes a minimum interval between accesses to a resource
}
\details{
This is used to provide the \code{.policy} argument to \code{\link{make.web.call}}.
}
|
drives <- read.csv("~/2005-2013 Drives.csv")
drives$End.Reason <- as.factor(drives$End.Reason)
# end.reason <- drives$End.Reason
# dummies <- model.matrix(~drives$End.Reason)
# drives <- cbind(drives, dummies)
# drives$End.Reason <- end.reason
drives$Points <- ifelse(drives$End.Reason == "TOUCHDOWN", 7,
ifelse(drives$End.Reason == "FIELD GOAL", 3,
ifelse(drives$End.Reason == "SAFETY", -2, 0)))
drives$Start.Spot <- as.factor(drives$Start.Spot)
expected <- aggregate(drives$Points, by = list(drives$Start.Spot), mean)
expected$Group.1 <- (100 - as.numeric(expected$Group.1))
drives$Starting.Pos.To.EZ <- (100 - as.numeric(drives$Start.Spot))
colnames(expected) <- c("Starting.Pos.To.EZ", "Expected.Points")
drives <- merge(drives, expected, by="Starting.Pos.To.EZ")
l <- lm(Points ~ as.numeric(Starting.Pos.To.EZ), drives)
summary(l)
plot(expected, type = "c", xlab = "Yards to End Zone", ylab = "Expected Points")
lines(expected)
abline(l)
write.csv(drives, file = "~/Drives with Expected Points.csv", row.names = FALSE)
|
/Expected Points.R
|
no_license
|
jmar257/cfb-analytics
|
R
| false | false | 1,092 |
r
|
drives <- read.csv("~/2005-2013 Drives.csv")
drives$End.Reason <- as.factor(drives$End.Reason)
# end.reason <- drives$End.Reason
# dummies <- model.matrix(~drives$End.Reason)
# drives <- cbind(drives, dummies)
# drives$End.Reason <- end.reason
drives$Points <- ifelse(drives$End.Reason == "TOUCHDOWN", 7,
ifelse(drives$End.Reason == "FIELD GOAL", 3,
ifelse(drives$End.Reason == "SAFETY", -2, 0)))
drives$Start.Spot <- as.factor(drives$Start.Spot)
expected <- aggregate(drives$Points, by = list(drives$Start.Spot), mean)
expected$Group.1 <- (100 - as.numeric(expected$Group.1))
drives$Starting.Pos.To.EZ <- (100 - as.numeric(drives$Start.Spot))
colnames(expected) <- c("Starting.Pos.To.EZ", "Expected.Points")
drives <- merge(drives, expected, by="Starting.Pos.To.EZ")
l <- lm(Points ~ as.numeric(Starting.Pos.To.EZ), drives)
summary(l)
plot(expected, type = "c", xlab = "Yards to End Zone", ylab = "Expected Points")
lines(expected)
abline(l)
write.csv(drives, file = "~/Drives with Expected Points.csv", row.names = FALSE)
|
####################################################################################################
# Load libs and data
####################################################################################################
load.libraries(c('stringr','truncnorm','reshape2','gdata','mvtnorm','gtools','yaml','GGally','stringr'))
installXLSXsupport()
#scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/base/')
scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/gas-experiment/')
base.scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/base/')
plot.dir.base <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/plots/')
#scens <- c('fuel-gasoline-price')
#scens <- c('fuel-canola-price','fuel-elec-price','fuel-h2-price','fuel-sorghum-price','fuel-sugarcane-price')
#scens <- c('discount-rate')
#scens <- pp('distrib-',c('h2','bev','phev','flex','ethanol'))
#scens <- pp('vehicle-',c('h2','bev','phev','flex'))
#scens <- c('bev-penetration')
scens <- c('blend-wall')
#scens <- c('base','fuel-gasoline-price','fuel-canola-price','fuel-elec-price','fuel-h2-price','fuel-sorghum-price','fuel-sugarcane-price','discount-rate',pp('distrib-',c('h2','bev','phev','flex','ethanol')),pp('vehicle-',c('h2','bev','phev','flex')),'bev-penetration','blend-wall')
#scens <- c('base')
####################################################################################################
# Configurations
####################################################################################################
make.plots <- F
# tool for pulling economic params
get.param <- function(param.name){
inputs[['EconomicAssumptions']][Name==param.name,list(Value)]$Value
}
load.inputs <- function(sheet){
inputs[[sheet]] <<- data.table(read.xls(input.file,sheet,stringsAsFactors=F,skip=1))
}
sheets <- c("MarketStructure","AltFuelPenetrationLimits","FuelTimeSeries","FuelRegionalMarkup","DistributionCosts","VehicleCosts","CarbonIntensity","EconomicAssumptions","CPI","VehicleLifetimeAndVMT")
# my fav color scheme
my.colors <- c(blue='#377eb8',green='#227222',orange='#C66200',purple='#470467',red='#B30C0C',yellow='#C6A600',light.green='#C0E0C0',magenta='#D0339D',dark.blue='#23128F',brown='#542D06',grey='#8A8A8A',light.yellow='#FFE664',light.purple='#9C50C0',light.orange='#FFB164')
alt.colors <- c(BEV='blue',PHEV='dark.blue',H2='red',
CanolaBiodiesel='light.green',SoyBiodiesel='green',SoyRenewableDiesel='grey',TallowRenewableDiesel='brown',UCOBiodiesel='light.purple',
SugarcaneEthanol='yellow',CornEthanolDryMill='grey',FlexCornEthanolDryMill='magenta',FlexSorghumEthanol='light.orange',FlexSugarcaneEthanol='light.yellow',SorghumEthanol='orange')
alt.colors <- data.frame(AltKey=names(alt.colors),color=alt.colors,color.hex=my.colors[alt.colors])
alt.type.colors <- c(PEV='blue',H2='red',Biodiesel='green',Ethanol='yellow',Flex='light.yellow')
alt.type.colors <- data.frame(AltKey=names(alt.type.colors),color=alt.type.colors,color.hex=my.colors[alt.type.colors])
amort.veh.cost <- function(veh.cost,tot.vmt,seg.vmt,mj.per.mile){
lifetime.in.segment <- tot.vmt / seg.vmt
overnight.cap <- (1-get.param('FractionFinancedVeh')) * veh.cost
loan.principal <- get.param('FractionFinancedVeh') * veh.cost
amort.npv <- apply(cbind(loan.principal,overnight.cap,lifetime.in.segment),1,amort.the.loan)
amort.npv.per.MJ <- amort.npv / seg.vmt / mj.per.mile
amort.npv.per.MJ
}
amort.the.loan <- function(x){
loan.principal <- x[1]
overnight.cap <- x[2]
lifetime.in.segment <- x[3]
loan.payments <- rep(loan.principal * get.param('FinanceRateVeh') / (1 - (1+get.param('FinanceRateVeh'))^-get.param('FinanceTermVeh')),get.param('FinanceTermVeh'))
loan.payments.disc <- loan.payments / (1 + get.param('DiscountRate'))^(1:(get.param('FinanceTermVeh')))
amort.npv <- (overnight.cap + sum(loan.payments.disc))*(get.param('DiscountRate')*(1+get.param('DiscountRate'))^lifetime.in.segment)/((1+get.param('DiscountRate'))^lifetime.in.segment - 1)
amort.npv
}
setup.pricing <- function(){
station.cost <<- 1
overnight.cap <<- (1-get.param('FractionFinancedDist')) * station.cost
loan.principal <<- get.param('FractionFinancedDist') * station.cost
loan.payments <<- rep(loan.principal * get.param('FinanceRateDist') / (1 - (1+get.param('FinanceRateDist'))^-get.param('FinanceTermDist')),get.param('FinanceTermDist'))
loan.payments.disc <<- loan.payments / (1 + get.param('DiscountRate'))^(0:(get.param('FinanceTermDist')-1))
amort.dist.ratio <<- (overnight.cap + sum(loan.payments.disc))*(get.param('DiscountRate')*(1+get.param('DiscountRate'))^get.param('DistributionLifetime'))/((1+get.param('DiscountRate'))^get.param('DistributionLifetime') - 1) / 1e3 # 1e3 converts from GJ to MJ
pens <<- inputs[['AltFuelPenetrationLimits']]
fuel.markup <<- inputs[['FuelRegionalMarkup']]
setkey(fuel.markup,Replaces)
carb <<- copy(inputs[['CarbonIntensity']])
gas.carb <<- carb[AltFuel=='Gas']$Intensity
gas.mj.per.gal <<- carb[AltFuel=='Gas']$ConversionFactor
diesel.carb <<- carb[AltFuel=='Diesel']$Intensity
flex.carb <<- carb[AltFuelType=='Ethanol']
flex.blend.by.energy <<- cbind(flex.carb$ConversionFactor * get.param('FlexBlend'),(1-get.param('FlexBlend'))* gas.mj.per.gal)
flex.blend.by.energy <<- as.data.frame(t(apply(flex.blend.by.energy,1,function(x){ x/sum(x) })))
names(flex.blend.by.energy) <<- c('flex','gas')
flex.carb[,':='(AltFuelType='Flex',Intensity=Intensity*flex.blend.by.energy$flex + gas.carb*flex.blend.by.energy$gas)]
eth.blend.by.energy <<- cbind(carb[AltFuelType=='Ethanol']$ConversionFactor * get.param('EthanolBlend'),(1-get.param('EthanolBlend'))* gas.mj.per.gal)
eth.blend.by.energy <<- as.data.frame(t(apply(eth.blend.by.energy,1,function(x){ x/sum(x) })))
names(eth.blend.by.energy) <<- c('eth','gas')
carb[AltFuelType=='Ethanol',':='(Intensity=Intensity*eth.blend.by.energy$eth + gas.carb*eth.blend.by.energy$gas)]
phev.carb<<- carb[AltFuelType=='Electricity']
phev.carb[,':='(AltFuelType='PHEV',AltFuel='PHEV',Intensity=Intensity*get.param('PHEVBlend')+gas.carb*(1-get.param('PHEVBlend')),EER=1/((1/EER)*get.param('PHEVBlend')+(1-get.param('PHEVBlend'))))]
carb[AltFuelType=='Biodiesel',':='(Intensity=Intensity*get.param('BiodieselBlend')+diesel.carb*(1-get.param('BiodieselBlend')))]
carb <<- rbindlist(list(carb,flex.carb,phev.carb),use.names=T,fill=T)
carb[AltFuelType=='Electricity',':='(AltFuelType='BEV',AltFuel='BEV')]
mark <<- inputs[['MarketStructure']]
ghg.goal <<- sum(mark$GHG) - (sum(mark[FuelType=='Gas']$EnergyDemand*1e3)*get.param('TargetGasolineIntensity') + sum(mark[FuelType=='Diesel']$EnergyDemand*1e3)*get.param('TargetDieselIntensity'))/1e6
fuel.price.m <<- melt(inputs[['FuelTimeSeries']],id.vars=c('Year','Quarter'))
setkey(fuel.price.m,variable)
fuel.price <<- fuel.price.m[Year>=2010,list(PriceAvg=mean(value,na.rm=T)),by='variable']
fuel.price[,FuelType:=carb$AltFuelType[match(variable,carb$AltFuel)]]
fuel.price[,':='(AltFuel=variable,variable=NULL)]
fuel.price[,Replaces:='None']
fuel.price[FuelType=='Gas' | FuelType=='Ethanol',Replaces:='Gas']
fuel.price[FuelType=='Diesel' | FuelType=='Biodiesel',Replaces:='Diesel']
fuel.price[FuelType=='H2',Replaces:='H2']
setkey(fuel.price,Replaces)
fuel.price[,PriceRV:=PriceAvg]
elec.price <<- fuel.price[AltFuel=='Electricity']$PriceRV
gas.price <<- fuel.price[AltFuel=='Gas']$PriceRV
diesel.price <<- fuel.price[AltFuel=='Diesel']$PriceRV
# Blend Flex and Ethanol
setkey(fuel.price,FuelType,AltFuel)
flex.prices <<- copy(fuel.price[FuelType=='Ethanol'])
flex.prices[,':='(FuelType='Flex',PriceRV=PriceRV*flex.blend.by.energy$flex+gas.price*flex.blend.by.energy$gas)]
fuel.price[FuelType=='Ethanol',':='(PriceRV=PriceRV*eth.blend.by.energy$eth+gas.price*eth.blend.by.energy$gas)]
# Blend PHEV
phev.price <<- data.table(AltFuel='PHEV',FuelType='PHEV',Replaces='None',PriceRV=elec.price * get.param('PHEVBlend') + gas.price * (1 - get.param('PHEVBlend')))
# Blend Biodiesel
fuel.price[FuelType=='Biodiesel',':='(PriceRV=PriceRV*get.param('BiodieselBlend')+diesel.price*(1-get.param('BiodieselBlend')))]
# Rename Elec to BEV
fuel.price[AltFuel=='Electricity',':='(FuelType='BEV',AltFuel='BEV')]
fuel.price <<- rbindlist(list(fuel.price,flex.prices,phev.price),use.names=T,fill=T)
setkey(fuel.price,Replaces)
fuel.price.by.county <<- fuel.markup[fuel.price,allow.cart=T]
fuel.price.by.county[is.na(Markup),Markup:=0]
fuel.price.by.county[,FuelCost:=PriceRV+Markup]
# Now EER weight the cost using the LDV value for H2
setkey(carb,AltFuel,IntensityEER) # need this to get H2 in correct order
setkey(carb,AltFuel)
setkey(fuel.price.by.county,AltFuel)
fuel.price.by.county <<- unique(carb)[,list(AltFuel,EER)][fuel.price.by.county]
fuel.price.by.county[,FuelCost:=FuelCost/EER]
# Join the conventional prices to market segments for later use in making the fuel cost incremental
mark <<- copy(mark)
setkey(mark,County,FuelType)
setkey(fuel.price.by.county,County,FuelType)
mark <<- fuel.price.by.county[mark,list(County,FuelType,VehicleType,VehicleStatus,NumVehicles,SegmentVMT,EnergyDemand,GHG,travel.demand,FuelCost)]
mark[,':='(ConventionalFuelCost=FuelCost,FuelCost=NULL)]
# Now drop the conventionals
fuel.price.by.county <<- fuel.price.by.county[FuelType!="Gas" & FuelType!="Diesel"]
fuel.price.by.county[,':='(AltFuelType=FuelType,FuelType=NULL)]
###
# Sample and amortized the station cost into 2014$ / MJ
###
station.costs <<- inputs[['DistributionCosts']]
station.costs[is.na(DistCostSD),DistCostSD:=0.25*DistCostAvg]
station.costs[,DistCostRV:=DistCostAvg]
station.costs[,StationCost:=DistCostRV * amort.dist.ratio]
setkey(carb,AltFuelType,IntensityEER) # need this to get H2 in correct order
setkey(carb,AltFuelType)
setkey(station.costs,AltFuelType)
station.costs <<- unique(carb)[,list(AltFuelType,EER)][station.costs]
station.costs[,StationCost:=StationCost/EER]
###
# Sample and amortize the vehicle costs into 2014$ / MJ
###
veh.costs <<- inputs[['VehicleCosts']]
setkey(veh.costs,VehicleType)
setkey(mark,VehicleType)
veh.costs <<- mark[VehicleStatus=='New'][veh.costs, allow.cartesian=T]
veh.costs[,SegmentVMT.per.veh.per.yr:=SegmentVMT/NumVehicles]
tot.vmt <<- inputs[['VehicleLifetimeAndVMT']]
# we need to base lifetime vmt off of the appropriate fuel type
veh.costs[,FuelTypeForLifetime:=FuelType]
veh.costs[AltFuelType%in%c('BEV','PHEV','Flex'),FuelTypeForLifetime:='Gas']
tot.vmt[,FuelTypeForLifetime:=FuelType]
setkey(tot.vmt,FuelTypeForLifetime,VehicleType)
setkey(veh.costs,FuelTypeForLifetime,VehicleType)
veh.costs <<- tot.vmt[veh.costs]
veh.costs[,':='(FuelType=i.FuelType,i.FuelType=NULL)]
# we need to get the segment vmt aggregated across vehicle status
setkey(mark,County,FuelType,VehicleType)
agg.seg.vmt <<- mark[,list(AggSegmentVMTPerVeh=sum(SegmentVMT)/sum(NumVehicles)),by=c('County','FuelType','VehicleType')]
setkey(veh.costs,County,FuelType,VehicleType)
veh.costs <<- agg.seg.vmt[veh.costs,allow.cartesian=T]
setkey(veh.costs,AltFuelType,VehicleType)
setkey(carb,AltFuelType,VehicleType)
veh.costs <<- unique(carb)[,list(AltFuelType,VehicleType,EER)][veh.costs]
veh.costs[is.na(EER),EER:=1]
veh.costs[,MJ.EER.per.mile:=EnergyDemand / SegmentVMT * 1000]
veh.costs[,cost.per.MJ.EER := amort.veh.cost(VehicleCostAvg,VMTPerLifetime,AggSegmentVMTPerVeh,MJ.EER.per.mile)]
veh.costs[,cost.per.MJ.EER.ratio := cost.per.MJ.EER / VehicleCostAvg]
veh.costs[,':='(VehicleCost=VehicleCostAvg * cost.per.MJ.EER.ratio)]
return(NULL)
}
##########################
# Plot Functions
##########################
plot.mac <- function(the.macc,col.to.plot='MAC',errorbars=F,the.title='',y.lim=500){
to.use <- streval(pp('the.macc[!is.nan(',col.to.plot,') & !',col.to.plot,'==Inf]'))
to.use[,AbatementPotential:=AbatementPotential/1e3]
streval(pp('setkey(to.use,',col.to.plot,')'))
to.use[,key:=factor(pp(ifelse(AltFuelType=='Flex','Flex',''),AltFuel,' - ',County,' - ',VehicleStatus,FuelType,VehicleType))]
to.use[,key:=factor(to.use$key, to.use$key)] # reorders the levels to match their rank
to.use[,x.pos:=0.5*(cumsum(AbatementPotential)+cumsum(c(0, head(AbatementPotential,-1))))]
to.use <- streval(pp('to.use[',col.to.plot,'<',y.lim,']'))
p <- streval(pp('ggplot(to.use,aes(x=x.pos,label=key,width=AbatementPotential,y=',col.to.plot,',fill=AltFuel))'))
p <- p + geom_bar(stat='identity',position='identity',colour='black',linetype='blank')+
theme_bw()+
geom_vline(xintercept=ghg.goal/1e3,color=my.colors['red'],linetype='longdash')+
scale_fill_manual(values=as.character(alt.colors$color.hex[match(sort(u(to.use$AltFuel)),alt.colors$AltKey)]))
if(errorbars & pp(col.to.plot,'.sd') %in% names(to.use)){
max.y <- streval(pp('max(to.use$',col.to.plot,' + to.use$',col.to.plot,'.sd)'))
p <- p + geom_point()+
geom_errorbar(aes(ymin=MAC-MAC.sd,ymax=MAC+MAC.sd,width=0))+
scale_y_continuous(limit=c(-750,max.y))
}
if(col.to.plot == 'MAC'){
p <- p + labs(x='GHG Abatement (1000 tons CO2eq)',y='Marginal Abatement Cost ($/ton CO2eq)',fill='County',title=the.title)
}else{
p <- p + labs(x='GHG Abatement (1000 tons CO2eq)',y='Marginal Intensity Abatement Cost ($1000/(g/MJ))',fill='County',title=the.title)
}
print(p)
p
}
all.stats <- data.table()
scen <- scens[1]
for(scen in scens){
scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/',scen,'/')
exper <- list(Factors=list(list(Name="Base",Levels=c('Base'))))
if(file.exists(pp(scenario.dir,'exper.yaml'))){
exper <- yaml.load(readChar(pp(scenario.dir,'exper.yaml'),file.info(pp(scenario.dir,'exper.yaml'))$size))
}
if("InputFile" %in% names(exper)){
input.file <- pp(scenario.dir,exper$InputFile)
}else{
input.file <- pp(scenario.dir,'AFCI_Portfolio_Inputs.xlsx')
}
plot.dir <- pp(plot.dir.base,scen,'/')
make.dir(plot.dir)
load(file=pp(scenario.dir,'results.Rdata'))
level.combs <- results$level.combs
names(level.combs) <- str_replace_all(names(level.combs)," ","_")
num.factors <- ncol(level.combs)
all.avg.maccs <- data.table()
level.i <- 1
####################################################################################################
# Factorial loop
####################################################################################################
for(level.i in 1:nrow(level.combs)){
my.cat(pp(pp(names(level.combs),":",level.combs[level.i,]),collapse=' X '))
inputs<-list()
for(sheet in sheets){
load.inputs(sheet)
}
for(fac.i in 1:num.factors){
if('Scale' %in% names(exper$Factors[[fac.i]])){
sheet <- names(exper$Factors[[fac.i]]$Scale)
lev.1d.i <- which(exper$Factors[[fac.i]]$Levels == level.combs[level.i,fac.i])
if('Row' %in% names(exper$Factors[[fac.i]]$Scale[[sheet]])){
column <- names(exper$Factors[[fac.i]]$Scale[[sheet]])[!names(exper$Factors[[fac.i]]$Scale[[sheet]])=='Row']
col.names <- names(exper$Factors[[fac.i]]$Scale[[sheet]]$Row)
row.keys <- sapply(exper$Factors[[fac.i]]$Scale[[sheet]]$Row,function(x){ x })
streval(pp('inputs[["',sheet,'"]][',pp(col.names,'=="',row.keys,'"',collapse="&"),',',column,':=',column,'*',exper$Factors[[fac.i]]$Scale[[sheet]][[column]][[lev.1d.i]],']'))
}else{
column <- names(exper$Factors[[fac.i]]$Scale[[sheet]])
streval(pp('inputs[["',sheet,'"]][,',column,':=',column,'*',exper$Factors[[fac.i]]$Scale[[sheet]][[column]][[lev.1d.i]],']'))
}
}
}
setup.pricing()
the.macc <- results$the.macc[[level.i]]
mac.results <- results$mac.results[[level.i]]
####################################################
# Summarize and store the avg MACC and key stats
####################################################
# for incomplete results, constrain the inds
inds <- which(!is.na(mac.results[1,,2]))
# Find average cost/rank
setkey(the.macc,VehicleStatus,VehicleType,FuelType,County,AltFuelType,AltFuel)
avg.results <- the.macc[,list(VehicleStatus,VehicleType,FuelType,County,AltFuelType,AltFuel,EnergyDemand,GHG)]
avg.results[,':='(MAC=apply(mac.results[,inds,2],1,mean,na.rm=T),MAC.sd=apply(mac.results[,inds,2],1,sd),MIAC=apply(mac.results[,inds,4],1,mean,na.rm=T),MIAC.sd=apply(mac.results[,inds,4],1,sd),AbatementPotential=apply(mac.results[,inds,3],1,mean))]
avg.results <- avg.results[!is.nan(MAC) & !MAC==Inf]
avg.results[,AbatementPotential:=AbatementPotential/1e3]
avg.results[,rank:=rank(MAC,ties.method='random')]
n.trials <- dim(mac.results)[2]
# Report the total cost of the solution and the conventional cost by comparison
setkey(avg.results,MAC)
avg.results[,CumulativeAbatement:=cumsum(AbatementPotential)]
avg.results[,TotalCost:=MAC * AbatementPotential / 1e3] # AbatementPotential is in K-tons, so this puts cost into $M
mark[,TotalCost:=EnergyDemand*ConventionalFuelCost * 1e3 / 1e6] # puts cost into $M
avg.results[,Penetration:=AbatementPotential*1e3/GHG]
avg.results[,EnergyPenetrated:=EnergyDemand*Penetration]
avg.results[,MJToGalFactor:=c('Gas'=115.63,'Diesel'=134)[FuelType]]
avg.results[,GalPenetrated:=EnergyPenetrated*1e3/MJToGalFactor]
stats <- data.table(WtAvgMAC=avg.results[CumulativeAbatement<ghg.goal/1e3,list(WtAvg=weighted.mean(MAC,AbatementPotential))]$WtAvg,NetCost=sum(avg.results[CumulativeAbatement <= ghg.goal/1e3]$TotalCost),BAUCost=sum(mark$TotalCost))
setkey(avg.results,MAC)
avg.results[,x.pos:=0.5*(cumsum(AbatementPotential)+cumsum(c(0, head(AbatementPotential,-1))))]
avg.results[,WtAvgMAC:=stats$WtAvgMAC]
for(fac.i in 1:num.factors){
fac.name <- names(level.combs)[fac.i]
streval(pp('avg.results[,',fac.name,':="',level.combs[level.i,fac.i],'"]'))
streval(pp('stats[,":="(Factor="',fac.name,'",Level="',level.combs[level.i,fac.i],'")]'))
}
all.avg.maccs <- rbindlist(list(all.avg.maccs,avg.results),use.names=T,fill=T)
all.stats <- rbindlist(list(all.stats,stats),use.names=T,fill=T)
}
all.avg.maccs[,key:=factor(pp(ifelse(AltFuelType=='Flex','Flex',''),AltFuel))]
for(fac.i in 1:num.factors){
fac.name <- names(level.combs)[fac.i]
streval(pp('all.avg.maccs[,',fac.name,':=factor(',fac.name,',level.combs[,',fac.i,'])]'))
}
if(make.plots){
to.use <- all.avg.maccs[AbatementPotential>0]
factor.name <- names(level.combs)[1]
streval(pp('setkey(to.use,',factor.name,',MAC)'))
to.use[,first.over.target:=CumulativeAbatement >= ghg.goal/1e3]
streval(pp('to.use[,first.over.target:=(first.over.target==T & c(F,head(first.over.target,-1))==F),by="',factor.name,'"]'))
to.use <- to.use[CumulativeAbatement <= ghg.goal/1e3 | first.over.target==T]
setkey(to.use,MAC)
alt.order <- to.use[,list(key=key[1]),by='key']
to.use[,key:=factor(key,alt.order$key)]
#to.use[abs(MAC)>1000,MAC:=1000*sign(MAC)]
p <- ggplot(to.use,aes(x=x.pos,label=key,width=AbatementPotential,y=MAC,fill=key))+
geom_bar(stat='identity',position='identity',colour='black',linetype='blank')+
theme_bw()+
geom_hline(aes(yintercept=WtAvgMAC),colour=my.colors['grey'],linetype='longdash')+
geom_vline(xintercept=ghg.goal/1e3,color=my.colors['red'],linetype='longdash')+
coord_cartesian(xlim = c(-10,ghg.goal/1e3+10),ylim=c(max(-1000,min(to.use$MAC))-20,min(1000,max(to.use$MAC))+20))+
scale_fill_manual(values=as.character(alt.colors$color.hex[match(sort(u(to.use$key)),alt.colors$AltKey)]))+
labs(x='GHG Abatement (kt CO2eq)',y='Marginal Abatement Cost ($/t CO2eq)',fill='Alternative',title=pp(exper$Name,': Average MACCs (',n.trials,' Trials)'))
p <- p + streval(pp('facet_wrap(~',factor.name,')'))
if(nrow(level.combs)==3){
ggsave(file=pp(plot.dir,'macc-avg.pdf'),plot=p,width=12,height=4)
}else if(nrow(level.combs)==4 | nrow(level.combs)==1){
ggsave(file=pp(plot.dir,'macc-avg.pdf'),plot=p,width=12,height=8)
}
}
}
# stats in slightly more useable form for comparing
#cast(melt(all.stats,measure.vars=c('WtAvgMAC','NetCost')),Factor + variable ~ Level)
#cast(melt(all.stats,measure.vars=c('WtAvgMAC','NetCost')),Factor ~ variable + Level)
|
/sensitivity.R
|
no_license
|
colinsheppard/smacc
|
R
| false | false | 20,520 |
r
|
####################################################################################################
# Load libs and data
####################################################################################################
load.libraries(c('stringr','truncnorm','reshape2','gdata','mvtnorm','gtools','yaml','GGally','stringr'))
installXLSXsupport()
#scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/base/')
scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/gas-experiment/')
base.scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/base/')
plot.dir.base <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/plots/')
#scens <- c('fuel-gasoline-price')
#scens <- c('fuel-canola-price','fuel-elec-price','fuel-h2-price','fuel-sorghum-price','fuel-sugarcane-price')
#scens <- c('discount-rate')
#scens <- pp('distrib-',c('h2','bev','phev','flex','ethanol'))
#scens <- pp('vehicle-',c('h2','bev','phev','flex'))
#scens <- c('bev-penetration')
scens <- c('blend-wall')
#scens <- c('base','fuel-gasoline-price','fuel-canola-price','fuel-elec-price','fuel-h2-price','fuel-sorghum-price','fuel-sugarcane-price','discount-rate',pp('distrib-',c('h2','bev','phev','flex','ethanol')),pp('vehicle-',c('h2','bev','phev','flex')),'bev-penetration','blend-wall')
#scens <- c('base')
####################################################################################################
# Configurations
####################################################################################################
make.plots <- F
# tool for pulling economic params
get.param <- function(param.name){
inputs[['EconomicAssumptions']][Name==param.name,list(Value)]$Value
}
load.inputs <- function(sheet){
inputs[[sheet]] <<- data.table(read.xls(input.file,sheet,stringsAsFactors=F,skip=1))
}
sheets <- c("MarketStructure","AltFuelPenetrationLimits","FuelTimeSeries","FuelRegionalMarkup","DistributionCosts","VehicleCosts","CarbonIntensity","EconomicAssumptions","CPI","VehicleLifetimeAndVMT")
# my fav color scheme
my.colors <- c(blue='#377eb8',green='#227222',orange='#C66200',purple='#470467',red='#B30C0C',yellow='#C6A600',light.green='#C0E0C0',magenta='#D0339D',dark.blue='#23128F',brown='#542D06',grey='#8A8A8A',light.yellow='#FFE664',light.purple='#9C50C0',light.orange='#FFB164')
alt.colors <- c(BEV='blue',PHEV='dark.blue',H2='red',
CanolaBiodiesel='light.green',SoyBiodiesel='green',SoyRenewableDiesel='grey',TallowRenewableDiesel='brown',UCOBiodiesel='light.purple',
SugarcaneEthanol='yellow',CornEthanolDryMill='grey',FlexCornEthanolDryMill='magenta',FlexSorghumEthanol='light.orange',FlexSugarcaneEthanol='light.yellow',SorghumEthanol='orange')
alt.colors <- data.frame(AltKey=names(alt.colors),color=alt.colors,color.hex=my.colors[alt.colors])
alt.type.colors <- c(PEV='blue',H2='red',Biodiesel='green',Ethanol='yellow',Flex='light.yellow')
alt.type.colors <- data.frame(AltKey=names(alt.type.colors),color=alt.type.colors,color.hex=my.colors[alt.type.colors])
amort.veh.cost <- function(veh.cost,tot.vmt,seg.vmt,mj.per.mile){
lifetime.in.segment <- tot.vmt / seg.vmt
overnight.cap <- (1-get.param('FractionFinancedVeh')) * veh.cost
loan.principal <- get.param('FractionFinancedVeh') * veh.cost
amort.npv <- apply(cbind(loan.principal,overnight.cap,lifetime.in.segment),1,amort.the.loan)
amort.npv.per.MJ <- amort.npv / seg.vmt / mj.per.mile
amort.npv.per.MJ
}
amort.the.loan <- function(x){
loan.principal <- x[1]
overnight.cap <- x[2]
lifetime.in.segment <- x[3]
loan.payments <- rep(loan.principal * get.param('FinanceRateVeh') / (1 - (1+get.param('FinanceRateVeh'))^-get.param('FinanceTermVeh')),get.param('FinanceTermVeh'))
loan.payments.disc <- loan.payments / (1 + get.param('DiscountRate'))^(1:(get.param('FinanceTermVeh')))
amort.npv <- (overnight.cap + sum(loan.payments.disc))*(get.param('DiscountRate')*(1+get.param('DiscountRate'))^lifetime.in.segment)/((1+get.param('DiscountRate'))^lifetime.in.segment - 1)
amort.npv
}
setup.pricing <- function(){
station.cost <<- 1
overnight.cap <<- (1-get.param('FractionFinancedDist')) * station.cost
loan.principal <<- get.param('FractionFinancedDist') * station.cost
loan.payments <<- rep(loan.principal * get.param('FinanceRateDist') / (1 - (1+get.param('FinanceRateDist'))^-get.param('FinanceTermDist')),get.param('FinanceTermDist'))
loan.payments.disc <<- loan.payments / (1 + get.param('DiscountRate'))^(0:(get.param('FinanceTermDist')-1))
amort.dist.ratio <<- (overnight.cap + sum(loan.payments.disc))*(get.param('DiscountRate')*(1+get.param('DiscountRate'))^get.param('DistributionLifetime'))/((1+get.param('DiscountRate'))^get.param('DistributionLifetime') - 1) / 1e3 # 1e3 converts from GJ to MJ
pens <<- inputs[['AltFuelPenetrationLimits']]
fuel.markup <<- inputs[['FuelRegionalMarkup']]
setkey(fuel.markup,Replaces)
carb <<- copy(inputs[['CarbonIntensity']])
gas.carb <<- carb[AltFuel=='Gas']$Intensity
gas.mj.per.gal <<- carb[AltFuel=='Gas']$ConversionFactor
diesel.carb <<- carb[AltFuel=='Diesel']$Intensity
flex.carb <<- carb[AltFuelType=='Ethanol']
flex.blend.by.energy <<- cbind(flex.carb$ConversionFactor * get.param('FlexBlend'),(1-get.param('FlexBlend'))* gas.mj.per.gal)
flex.blend.by.energy <<- as.data.frame(t(apply(flex.blend.by.energy,1,function(x){ x/sum(x) })))
names(flex.blend.by.energy) <<- c('flex','gas')
flex.carb[,':='(AltFuelType='Flex',Intensity=Intensity*flex.blend.by.energy$flex + gas.carb*flex.blend.by.energy$gas)]
eth.blend.by.energy <<- cbind(carb[AltFuelType=='Ethanol']$ConversionFactor * get.param('EthanolBlend'),(1-get.param('EthanolBlend'))* gas.mj.per.gal)
eth.blend.by.energy <<- as.data.frame(t(apply(eth.blend.by.energy,1,function(x){ x/sum(x) })))
names(eth.blend.by.energy) <<- c('eth','gas')
carb[AltFuelType=='Ethanol',':='(Intensity=Intensity*eth.blend.by.energy$eth + gas.carb*eth.blend.by.energy$gas)]
phev.carb<<- carb[AltFuelType=='Electricity']
phev.carb[,':='(AltFuelType='PHEV',AltFuel='PHEV',Intensity=Intensity*get.param('PHEVBlend')+gas.carb*(1-get.param('PHEVBlend')),EER=1/((1/EER)*get.param('PHEVBlend')+(1-get.param('PHEVBlend'))))]
carb[AltFuelType=='Biodiesel',':='(Intensity=Intensity*get.param('BiodieselBlend')+diesel.carb*(1-get.param('BiodieselBlend')))]
carb <<- rbindlist(list(carb,flex.carb,phev.carb),use.names=T,fill=T)
carb[AltFuelType=='Electricity',':='(AltFuelType='BEV',AltFuel='BEV')]
mark <<- inputs[['MarketStructure']]
ghg.goal <<- sum(mark$GHG) - (sum(mark[FuelType=='Gas']$EnergyDemand*1e3)*get.param('TargetGasolineIntensity') + sum(mark[FuelType=='Diesel']$EnergyDemand*1e3)*get.param('TargetDieselIntensity'))/1e6
fuel.price.m <<- melt(inputs[['FuelTimeSeries']],id.vars=c('Year','Quarter'))
setkey(fuel.price.m,variable)
fuel.price <<- fuel.price.m[Year>=2010,list(PriceAvg=mean(value,na.rm=T)),by='variable']
fuel.price[,FuelType:=carb$AltFuelType[match(variable,carb$AltFuel)]]
fuel.price[,':='(AltFuel=variable,variable=NULL)]
fuel.price[,Replaces:='None']
fuel.price[FuelType=='Gas' | FuelType=='Ethanol',Replaces:='Gas']
fuel.price[FuelType=='Diesel' | FuelType=='Biodiesel',Replaces:='Diesel']
fuel.price[FuelType=='H2',Replaces:='H2']
setkey(fuel.price,Replaces)
fuel.price[,PriceRV:=PriceAvg]
elec.price <<- fuel.price[AltFuel=='Electricity']$PriceRV
gas.price <<- fuel.price[AltFuel=='Gas']$PriceRV
diesel.price <<- fuel.price[AltFuel=='Diesel']$PriceRV
# Blend Flex and Ethanol
setkey(fuel.price,FuelType,AltFuel)
flex.prices <<- copy(fuel.price[FuelType=='Ethanol'])
flex.prices[,':='(FuelType='Flex',PriceRV=PriceRV*flex.blend.by.energy$flex+gas.price*flex.blend.by.energy$gas)]
fuel.price[FuelType=='Ethanol',':='(PriceRV=PriceRV*eth.blend.by.energy$eth+gas.price*eth.blend.by.energy$gas)]
# Blend PHEV
phev.price <<- data.table(AltFuel='PHEV',FuelType='PHEV',Replaces='None',PriceRV=elec.price * get.param('PHEVBlend') + gas.price * (1 - get.param('PHEVBlend')))
# Blend Biodiesel
fuel.price[FuelType=='Biodiesel',':='(PriceRV=PriceRV*get.param('BiodieselBlend')+diesel.price*(1-get.param('BiodieselBlend')))]
# Rename Elec to BEV
fuel.price[AltFuel=='Electricity',':='(FuelType='BEV',AltFuel='BEV')]
fuel.price <<- rbindlist(list(fuel.price,flex.prices,phev.price),use.names=T,fill=T)
setkey(fuel.price,Replaces)
fuel.price.by.county <<- fuel.markup[fuel.price,allow.cart=T]
fuel.price.by.county[is.na(Markup),Markup:=0]
fuel.price.by.county[,FuelCost:=PriceRV+Markup]
# Now EER weight the cost using the LDV value for H2
setkey(carb,AltFuel,IntensityEER) # need this to get H2 in correct order
setkey(carb,AltFuel)
setkey(fuel.price.by.county,AltFuel)
fuel.price.by.county <<- unique(carb)[,list(AltFuel,EER)][fuel.price.by.county]
fuel.price.by.county[,FuelCost:=FuelCost/EER]
# Join the conventional prices to market segments for later use in making the fuel cost incremental
mark <<- copy(mark)
setkey(mark,County,FuelType)
setkey(fuel.price.by.county,County,FuelType)
mark <<- fuel.price.by.county[mark,list(County,FuelType,VehicleType,VehicleStatus,NumVehicles,SegmentVMT,EnergyDemand,GHG,travel.demand,FuelCost)]
mark[,':='(ConventionalFuelCost=FuelCost,FuelCost=NULL)]
# Now drop the conventionals
fuel.price.by.county <<- fuel.price.by.county[FuelType!="Gas" & FuelType!="Diesel"]
fuel.price.by.county[,':='(AltFuelType=FuelType,FuelType=NULL)]
###
# Sample and amortized the station cost into 2014$ / MJ
###
station.costs <<- inputs[['DistributionCosts']]
station.costs[is.na(DistCostSD),DistCostSD:=0.25*DistCostAvg]
station.costs[,DistCostRV:=DistCostAvg]
station.costs[,StationCost:=DistCostRV * amort.dist.ratio]
setkey(carb,AltFuelType,IntensityEER) # need this to get H2 in correct order
setkey(carb,AltFuelType)
setkey(station.costs,AltFuelType)
station.costs <<- unique(carb)[,list(AltFuelType,EER)][station.costs]
station.costs[,StationCost:=StationCost/EER]
###
# Sample and amortize the vehicle costs into 2014$ / MJ
###
veh.costs <<- inputs[['VehicleCosts']]
setkey(veh.costs,VehicleType)
setkey(mark,VehicleType)
veh.costs <<- mark[VehicleStatus=='New'][veh.costs, allow.cartesian=T]
veh.costs[,SegmentVMT.per.veh.per.yr:=SegmentVMT/NumVehicles]
tot.vmt <<- inputs[['VehicleLifetimeAndVMT']]
# we need to base lifetime vmt off of the appropriate fuel type
veh.costs[,FuelTypeForLifetime:=FuelType]
veh.costs[AltFuelType%in%c('BEV','PHEV','Flex'),FuelTypeForLifetime:='Gas']
tot.vmt[,FuelTypeForLifetime:=FuelType]
setkey(tot.vmt,FuelTypeForLifetime,VehicleType)
setkey(veh.costs,FuelTypeForLifetime,VehicleType)
veh.costs <<- tot.vmt[veh.costs]
veh.costs[,':='(FuelType=i.FuelType,i.FuelType=NULL)]
# we need to get the segment vmt aggregated across vehicle status
setkey(mark,County,FuelType,VehicleType)
agg.seg.vmt <<- mark[,list(AggSegmentVMTPerVeh=sum(SegmentVMT)/sum(NumVehicles)),by=c('County','FuelType','VehicleType')]
setkey(veh.costs,County,FuelType,VehicleType)
veh.costs <<- agg.seg.vmt[veh.costs,allow.cartesian=T]
setkey(veh.costs,AltFuelType,VehicleType)
setkey(carb,AltFuelType,VehicleType)
veh.costs <<- unique(carb)[,list(AltFuelType,VehicleType,EER)][veh.costs]
veh.costs[is.na(EER),EER:=1]
veh.costs[,MJ.EER.per.mile:=EnergyDemand / SegmentVMT * 1000]
veh.costs[,cost.per.MJ.EER := amort.veh.cost(VehicleCostAvg,VMTPerLifetime,AggSegmentVMTPerVeh,MJ.EER.per.mile)]
veh.costs[,cost.per.MJ.EER.ratio := cost.per.MJ.EER / VehicleCostAvg]
veh.costs[,':='(VehicleCost=VehicleCostAvg * cost.per.MJ.EER.ratio)]
return(NULL)
}
##########################
# Plot Functions
##########################
plot.mac <- function(the.macc,col.to.plot='MAC',errorbars=F,the.title='',y.lim=500){
to.use <- streval(pp('the.macc[!is.nan(',col.to.plot,') & !',col.to.plot,'==Inf]'))
to.use[,AbatementPotential:=AbatementPotential/1e3]
streval(pp('setkey(to.use,',col.to.plot,')'))
to.use[,key:=factor(pp(ifelse(AltFuelType=='Flex','Flex',''),AltFuel,' - ',County,' - ',VehicleStatus,FuelType,VehicleType))]
to.use[,key:=factor(to.use$key, to.use$key)] # reorders the levels to match their rank
to.use[,x.pos:=0.5*(cumsum(AbatementPotential)+cumsum(c(0, head(AbatementPotential,-1))))]
to.use <- streval(pp('to.use[',col.to.plot,'<',y.lim,']'))
p <- streval(pp('ggplot(to.use,aes(x=x.pos,label=key,width=AbatementPotential,y=',col.to.plot,',fill=AltFuel))'))
p <- p + geom_bar(stat='identity',position='identity',colour='black',linetype='blank')+
theme_bw()+
geom_vline(xintercept=ghg.goal/1e3,color=my.colors['red'],linetype='longdash')+
scale_fill_manual(values=as.character(alt.colors$color.hex[match(sort(u(to.use$AltFuel)),alt.colors$AltKey)]))
if(errorbars & pp(col.to.plot,'.sd') %in% names(to.use)){
max.y <- streval(pp('max(to.use$',col.to.plot,' + to.use$',col.to.plot,'.sd)'))
p <- p + geom_point()+
geom_errorbar(aes(ymin=MAC-MAC.sd,ymax=MAC+MAC.sd,width=0))+
scale_y_continuous(limit=c(-750,max.y))
}
if(col.to.plot == 'MAC'){
p <- p + labs(x='GHG Abatement (1000 tons CO2eq)',y='Marginal Abatement Cost ($/ton CO2eq)',fill='County',title=the.title)
}else{
p <- p + labs(x='GHG Abatement (1000 tons CO2eq)',y='Marginal Intensity Abatement Cost ($1000/(g/MJ))',fill='County',title=the.title)
}
print(p)
p
}
all.stats <- data.table()
scen <- scens[1]
for(scen in scens){
scenario.dir <- pp(afrp.shared,'Task-2.1-AFI-Deployment-Assessment/AFCI_Porfolio_Model/',scen,'/')
exper <- list(Factors=list(list(Name="Base",Levels=c('Base'))))
if(file.exists(pp(scenario.dir,'exper.yaml'))){
exper <- yaml.load(readChar(pp(scenario.dir,'exper.yaml'),file.info(pp(scenario.dir,'exper.yaml'))$size))
}
if("InputFile" %in% names(exper)){
input.file <- pp(scenario.dir,exper$InputFile)
}else{
input.file <- pp(scenario.dir,'AFCI_Portfolio_Inputs.xlsx')
}
plot.dir <- pp(plot.dir.base,scen,'/')
make.dir(plot.dir)
load(file=pp(scenario.dir,'results.Rdata'))
level.combs <- results$level.combs
names(level.combs) <- str_replace_all(names(level.combs)," ","_")
num.factors <- ncol(level.combs)
all.avg.maccs <- data.table()
level.i <- 1
####################################################################################################
# Factorial loop
####################################################################################################
for(level.i in 1:nrow(level.combs)){
my.cat(pp(pp(names(level.combs),":",level.combs[level.i,]),collapse=' X '))
inputs<-list()
for(sheet in sheets){
load.inputs(sheet)
}
for(fac.i in 1:num.factors){
if('Scale' %in% names(exper$Factors[[fac.i]])){
sheet <- names(exper$Factors[[fac.i]]$Scale)
lev.1d.i <- which(exper$Factors[[fac.i]]$Levels == level.combs[level.i,fac.i])
if('Row' %in% names(exper$Factors[[fac.i]]$Scale[[sheet]])){
column <- names(exper$Factors[[fac.i]]$Scale[[sheet]])[!names(exper$Factors[[fac.i]]$Scale[[sheet]])=='Row']
col.names <- names(exper$Factors[[fac.i]]$Scale[[sheet]]$Row)
row.keys <- sapply(exper$Factors[[fac.i]]$Scale[[sheet]]$Row,function(x){ x })
streval(pp('inputs[["',sheet,'"]][',pp(col.names,'=="',row.keys,'"',collapse="&"),',',column,':=',column,'*',exper$Factors[[fac.i]]$Scale[[sheet]][[column]][[lev.1d.i]],']'))
}else{
column <- names(exper$Factors[[fac.i]]$Scale[[sheet]])
streval(pp('inputs[["',sheet,'"]][,',column,':=',column,'*',exper$Factors[[fac.i]]$Scale[[sheet]][[column]][[lev.1d.i]],']'))
}
}
}
setup.pricing()
the.macc <- results$the.macc[[level.i]]
mac.results <- results$mac.results[[level.i]]
####################################################
# Summarize and store the avg MACC and key stats
####################################################
# for incomplete results, constrain the inds
inds <- which(!is.na(mac.results[1,,2]))
# Find average cost/rank
setkey(the.macc,VehicleStatus,VehicleType,FuelType,County,AltFuelType,AltFuel)
avg.results <- the.macc[,list(VehicleStatus,VehicleType,FuelType,County,AltFuelType,AltFuel,EnergyDemand,GHG)]
avg.results[,':='(MAC=apply(mac.results[,inds,2],1,mean,na.rm=T),MAC.sd=apply(mac.results[,inds,2],1,sd),MIAC=apply(mac.results[,inds,4],1,mean,na.rm=T),MIAC.sd=apply(mac.results[,inds,4],1,sd),AbatementPotential=apply(mac.results[,inds,3],1,mean))]
avg.results <- avg.results[!is.nan(MAC) & !MAC==Inf]
avg.results[,AbatementPotential:=AbatementPotential/1e3]
avg.results[,rank:=rank(MAC,ties.method='random')]
n.trials <- dim(mac.results)[2]
# Report the total cost of the solution and the conventional cost by comparison
setkey(avg.results,MAC)
avg.results[,CumulativeAbatement:=cumsum(AbatementPotential)]
avg.results[,TotalCost:=MAC * AbatementPotential / 1e3] # AbatementPotential is in K-tons, so this puts cost into $M
mark[,TotalCost:=EnergyDemand*ConventionalFuelCost * 1e3 / 1e6] # puts cost into $M
avg.results[,Penetration:=AbatementPotential*1e3/GHG]
avg.results[,EnergyPenetrated:=EnergyDemand*Penetration]
avg.results[,MJToGalFactor:=c('Gas'=115.63,'Diesel'=134)[FuelType]]
avg.results[,GalPenetrated:=EnergyPenetrated*1e3/MJToGalFactor]
stats <- data.table(WtAvgMAC=avg.results[CumulativeAbatement<ghg.goal/1e3,list(WtAvg=weighted.mean(MAC,AbatementPotential))]$WtAvg,NetCost=sum(avg.results[CumulativeAbatement <= ghg.goal/1e3]$TotalCost),BAUCost=sum(mark$TotalCost))
setkey(avg.results,MAC)
avg.results[,x.pos:=0.5*(cumsum(AbatementPotential)+cumsum(c(0, head(AbatementPotential,-1))))]
avg.results[,WtAvgMAC:=stats$WtAvgMAC]
for(fac.i in 1:num.factors){
fac.name <- names(level.combs)[fac.i]
streval(pp('avg.results[,',fac.name,':="',level.combs[level.i,fac.i],'"]'))
streval(pp('stats[,":="(Factor="',fac.name,'",Level="',level.combs[level.i,fac.i],'")]'))
}
all.avg.maccs <- rbindlist(list(all.avg.maccs,avg.results),use.names=T,fill=T)
all.stats <- rbindlist(list(all.stats,stats),use.names=T,fill=T)
}
all.avg.maccs[,key:=factor(pp(ifelse(AltFuelType=='Flex','Flex',''),AltFuel))]
for(fac.i in 1:num.factors){
fac.name <- names(level.combs)[fac.i]
streval(pp('all.avg.maccs[,',fac.name,':=factor(',fac.name,',level.combs[,',fac.i,'])]'))
}
if(make.plots){
to.use <- all.avg.maccs[AbatementPotential>0]
factor.name <- names(level.combs)[1]
streval(pp('setkey(to.use,',factor.name,',MAC)'))
to.use[,first.over.target:=CumulativeAbatement >= ghg.goal/1e3]
streval(pp('to.use[,first.over.target:=(first.over.target==T & c(F,head(first.over.target,-1))==F),by="',factor.name,'"]'))
to.use <- to.use[CumulativeAbatement <= ghg.goal/1e3 | first.over.target==T]
setkey(to.use,MAC)
alt.order <- to.use[,list(key=key[1]),by='key']
to.use[,key:=factor(key,alt.order$key)]
#to.use[abs(MAC)>1000,MAC:=1000*sign(MAC)]
p <- ggplot(to.use,aes(x=x.pos,label=key,width=AbatementPotential,y=MAC,fill=key))+
geom_bar(stat='identity',position='identity',colour='black',linetype='blank')+
theme_bw()+
geom_hline(aes(yintercept=WtAvgMAC),colour=my.colors['grey'],linetype='longdash')+
geom_vline(xintercept=ghg.goal/1e3,color=my.colors['red'],linetype='longdash')+
coord_cartesian(xlim = c(-10,ghg.goal/1e3+10),ylim=c(max(-1000,min(to.use$MAC))-20,min(1000,max(to.use$MAC))+20))+
scale_fill_manual(values=as.character(alt.colors$color.hex[match(sort(u(to.use$key)),alt.colors$AltKey)]))+
labs(x='GHG Abatement (kt CO2eq)',y='Marginal Abatement Cost ($/t CO2eq)',fill='Alternative',title=pp(exper$Name,': Average MACCs (',n.trials,' Trials)'))
p <- p + streval(pp('facet_wrap(~',factor.name,')'))
if(nrow(level.combs)==3){
ggsave(file=pp(plot.dir,'macc-avg.pdf'),plot=p,width=12,height=4)
}else if(nrow(level.combs)==4 | nrow(level.combs)==1){
ggsave(file=pp(plot.dir,'macc-avg.pdf'),plot=p,width=12,height=8)
}
}
}
# stats in slightly more useable form for comparing
#cast(melt(all.stats,measure.vars=c('WtAvgMAC','NetCost')),Factor + variable ~ Level)
#cast(melt(all.stats,measure.vars=c('WtAvgMAC','NetCost')),Factor ~ variable + Level)
|
library(party)
library(C50)
df = read.csv("Company_Data.csv")
str(df)
head(df)
pairs(df)
range(df$Sales)
median(df$Sales)
sort(df$Sales)
length(df$Sales)
# Less Assume 3 sales segments I may consider low, Medium and High.
# Lets see the cutoff for High sales
sort(df$Sales)[(400/3 * 2)]
# As here cutoff we got is 8.67
# so we can condider that those sales which values are gratter than 8.5 will be considered as High sales and rest will be low sales
SaleC <- ifelse(df$Sales > 8.5,"High","Low")
prop.table(table(SaleC)) # Desired result achieved
comp <- data.frame(SaleC,df[,-1])
set.seed(101);split <- sample(nrow(comp),nrow(comp)*.7,F)
Train_comp <- comp[split,]
Test_comp <- comp[-split,]
#Model Building
model<-C5.0(SaleC~.,data = Train_comp)
#Generate the model summary
summary(model)
#Predict for test data set
prob<-predict.C5.0(model,Test_comp[,-5]) #type ="prob"
#Accuracy of the algorithm
a<-table(Test_comp$Sales,pred)
sum(diag(a))/sum(a)
#Visualize the decision tree
plot(model)
|
/Decision Forest.R
|
no_license
|
AkshayChopade07/R-Codes
|
R
| false | false | 1,034 |
r
|
library(party)
library(C50)
df = read.csv("Company_Data.csv")
str(df)
head(df)
pairs(df)
range(df$Sales)
median(df$Sales)
sort(df$Sales)
length(df$Sales)
# Less Assume 3 sales segments I may consider low, Medium and High.
# Lets see the cutoff for High sales
sort(df$Sales)[(400/3 * 2)]
# As here cutoff we got is 8.67
# so we can condider that those sales which values are gratter than 8.5 will be considered as High sales and rest will be low sales
SaleC <- ifelse(df$Sales > 8.5,"High","Low")
prop.table(table(SaleC)) # Desired result achieved
comp <- data.frame(SaleC,df[,-1])
set.seed(101);split <- sample(nrow(comp),nrow(comp)*.7,F)
Train_comp <- comp[split,]
Test_comp <- comp[-split,]
#Model Building
model<-C5.0(SaleC~.,data = Train_comp)
#Generate the model summary
summary(model)
#Predict for test data set
prob<-predict.C5.0(model,Test_comp[,-5]) #type ="prob"
#Accuracy of the algorithm
a<-table(Test_comp$Sales,pred)
sum(diag(a))/sum(a)
#Visualize the decision tree
plot(model)
|
#### This provides the complete code to read in the household power consumption data
##### from a file saved in the same directory, get the data for the first two days in February 2007
##### then produce the fourth chart (a panel plot of four other graphs) and save it as a .png file.
pwrdata <-read.table("household_power_consumption.txt", sep = ";", na.strings = "?", header = TRUE)
#Convert the date column from a factor to a date
pwrdata$Date = as.Date(pwrdata$Date, format = "%d/%m/%Y")
#Get the data for the first two days in February 2007
thedata<-pwrdata[pwrdata$Date==as.Date("1/2/2007",format = "%d/%m/%Y") | pwrdata$Date==as.Date("2/2/2007",format = "%d/%m/%Y"),]
#Delete the full data set from memory - it is no longer needed
> rm(pwrdata)
#Convert the time column from a factor to a time
tempdate <-as.character(thedata$Date) #string holding the date
temptime <-as.character(thedata$Time) #string holding the time
tempdatetime = paste(tempdate, temptime) #string holding both date and time
thedata$Time <-strptime(tempdatetime, "%Y-%m-%d %H:%M:%S") #Convert the time column
#set up grid for four graphs
par(mfrow = c(2, 2))
#top left panel
plot(thedata$Time,thedata$Global_active_power, xlab = "", ylab = "Global Active Power (kilowatts)",type = "n")
lines(thedata$Time,thedata$Global_active_power)
#top right panel
plot(thedata$Time,thedata$Voltage, ylab = "Voltage", xlab = "datetime",type = "n")
lines(thedata$Time,thedata$Voltage)
#bottom left panel
plot(thedata$Time,thedata$Sub_metering_1, xlab = "", ylab = "Energy sub metering",type = "n")
lines(thedata$Time,thedata$Sub_metering_1)
lines(thedata$Time, thedata$Sub_metering_2, col = "red")
lines(thedata$Time,thedata$Sub_metering_3, col = "blue")
legend("topright", lty = c(1,1,1), col = c("black", "red","blue"), legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), bty = "n", cex = 0.7)
#bottom right panel
plot(thedata$Time,thedata$Global_reactive_power, ylab = "Global_reactive_power", xlab = "datetime",type = "n")
lines(thedata$Time,thedata$Global_reactive_power)
#copy the file to a png file
dev.copy(png, height = 480, width = 480, file = "plot4.png")
dev.off() #close the png device
|
/plot4.R
|
no_license
|
james882/ExData_Plotting1
|
R
| false | false | 2,206 |
r
|
#### This provides the complete code to read in the household power consumption data
##### from a file saved in the same directory, get the data for the first two days in February 2007
##### then produce the fourth chart (a panel plot of four other graphs) and save it as a .png file.
pwrdata <-read.table("household_power_consumption.txt", sep = ";", na.strings = "?", header = TRUE)
#Convert the date column from a factor to a date
pwrdata$Date = as.Date(pwrdata$Date, format = "%d/%m/%Y")
#Get the data for the first two days in February 2007
thedata<-pwrdata[pwrdata$Date==as.Date("1/2/2007",format = "%d/%m/%Y") | pwrdata$Date==as.Date("2/2/2007",format = "%d/%m/%Y"),]
#Delete the full data set from memory - it is no longer needed
> rm(pwrdata)
#Convert the time column from a factor to a time
tempdate <-as.character(thedata$Date) #string holding the date
temptime <-as.character(thedata$Time) #string holding the time
tempdatetime = paste(tempdate, temptime) #string holding both date and time
thedata$Time <-strptime(tempdatetime, "%Y-%m-%d %H:%M:%S") #Convert the time column
#set up grid for four graphs
par(mfrow = c(2, 2))
#top left panel
plot(thedata$Time,thedata$Global_active_power, xlab = "", ylab = "Global Active Power (kilowatts)",type = "n")
lines(thedata$Time,thedata$Global_active_power)
#top right panel
plot(thedata$Time,thedata$Voltage, ylab = "Voltage", xlab = "datetime",type = "n")
lines(thedata$Time,thedata$Voltage)
#bottom left panel
plot(thedata$Time,thedata$Sub_metering_1, xlab = "", ylab = "Energy sub metering",type = "n")
lines(thedata$Time,thedata$Sub_metering_1)
lines(thedata$Time, thedata$Sub_metering_2, col = "red")
lines(thedata$Time,thedata$Sub_metering_3, col = "blue")
legend("topright", lty = c(1,1,1), col = c("black", "red","blue"), legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), bty = "n", cex = 0.7)
#bottom right panel
plot(thedata$Time,thedata$Global_reactive_power, ylab = "Global_reactive_power", xlab = "datetime",type = "n")
lines(thedata$Time,thedata$Global_reactive_power)
#copy the file to a png file
dev.copy(png, height = 480, width = 480, file = "plot4.png")
dev.off() #close the png device
|
test_script <- function() {
library(data.table)
t <- as.data.table(list(
col1 = rep(1,100),
col2 = rep(2,100),
col3 = c(rep("a",50),rep("b",50)),
col4 = c(rep("d",25),rep("e",25),rep("f",25),rep("g",25))
))
pivot_table_gadget(t)
}
|
/R/test_script.R
|
no_license
|
mrhopko/pivotTableFlavoR
|
R
| false | false | 265 |
r
|
test_script <- function() {
library(data.table)
t <- as.data.table(list(
col1 = rep(1,100),
col2 = rep(2,100),
col3 = c(rep("a",50),rep("b",50)),
col4 = c(rep("d",25),rep("e",25),rep("f",25),rep("g",25))
))
pivot_table_gadget(t)
}
|
library("clickstream")
library("arulesSequences")
## Load Data
cls <- readClickstreams(file = "path_to_file", sep = ",", header = F)
cls
summary(cls)
## Fitting Markov Chain
mc <- fitMarkovChain(clickstreamList = cls, order = 3)
options(digits = 2)
##compute transition probabilities
mc
options(digits = 7)
summary(mc)
##plot transition diagram and heatmap
plot(mc)
hmPlot(mc)
##clustering
set.seed(42)
clusters <- clusterClickstreams(clickstreamList = cls, order = 1, centers = 2)
clusters
#To produce the clustering plot of the post in the code of function clusterClickstreams
#add tthe following in line 17:
# ggplot(transitionData, aes(StatesChanged,id, colour=fit$cluster))+geom_point()
summary(clusters)
#Predict clicks
pattern <- new("Pattern", sequence = c("Action14", "Action4"))
resultPattern <- predict(mc, startPattern = pattern, dist = 1) # set dist = n to predict n steps ahead
resultPattern
##cSPACE data mining
frequencyDF <- frequencies(cls)
frequencyDF
trans <- as.transactions(cls)
sequences <- as(cspade(trans, parameter = list(support = 0)), "data.frame")
sequences
|
/clickstream_analysis.R
|
permissive
|
jaradc/ClickstreamAnalysis
|
R
| false | false | 1,096 |
r
|
library("clickstream")
library("arulesSequences")
## Load Data
cls <- readClickstreams(file = "path_to_file", sep = ",", header = F)
cls
summary(cls)
## Fitting Markov Chain
mc <- fitMarkovChain(clickstreamList = cls, order = 3)
options(digits = 2)
##compute transition probabilities
mc
options(digits = 7)
summary(mc)
##plot transition diagram and heatmap
plot(mc)
hmPlot(mc)
##clustering
set.seed(42)
clusters <- clusterClickstreams(clickstreamList = cls, order = 1, centers = 2)
clusters
#To produce the clustering plot of the post in the code of function clusterClickstreams
#add tthe following in line 17:
# ggplot(transitionData, aes(StatesChanged,id, colour=fit$cluster))+geom_point()
summary(clusters)
#Predict clicks
pattern <- new("Pattern", sequence = c("Action14", "Action4"))
resultPattern <- predict(mc, startPattern = pattern, dist = 1) # set dist = n to predict n steps ahead
resultPattern
##cSPACE data mining
frequencyDF <- frequencies(cls)
frequencyDF
trans <- as.transactions(cls)
sequences <- as(cspade(trans, parameter = list(support = 0)), "data.frame")
sequences
|
testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.31584307392677e+77, 9.85751697122895e+295, 1.22810536108214e+146, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(10L, 3L)))
result <- do.call(CNull:::communities_individual_based_sampling_alpha,testlist)
str(result)
|
/CNull/inst/testfiles/communities_individual_based_sampling_alpha/AFL_communities_individual_based_sampling_alpha/communities_individual_based_sampling_alpha_valgrind_files/1615777940-test.R
|
no_license
|
akhikolla/updatedatatype-list2
|
R
| false | false | 348 |
r
|
testlist <- list(m = NULL, repetitions = 0L, in_m = structure(c(2.31584307392677e+77, 9.85751697122895e+295, 1.22810536108214e+146, 4.12396251261199e-221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(10L, 3L)))
result <- do.call(CNull:::communities_individual_based_sampling_alpha,testlist)
str(result)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/removeSeq.R
\name{removeSeq}
\alias{removeSeq}
\title{Remove sequence}
\usage{
removeSeq(file.list, sequence)
}
\arguments{
\item{file.list}{A list of data frames imported using the LymphoSeq function
readImmunoSeq. "aminoAcid", "count", and "frequencyCount" are required columns.}
\item{sequence}{A character vector of one or more amino acid sequences to
remove from the list of data frames.}
}
\value{
Returns a list of data frames like the one imported except all rows
with the specified amino acid sequence are removed. The frequencyCount is
recalculated.
}
\description{
Removes an amino acid sequence and associated data from all instances within
a list of data frames and then recomputes the frequencyCount.
}
\examples{
file.path <- system.file("extdata", "TCRB_sequencing", package = "LymphoSeq")
file.list <- readImmunoSeq(path = file.path)
searchSeq(list = file.list, sequence = "CASSDLIGNGKLFF")
cleansed <- removeSeq(file.list = file.list, sequence = "CASSDLIGNGKLFF")
searchSeq(list = cleansed, sequence = "CASSDLIGNGKLFF")
}
|
/man/removeSeq.Rd
|
no_license
|
davidcoffey/LymphoSeq
|
R
| false | true | 1,130 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/removeSeq.R
\name{removeSeq}
\alias{removeSeq}
\title{Remove sequence}
\usage{
removeSeq(file.list, sequence)
}
\arguments{
\item{file.list}{A list of data frames imported using the LymphoSeq function
readImmunoSeq. "aminoAcid", "count", and "frequencyCount" are required columns.}
\item{sequence}{A character vector of one or more amino acid sequences to
remove from the list of data frames.}
}
\value{
Returns a list of data frames like the one imported except all rows
with the specified amino acid sequence are removed. The frequencyCount is
recalculated.
}
\description{
Removes an amino acid sequence and associated data from all instances within
a list of data frames and then recomputes the frequencyCount.
}
\examples{
file.path <- system.file("extdata", "TCRB_sequencing", package = "LymphoSeq")
file.list <- readImmunoSeq(path = file.path)
searchSeq(list = file.list, sequence = "CASSDLIGNGKLFF")
cleansed <- removeSeq(file.list = file.list, sequence = "CASSDLIGNGKLFF")
searchSeq(list = cleansed, sequence = "CASSDLIGNGKLFF")
}
|
# read the dataset from the source text file which was unzip in a local folder
dataset <- read.table(file = "D:/Disco D/data/EDA/Week1/household_power_consumption.txt",
sep=";", stringsAsFactors = FALSE, na.strings = '?', skipNul = TRUE, header = TRUE)
## We will only be using data from the dates 2007-02-01 and 2007-02-02.
subdata <- dataset[dataset$Date %in% c("1/2/2007", "2/2/2007"),]
subdata$Date <- as.Date.character(subdata$Date, format = "%d/%m/%Y")
Sys.setlocale("LC_TIME", "English")
datetime <- strptime(paste(as.character(subdata$Date),subdata$Time), format = "%Y-%m-%d %H:%M:%S")
## Launch the png graphic device
png(filename = "Plot4.png")
## define 2 rows and 2 columns
par(mfrow = c(2,2))
## make the plots
plot(datetime, subdata$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power")
plot(datetime, subdata$Voltage , type = "l", xlab = "datetime", ylab = "Voltage")
with(subdata, plot(datetime, Sub_metering_1, type = "n", xlab="", ylab="Energy sub metering"))
with(subdata, points(datetime, Sub_metering_1, type = "l", main = "Sub_metering_1"))
with(subdata, points(datetime, Sub_metering_2, type = "l", col="red", main = "Sub_metering_2"))
with(subdata, points(datetime, Sub_metering_3, type = "l", col="blue", main = "Sub_metering_3"))
legend("topright", lwd = 2, lty=1, bty="n", col = c("black","red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
plot(datetime, subdata$Global_reactive_power , type = "l", xlab = "datetime",
ylab = "Global_reactive_power")
## close graphic device
dev.off()
|
/Plot4.R
|
no_license
|
PattyCh/ExData_Plotting1
|
R
| false | false | 1,599 |
r
|
# read the dataset from the source text file which was unzip in a local folder
dataset <- read.table(file = "D:/Disco D/data/EDA/Week1/household_power_consumption.txt",
sep=";", stringsAsFactors = FALSE, na.strings = '?', skipNul = TRUE, header = TRUE)
## We will only be using data from the dates 2007-02-01 and 2007-02-02.
subdata <- dataset[dataset$Date %in% c("1/2/2007", "2/2/2007"),]
subdata$Date <- as.Date.character(subdata$Date, format = "%d/%m/%Y")
Sys.setlocale("LC_TIME", "English")
datetime <- strptime(paste(as.character(subdata$Date),subdata$Time), format = "%Y-%m-%d %H:%M:%S")
## Launch the png graphic device
png(filename = "Plot4.png")
## define 2 rows and 2 columns
par(mfrow = c(2,2))
## make the plots
plot(datetime, subdata$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power")
plot(datetime, subdata$Voltage , type = "l", xlab = "datetime", ylab = "Voltage")
with(subdata, plot(datetime, Sub_metering_1, type = "n", xlab="", ylab="Energy sub metering"))
with(subdata, points(datetime, Sub_metering_1, type = "l", main = "Sub_metering_1"))
with(subdata, points(datetime, Sub_metering_2, type = "l", col="red", main = "Sub_metering_2"))
with(subdata, points(datetime, Sub_metering_3, type = "l", col="blue", main = "Sub_metering_3"))
legend("topright", lwd = 2, lty=1, bty="n", col = c("black","red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
plot(datetime, subdata$Global_reactive_power , type = "l", xlab = "datetime",
ylab = "Global_reactive_power")
## close graphic device
dev.off()
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/cluster_mutual_information.R
\name{cluster_mutual_information}
\alias{cluster_mutual_information}
\title{A MVDA Function}
\usage{
cluster_mutual_information(vc1, vc2, elem)
}
\arguments{
\item{vc1}{a numeric vector of clustering results}
\item{vc2}{a numeric vector of clustering results}
\item{elem}{the matrix representing your dataset}
}
\value{
the mutual information between clustering
}
\description{
This function evaluate the mutual information between two clustering results
}
\keyword{clustering;}
\keyword{entropy}
\keyword{multi-view}
|
/MVDA_package/man/cluster_mutual_information.Rd
|
no_license
|
angy89/MVDA
|
R
| false | false | 636 |
rd
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/cluster_mutual_information.R
\name{cluster_mutual_information}
\alias{cluster_mutual_information}
\title{A MVDA Function}
\usage{
cluster_mutual_information(vc1, vc2, elem)
}
\arguments{
\item{vc1}{a numeric vector of clustering results}
\item{vc2}{a numeric vector of clustering results}
\item{elem}{the matrix representing your dataset}
}
\value{
the mutual information between clustering
}
\description{
This function evaluate the mutual information between two clustering results
}
\keyword{clustering;}
\keyword{entropy}
\keyword{multi-view}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/NegLogInt_Fn.R
\name{NegLogInt_Fn}
\alias{NegLogInt_Fn}
\title{Perform SS implementation of Laplace Approximation}
\usage{
NegLogInt_Fn(File = NA, Input_SD_Group_Vec, CTL_linenum_List, ESTPAR_num_List,
PAR_num_Vec, Int_Group_List = list(1), StartFromPar = TRUE,
Intern = TRUE, ReDoBiasRamp = FALSE, BiasRamp_linenum_Vec = NULL,
CTL_linenum_Type = NULL, systemcmd = FALSE, exe = "ss")
}
\arguments{
\item{File}{Directory containing Stock Synthesis files
(e.g., "C:/Users/James Thorson/Desktop/")}
\item{Input_SD_Group_Vec}{Vector where each element is the standard deviation
for a group of random effects (e.g., a model with a single group of random
effects will have Input_SD_Group_Vec be a vector of length one)}
\item{CTL_linenum_List}{List (same length as \code{Input_SD_Group_Vec}),
where each
element is a vector giving the line number(s) for the random effect standard
deviation parameter or penalty in the CTL file (and where each line will
correspond to a 7-parameter or 14-parameter line).}
\item{ESTPAR_num_List}{List (same length as \code{Input_SD_Group_Vec}),
where each
element is a vector giving the parameter number for the random effect
coefficients in that group of random effects. These "parameter numbers"
correspond to the number of these parameters in the list of parameters in the
".cor" output file.}
\item{PAR_num_Vec}{Vector giving the number in the ".par" vector for each
random effect coefficient.}
\item{Int_Group_List}{List where each element is a vector, providing a way of
grouping different random effect groups into a single category. Although
this input is still required, it is no has the former input Version has been
hardwired to Version = 1.}
\item{StartFromPar}{Logical flag (TRUE or FALSE) saying whether to start each
round of optimization from a ".par" file (I recommend TRUE)}
\item{Intern}{Logical flag saying whether to display all ss3 runtime output
in the R terminal}
\item{ReDoBiasRamp}{Logical flag saying whether to re-do the bias ramp
(using \code{\link{SS_fitbiasramp}}) each time Stock Synthesis is run.}
\item{BiasRamp_linenum_Vec}{Vector giving the line numbers from the CTL file
that contain the information about the bias ramp.}
\item{CTL_linenum_Type}{Character vector (same length as
\code{Input_SD_Group_Vec}),
where each element is either "Short_Param", "Long_Penalty", "Long_Penalty".
Default is NULL, and if not explicitly specified the program will attempt to
detect these automatically based on the length of relevant lines from the CTL
file.}
\item{systemcmd}{Should R call SS using "system" function instead of "shell".
This may be required when running R in Emacs on Windows. Default = FALSE.}
\item{exe}{SS executable name (excluding extension), either "ss" or "ss3".
This string is used for both calling the executable and also finding the
output files like ss.par. For 3.30, it should always be "ss" since the
output file names are hardwired in the TPL code.}
}
\description{
(Attempt to) perform the SS implementation of the Laplace Approximation
from Thorson, Hicks and Methot (2014) ICES J. Mar. Sci.
}
\examples{
\dontrun{
direc <- "C:/Models/LaplaceApprox/base" #need the full path because wd is changed in function
if("Optimization_record.txt" \%in\% list.files(direc)) {
file.remove(file.path(direc,"Optimization_record.txt"))
}
Opt = optimize(f=NegLogInt_Fn,
interval=c(0.001, 0.12),
maximum=FALSE,
File=direc,
Input_SD_Group_Vec=1,
CTL_linenum_List=list(127:131),
ESTPAR_num_List=list(86:205),
Int_Group_List=1,
PAR_num_Vec=NA,
Intern=TRUE)
}
}
\references{
Thorson, J.T., Hicks, A.C., and Methot, R.D. 2014. Random
effect estimation of time-varying factors in Stock Synthesis. ICES J. Mar.
Sci.
}
\seealso{
\code{\link{read.admbFit}}, \code{\link{getADMBHessian}}
}
\author{
James Thorson
}
|
/man/NegLogInt_Fn.Rd
|
no_license
|
paulburch/r4ss
|
R
| false | true | 4,070 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/NegLogInt_Fn.R
\name{NegLogInt_Fn}
\alias{NegLogInt_Fn}
\title{Perform SS implementation of Laplace Approximation}
\usage{
NegLogInt_Fn(File = NA, Input_SD_Group_Vec, CTL_linenum_List, ESTPAR_num_List,
PAR_num_Vec, Int_Group_List = list(1), StartFromPar = TRUE,
Intern = TRUE, ReDoBiasRamp = FALSE, BiasRamp_linenum_Vec = NULL,
CTL_linenum_Type = NULL, systemcmd = FALSE, exe = "ss")
}
\arguments{
\item{File}{Directory containing Stock Synthesis files
(e.g., "C:/Users/James Thorson/Desktop/")}
\item{Input_SD_Group_Vec}{Vector where each element is the standard deviation
for a group of random effects (e.g., a model with a single group of random
effects will have Input_SD_Group_Vec be a vector of length one)}
\item{CTL_linenum_List}{List (same length as \code{Input_SD_Group_Vec}),
where each
element is a vector giving the line number(s) for the random effect standard
deviation parameter or penalty in the CTL file (and where each line will
correspond to a 7-parameter or 14-parameter line).}
\item{ESTPAR_num_List}{List (same length as \code{Input_SD_Group_Vec}),
where each
element is a vector giving the parameter number for the random effect
coefficients in that group of random effects. These "parameter numbers"
correspond to the number of these parameters in the list of parameters in the
".cor" output file.}
\item{PAR_num_Vec}{Vector giving the number in the ".par" vector for each
random effect coefficient.}
\item{Int_Group_List}{List where each element is a vector, providing a way of
grouping different random effect groups into a single category. Although
this input is still required, it is no has the former input Version has been
hardwired to Version = 1.}
\item{StartFromPar}{Logical flag (TRUE or FALSE) saying whether to start each
round of optimization from a ".par" file (I recommend TRUE)}
\item{Intern}{Logical flag saying whether to display all ss3 runtime output
in the R terminal}
\item{ReDoBiasRamp}{Logical flag saying whether to re-do the bias ramp
(using \code{\link{SS_fitbiasramp}}) each time Stock Synthesis is run.}
\item{BiasRamp_linenum_Vec}{Vector giving the line numbers from the CTL file
that contain the information about the bias ramp.}
\item{CTL_linenum_Type}{Character vector (same length as
\code{Input_SD_Group_Vec}),
where each element is either "Short_Param", "Long_Penalty", "Long_Penalty".
Default is NULL, and if not explicitly specified the program will attempt to
detect these automatically based on the length of relevant lines from the CTL
file.}
\item{systemcmd}{Should R call SS using "system" function instead of "shell".
This may be required when running R in Emacs on Windows. Default = FALSE.}
\item{exe}{SS executable name (excluding extension), either "ss" or "ss3".
This string is used for both calling the executable and also finding the
output files like ss.par. For 3.30, it should always be "ss" since the
output file names are hardwired in the TPL code.}
}
\description{
(Attempt to) perform the SS implementation of the Laplace Approximation
from Thorson, Hicks and Methot (2014) ICES J. Mar. Sci.
}
\examples{
\dontrun{
direc <- "C:/Models/LaplaceApprox/base" #need the full path because wd is changed in function
if("Optimization_record.txt" \%in\% list.files(direc)) {
file.remove(file.path(direc,"Optimization_record.txt"))
}
Opt = optimize(f=NegLogInt_Fn,
interval=c(0.001, 0.12),
maximum=FALSE,
File=direc,
Input_SD_Group_Vec=1,
CTL_linenum_List=list(127:131),
ESTPAR_num_List=list(86:205),
Int_Group_List=1,
PAR_num_Vec=NA,
Intern=TRUE)
}
}
\references{
Thorson, J.T., Hicks, A.C., and Methot, R.D. 2014. Random
effect estimation of time-varying factors in Stock Synthesis. ICES J. Mar.
Sci.
}
\seealso{
\code{\link{read.admbFit}}, \code{\link{getADMBHessian}}
}
\author{
James Thorson
}
|
rm(list = ls())
library(tidyverse)
'%nin%' <- function(x,y)!('%in%'(x,y))
printf <- function(...) cat(sprintf(...))
rxn_md = read_csv("Recon2_export/rxn_md.csv")
central_carbon = rxn_md %>%
# turns out that some of the interesting glycolysis reactions (e.g., HEX1 = hexokinase) have confidence = 2
# filter(rxn_confidence %in% c("0", "4")) %>%
filter(str_detect(subsystem, "(Glycolysis|Citric acid cycle)")) %>%
arrange(rxn_code_nodirection) %>%
#manually exclude some uninteresting reactions
filter(!str_detect(rxn_code_nodirection, "^AL(C|D)D2")) %>%
filter(rxn_code_nodirection %nin% c("ETOHMO")) %>%
filter(!grepl("\\[(l|r|x|n|g|a)\\]", rxn_formula))
#unique just in case
writeLines(central_carbon$rxn_code_nodirection %>% unique(),
con = "Recon2_export/central_carbon_rxns.txt")
exchange_rxns = rxn_md %>%
#no need to include the DM_ reactions that have Exchange/demand as their subsystem,
#David didn't define them as exchange, it seems
filter(grepl("^EX_", rxn_code_nodirection)) #| (subsystem == "Exchange/demand reaction"))
writeLines(exchange_rxns$rxn_code_nodirection %>% unique(),
con = "Recon2_export/exchange_rxns.txt")
|
/compass/Resources/Recon2_export/define_reaction_subsets.R
|
permissive
|
merlinTFG/Compass
|
R
| false | false | 1,183 |
r
|
rm(list = ls())
library(tidyverse)
'%nin%' <- function(x,y)!('%in%'(x,y))
printf <- function(...) cat(sprintf(...))
rxn_md = read_csv("Recon2_export/rxn_md.csv")
central_carbon = rxn_md %>%
# turns out that some of the interesting glycolysis reactions (e.g., HEX1 = hexokinase) have confidence = 2
# filter(rxn_confidence %in% c("0", "4")) %>%
filter(str_detect(subsystem, "(Glycolysis|Citric acid cycle)")) %>%
arrange(rxn_code_nodirection) %>%
#manually exclude some uninteresting reactions
filter(!str_detect(rxn_code_nodirection, "^AL(C|D)D2")) %>%
filter(rxn_code_nodirection %nin% c("ETOHMO")) %>%
filter(!grepl("\\[(l|r|x|n|g|a)\\]", rxn_formula))
#unique just in case
writeLines(central_carbon$rxn_code_nodirection %>% unique(),
con = "Recon2_export/central_carbon_rxns.txt")
exchange_rxns = rxn_md %>%
#no need to include the DM_ reactions that have Exchange/demand as their subsystem,
#David didn't define them as exchange, it seems
filter(grepl("^EX_", rxn_code_nodirection)) #| (subsystem == "Exchange/demand reaction"))
writeLines(exchange_rxns$rxn_code_nodirection %>% unique(),
con = "Recon2_export/exchange_rxns.txt")
|
ui <- navbarPage(title = "test",
tabPanel("Scot Demo"))
server <- function(input, output, session) {
}
shinyApp(ui = ui, server = server)
|
/sg-training-r-project/app.R
|
no_license
|
Swirrl/sg-training-material
|
R
| false | false | 156 |
r
|
ui <- navbarPage(title = "test",
tabPanel("Scot Demo"))
server <- function(input, output, session) {
}
shinyApp(ui = ui, server = server)
|
##### Reason: combine the results for the variance explained by different factors for each gene
##### Author: Drew Neavin
##### Date: 14 March, 2022
##### Load in libraries #####
library(data.table)
library(tidyverse)
library(ggridges)
library(raincloudplots)
library(ggdist)
library(clusterProfiler)
library(org.Hs.eg.db)
library(GOSemSim)
library(RColorBrewer)
##### Set up directories #####
dir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/"
icc_dir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance_integratedSCT/gene_separated/icc/"
icc_dir2 <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance/gene_separated/icc/"
icc_interaction_dir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance_integratedSCT/gene_separated/icc_interaction/"
outdir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance_integratedSCT/combined/"
outdir_comparison <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/comparison/"
dir.create(outdir, recursive = TRUE)
dir.create(outdir_comparison, recursive = TRUE)
vars <- c("Line", "Passage", "Line:Passage", "Residual")
selected_vars <- c("Line", "Passage", "Line:Passage", "Residual")
var_colors <- c("#4734a9", "#78c0fe", "#97cf8a", "gray80")
names(var_colors) <- vars
var_colors <- var_colors[selected_vars]
##### Get list of icc files #####
icc_files <- list.files(icc_dir, pattern= ".rds")
# icc_files2 <- list.files(icc_dir2)
##### Read in icc results #####
icc_results_list <- lapply(icc_files, function(x){
readRDS(paste0(icc_dir,x))
})
names(icc_results_list) <- icc_files
# icc_results_list2 <- lapply(icc_files2, function(x){
# readRDS(paste0(icc_dir2,x))
# })
# names(icc_results_list2) <- icc_files2
##### Get list of icc interaction files #####
icc_interaction_files <- list.files(icc_interaction_dir, pattern = "_icc.rds")
##### Read in icc results #####
icc_interaction_results_list <- lapply(icc_interaction_files, function(x){
readRDS(paste0(icc_interaction_dir,x))
})
names(icc_interaction_results_list) <- icc_interaction_files
##### Merge icc results into a single data.table #####
icc_dt <- do.call(rbind, icc_results_list)
# icc_dt2 <- do.call(rbind, icc_results_list2)
# colnames(icc_dt2) <- paste0("integrate_sct_", colnames(icc_dt2))
# icc_dt_joined <- icc_dt[icc_dt2, on = c("grp" = "integrate_sct_grp", "gene" = "integrate_sct_gene")]
# icc_dt_joined$diff <- icc_dt_joined$percent - icc_dt_joined$integrate_sct_percent
# max(na.omit(icc_dt_joined$diff))
# icc_dt_joined[diff == max(na.omit(icc_dt_joined$diff))]
# icc_dt_joined[gene == "ENSG00000106153"]
# diff_dist <- ggplot(icc_dt_joined, aes(diff)) +
# geom_histogram() +
# facet_wrap(vars(grp))
# # theme_classic()
# ggsave(diff_dist, filename = paste0(outdir_comparison, "diff_histogram.png"))
# scatter <- ggplot(icc_dt_joined, aes(percent,integrate_sct_percent)) +
# geom_point() +
# facet_wrap(vars(grp), scales = "free") +
# theme_classic()
# ggsave(scatter, filename = paste0(outdir_comparison, "scatter_correlation.png"), height = 4.5)
# icc_dt_joined_long <- melt(icc_dt_joined, id.vars = c("grp", "gene"),measure.vars = c("percent", "integrate_sct_percent"))
# dist <- ggplot(icc_dt_joined_long, aes(value)) +
# geom_histogram() +
# facet_grid(grp ~ variable) +
# theme_classic()
# ggsave(dist, filename = paste0(outdir_comparison, "histogram.png"))
# ### want to use the integrate_sct_percent
# ### compared the two methods and appears that fitting when have been separately sct assessed => Line effect well correlated but time is much less (and not well correlated between the two methods) so likely inducing Time effects from normalizing all together
icc_dt$percent_round <- round(icc_dt$percent)
icc_dt$grp <- gsub("Time", "Passage", icc_dt$grp)
icc_dt$grp <- factor(icc_dt$grp, levels= rev(c("Line", "Passage", "Line:Passage", "Residual")))
group_size <- data.table(table(icc_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_dt <- group_size[icc_dt, on = "grp"]
icc_dt$grp_size <- factor(icc_dt$grp_size, levels = unique(group_size$grp_size))
##### Merge icc_interaction results into a single data.table #####
icc_interaction_dt <- do.call(rbind, icc_interaction_results_list)
icc_interaction_dt$percent_round <- round(icc_interaction_dt$percent)
icc_interaction_dt$grp <- gsub("Time", "Passage", icc_interaction_dt$grp)
icc_interaction_dt$grp <- factor(icc_interaction_dt$grp, levels= rev(c("Line", "Passage", "Line:Passage", "Residual")))
group_size <- data.table(table(icc_interaction_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_interaction_dt <- group_size[icc_interaction_dt, on = "grp"]
icc_interaction_dt$grp_size <- factor(icc_interaction_dt$grp_size, levels = unique(group_size$grp_size))
### *** Need to add individual effects without interaction in to interaction dt *** ###
icc_interaction_plus_dt <- rbind(icc_interaction_dt, icc_dt[!(gene %in% icc_interaction_dt$gene)])
group_size <- data.table(table(icc_interaction_plus_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_interaction_plus_dt <- group_size[icc_interaction_plus_dt, on = "grp"]
icc_interaction_plus_dt$grp_size <- factor(icc_interaction_plus_dt$grp_size, levels = unique(group_size$grp_size))
var_explained_manuscript <- icc_interaction_plus_dt[,c("grp", "percent", "P", "gene")]
colnames(var_explained_manuscript) <- c("Covariate", "Percent_Variance_Explained", "P", "ENSG")
##### Add gene IDs for easy identification downstream #####
GeneConversion1 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/DRENEA_1/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion2 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/Village_B_1_week/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion <- unique(rbind(GeneConversion1, GeneConversion2))
GeneConversion <- GeneConversion[!duplicated(GeneConversion$X1),]
GeneConversion$X3 <- NULL
colnames(GeneConversion) <- c("ENSG", "Gene_ID")
GeneConversion <- data.table(GeneConversion)
### Add the gene IDs to the icc_dt ###
var_explained_manuscript <- GeneConversion[var_explained_manuscript, on =c("ENSG")]
fwrite(var_explained_manuscript, paste0(outdir, "multi-passage_variance_explained_manuscript.tsv"), sep = "\t")
##### Check difference in percent explained with and without interactions #####
icc_interaction_dt_joined <- icc_dt[icc_interaction_dt, on = c("grp", "gene")]
icc_interaction_dt_joined$difference <- icc_interaction_dt_joined$percent - icc_interaction_dt_joined$i.percent
pRaincloud_dif <- ggplot(icc_interaction_dt_joined, aes(x = difference, y = factor(grp_size, levels = rev(levels(grp_size))), fill = factor(grp, levels = rev(selected_vars)))) +
geom_density_ridges(stat = "binline", bins = 90, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.03, 0)) +
scale_fill_manual(values = var_colors)
ggsave(pRaincloud_dif, filename = paste0(outdir, "variance_explained_interaction_difference_raincloud.png"), height = 8, width = 7)
ggsave(pRaincloud_dif, filename = paste0(outdir, "variance_explained_interaction_difference_raincloud.pdf"), height = 8, width = 7)
##### Make a figure of stacked variance explained #####
### Order based on line variance explained ###
genes_list <- list()
for (group in c("Line", "Passage", "Line:Passage", "Residual")){
genes_list[[group]] <- icc_dt[grp == group][rev(order(percent_round))]$gene
}
genes <- unique(unlist(genes_list))
icc_dt$gene <- factor(icc_dt$gene, levels = genes)
icc_dt$grp <- factor(icc_dt$grp, levels= rev(c("Line", "Passage", "Line:Passage", "Residual")))
## First on line percent, then village percent ##
bar_proportions <- ggplot(icc_dt, aes(x = gene, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity") +
theme_classic() +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
scale_fill_manual(values = var_colors)
ggsave(bar_proportions, filename = paste0(outdir, "variance_explained_bar.png"), width = 20)
### Try boxplot ###
boxplot <- ggplot(icc_dt, aes(x = factor(grp, levels = rev(levels(grp))), y = percent, fill = factor(grp, levels = rev(levels(grp))), color = factor(grp, levels = rev(levels(grp))))) +
geom_boxplot(alpha = 0.5, size = 0.5) +
theme_classic() +
xlab("Covariate") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
legend.position="none") +
scale_fill_manual(values = var_colors) +
scale_color_manual(values = var_colors)
ggsave(boxplot, filename = paste0(outdir, "variance_explained_box.png"), height = 3, width = 2)
### Try ridgplots ###
pRidges <- ggplot(icc_dt[grp != "Residual"], aes(x = percent, y = factor(grp, levels = rev(levels(grp))), fill = factor(grp, levels = rev(levels(grp))))) +
geom_density_ridges(stat = "binline", bins = 200, scale = 0.95, draw_baseline = FALSE) +
# geom_density_ridges() +
theme_classic()
ggsave(pRidges, filename = paste0(outdir, "variance_explained_ridge.png"), height = 8, width = 10)
### Try ridgplots ###
pRidges_pop <- ggplot(icc_dt[grp != "Residual"][percent > 10], aes(x = percent, y = factor(grp, levels = rev(levels(grp))), fill = factor(grp, levels = rev(levels(grp))))) +
geom_density_ridges(stat = "binline", bins = 180, scale = 0.95, draw_baseline = FALSE) +
# geom_density_ridges() +
theme_classic()
ggsave(pRidges_pop, filename = paste0(outdir, "variance_explained_ridge_pop.png"), height = 8, width = 10)
# pRaincloud <- ggplot(icc_dt, aes(x = percent, y = factor(grp_size, levels = rev(levels(grp_size))), fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(stat = "binline", bins = 90, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
# geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors)
pRaincloud <- ggplot(icc_dt, aes(x = percent, y = factor(grp_size, levels = rev(levels(grp_size))), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.1, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud, filename = paste0(outdir, "variance_explained_raincloud.png"), height = 2, width = 5)
ggsave(pRaincloud, filename = paste0(outdir, "variance_explained_raincloud.pdf"), height = 2, width = 5)
icc_interaction_plus_dt$grp_size <- factor(icc_interaction_plus_dt$grp_size, levels = c("Line\nN = 12076", "Passage\nN = 3620", "Line:Passage\nN = 2033", "Residual\nN = 12076"))
# pRaincloud_interaction <- ggplot(icc_interaction_plus_dt, aes(x = percent, y = grp_size, fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(size = 0.1, stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity.., fill = factor(grp, levels = rev(vars))), alpha = 0.75) +
# geom_boxplot(outlier.shape=20, size = 0.1,width = .15, outlier.size = 0.01, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors) +
# scale_color_manual(values = var_colors) +
# geom_vline(xintercept = 1,color = "grey70", size = 0.4, lty="11")
pRaincloud_interaction <- ggplot(icc_interaction_plus_dt, aes(x = percent, y = factor(grp_size, levels = levels(grp_size)), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.1, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud_interaction, filename = paste0(outdir, "variance_explained_raincloud_interaction.png"), height = 2, width = 4)
ggsave(pRaincloud_interaction, filename = paste0(outdir, "variance_explained_raincloud_interaction.pdf"), height = 2, width = 4)
icc_interaction_sig_list <- list()
for (ensg in unique(icc_interaction_plus_dt$gene)){
icc_interaction_sig_list[[ensg]] <- icc_interaction_plus_dt[gene == ensg][P < 0.05/(nrow(icc_interaction_plus_dt[gene == ensg])-1)]
icc_interaction_sig_list[[ensg]] <- rbind(icc_interaction_sig_list[[ensg]], icc_interaction_plus_dt[gene == ensg & grp == "Residual"])
}
icc_interaction_sig_dt <- do.call(rbind, icc_interaction_sig_list)
group_size <- data.table(table(icc_interaction_sig_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_interaction_sig_dt <- group_size[icc_interaction_sig_dt, on = "grp"]
icc_interaction_sig_dt$grp_size <- factor(icc_interaction_sig_dt$grp_size, levels = unique(group_size$grp_size))
grp_size_order <- c("Line\nN = 12076", "Passage\nN = 3620", "Line:Passage\nN = 2033", "Residual\nN = 12076")
mean(icc_interaction_sig_dt[grp == "Line"]$percent)
mean(icc_interaction_sig_dt[grp == "Passage"]$percent)
mean(icc_interaction_sig_dt[grp == "Line:Passage"]$percent)
mean(icc_interaction_sig_dt[grp == "Line" & percent > 1]$percent)
mean(icc_interaction_sig_dt[grp == "Passage" & percent > 1]$percent)
mean(icc_interaction_sig_dt[grp == "Line:Passage" & percent > 1]$percent)
# pRaincloud_interaction_sig <- ggplot(icc_interaction_sig_dt, aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
# geom_boxplot(size = 0.5,width = .15, outlier.size = 0.15, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors) +
# geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
pRaincloud_interaction_sig <- ggplot(icc_interaction_sig_dt, aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.07, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud_interaction_sig, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant.png"), height = 2, width = 4)
ggsave(pRaincloud_interaction_sig, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant.pdf"), height = 2, width = 4)
total <- icc_interaction_sig_dt[,.(count = .N), by = .(grp)]
total_less1pct <- icc_interaction_sig_dt[percent <= 1][,.(count_less_1pct = .N), by = .(grp)]
total_less5pct <- icc_interaction_sig_dt[percent <= 5][,.(count_less_5pct = .N), by = .(grp)]
total_less10pct <- icc_interaction_sig_dt[percent <= 10][,.(count_less_10pct = .N), by = .(grp)]
summary <- total[total_less1pct, on = "grp"]
summary <- summary[total_less5pct, on = "grp"]
summary <- summary[total_less10pct, on = "grp"]
summary$count_greater_1pct <- summary$count - summary$count_less_1pct
summary$count_greater_5pct <- summary$count - summary$count_less_5pct
summary$count_greater_10pct <- summary$count - summary$count_less_10pct
summary$percent_1pct <- (summary$count_less_1pct/summary$count)*100
summary$percent_5pct <- (summary$count_less_5pct/summary$count)*100
summary$percent_10pct <- (summary$count_less_10pct/summary$count)*100
# pRaincloud_interaction_sig_1pct <- ggplot(icc_interaction_sig_dt[percent >= 1], aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(stat = "binline", bins = 90, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
# geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors) +
# geom_vline(xintercept = 1, linetype = "dashed", color = "firebrick3")
pRaincloud_interaction_sig_1pct <- ggplot(icc_interaction_sig_dt[percent >= 1], aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.07, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud_interaction_sig_1pct, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_1pct.png"), height = 2, width = 4)
ggsave(pRaincloud_interaction_sig_1pct, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_1pct.pdf"), height = 2, width = 4)
##### Pull just the significant variances genome-wide #####
icc_interaction_plus_dt$fdr <- p.adjust(icc_interaction_plus_dt$P, method="fdr")
icc_interaction_sig_gw_dt <- icc_interaction_plus_dt[fdr < 0.05 | is.na(fdr)]
group_size_sig_gw <- data.table(table(icc_interaction_sig_gw_dt$grp))
colnames(group_size_sig_gw) <- c("grp", "size")
group_size_sig_gw$grp_size <- paste0(group_size_sig_gw$grp, "\nN = ", formatC(group_size_sig_gw$size, format="d", big.mark=","))
icc_interaction_sig_gw_dt <- group_size_sig_gw[icc_interaction_sig_gw_dt, on = "grp"]
icc_interaction_sig_gw_dt$grp_size <- factor(icc_interaction_sig_gw_dt$grp_size, levels = unique(group_size_sig_gw$grp_size))
group_size_sig_gw_order <- c("Line\nN = 750", "Passage\nN = 750", "Line:Passage\nN = 619", "Residual\nN = 750")
pRaincloud_interaction_sig_gw <- ggplot(icc_interaction_sig_gw_dt, aes(x = percent, y = factor(grp_size, levels = group_size_sig_gw_order), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.03, 0)) +
scale_fill_manual(values = var_colors) +
geom_vline(xintercept = 1, linetype = "dashed", color = "firebrick3") +
labs(fill="Covariate")
ggsave(pRaincloud_interaction_sig_gw, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_genome_wide.png"), height = 8, width = 7)
ggsave(pRaincloud_interaction_sig_gw, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_genome_wide.pdf"), height = 8, width = 7)
icc_interaction_sig_dt[gene == "ENSG00000106153"]
icc_dt[gene == "ENSG00000106153"]
icc_interaction_plus_dt[gene == "ENSG00000106153"]
icc_interaction_sig_gw_dt[gene == "ENSG00000106153"]
icc_interaction_sig_gw_dt2[gene == "ENSG00000106153"]
##### Add gene IDs for easy identification downstream #####
GeneConversion1 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/DRENEA_1/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion2 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/Village_B_1_week/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion <- unique(rbind(GeneConversion1, GeneConversion2))
GeneConversion <- GeneConversion[!duplicated(GeneConversion$X1),]
GeneConversion$X3 <- NULL
colnames(GeneConversion) <- c("gene", "Gene_ID")
GeneConversion <- data.table(GeneConversion)
### Add the gene IDs to the icc_dt ###
icc_interaction_sig_gw_dt <- GeneConversion[icc_interaction_sig_gw_dt, on = "gene"]
icc_interaction_sig_gw_dt[grp == "Cryopreserved"& percent_round > 1][rev(order(percent))]$Gene_ID
head(icc_interaction_sig_gw_dt[grp == "Cryopreserved" & percent_round > 1][rev(order(percent))][,c("Gene_ID", "percent_round")], n = 50)
icc_interaction_sig_gw_dt[grp == "Line"][rev(order(percent))]$Gene_ID
head(icc_interaction_sig_gw_dt[grp == "Line" & percent_round > 1][rev(order(percent))][,c("Gene_ID", "percent_round")], n = 50)
icc_interaction_sig_gw_dt[grp == "Village"][rev(order(percent))]$Gene_ID
head(icc_interaction_sig_gw_dt[grp == "Village" & percent_round > 1][rev(order(percent))][,c("Gene_ID", "percent_round")], n = 50)
fwrite(icc_interaction_sig_gw_dt, paste0(outdir, "sig_results.tsv.gz"), sep = "\t", compress = "gzip")
## Highlight
## X chromosome genes - wouldn't expect these to be Line-biased because expressed by both males and females
## Y chromosome genes - should be line-biased because expressed by only males and have some male(s) and some female(s)
## mt genes
## ribosomal genes
## look at gsea and kegg pathways for each
## Read in gtf used as reference and pull just X, Y or MT chromosome genes from it, use ribosomal file for rb genes
gtf <- fread("/directflow/GWCCGPipeline/projects/reference/refdata-cellranger-GRCh38-3.0.0/genes/genes.gtf", sep = "\t", autostart = 6, header = FALSE)
gtf_genes <- gtf[!(grep("transcript_id", V9))]
gtf_genes$V9 <- gsub("gene_id \"", "",gtf_genes$V9 ) %>%
gsub("\"; gene_version \"", ";", .) %>%
gsub("\"; gene_name \"", ";", .) %>%
gsub("\"; gene_source \"", ";", .) %>%
gsub("\"; gene_biotype \"", ";", .) %>%
gsub("\"", "", .)
gtf_genes[, c("gene_id", "gene_version", "gene_name", "gene_source", "gene_biotype") := data.table(str_split_fixed(V9,";", 5))]
icc_interaction_plus_dt <- GeneConversion[icc_interaction_plus_dt, on = "gene"]
X_chromosome_genes <- gtf_genes[V1 == "X"]
X_genelist <- X_chromosome_genes$gene_id[X_chromosome_genes$gene_id %in% genes]
Y_chromosome_genes <- gtf_genes[V1 == "Y"]
Y_genelist <- Y_chromosome_genes$gene_id[Y_chromosome_genes$gene_id %in% genes]
MT_chromosome_genes <- gtf_genes[V1 == "MT"]
MT_genelist <- MT_chromosome_genes$gene_id[MT_chromosome_genes$gene_id %in% genes]
RbGeneList <- read.delim(file = "/directflow/SCCGGroupShare/projects/DrewNeavin/References/RibosomalGeneList_GeneID_ENSG.txt")
Rb_genelist <- RbGeneList$ENSG[RbGeneList$ENSG %in% genes]
### Make stacked bar plots of the variance explained by different factors for these gene groups
## Figure of x chromosome genes ##
icc_x <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% X_genelist][order(percent_round)]$gene), on = "gene"]
icc_x$grp <- factor(icc_x$grp, levels = rev(selected_vars))
icc_x$gene <- factor(icc_x$gene, levels = unique(icc_x$gene))
bar_proportions_x <- ggplot(icc_x, aes(x = gene, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = var_colors) +
ggtitle("Variance Explained of\nX Chromosome Genes")
ggsave(bar_proportions_x, filename = paste0(outdir, "variance_explained_bar_x_genes.png"), width = 20)
## Figure of y chromosome genes ##
icc_y <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% Y_genelist][order(percent_round)]$gene), on = "gene"]
icc_y$grp <- factor(icc_y$grp, levels = rev(selected_vars))
icc_y$gene <- factor(icc_y$gene, levels = unique(icc_y$gene))
icc_y$Gene_ID <- factor(icc_y$Gene_ID, levels = unique(icc_y$Gene_ID))
bar_proportions_y <- ggplot(icc_y, aes(x = Gene_ID, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
# axis.text.x=element_blank(),
# axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
scale_fill_manual(values = var_colors) +
scale_y_continuous(expand = c(0, 0)) +
ggtitle("Variance Explained of\nY Chromosome Genes") +
ylab("Percent")
ggsave(bar_proportions_y, filename = paste0(outdir, "variance_explained_bar_y_genes.png"), width = 4.5, height = 4.5)
ggsave(bar_proportions_y, filename = paste0(outdir, "variance_explained_bar_y_genes.pdf"), width = 4.5, height = 4.5)
## Figure of mt chromosome genes ##
icc_mt <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% MT_genelist][order(percent_round)]$gene), on = "gene"]
icc_mt$grp <- factor(icc_mt$grp, levels = rev(selected_vars))
icc_mt$gene <- factor(icc_mt$gene, levels = unique(icc_mt$gene))
icc_mt$Gene_ID <- factor(icc_mt$Gene_ID, levels = unique(icc_mt$Gene_ID))
bar_proportions_mt <- ggplot(icc_mt, aes(x = Gene_ID, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
# axis.text.x=element_blank(),
# axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
scale_fill_manual(values = var_colors) +
scale_y_continuous(expand = c(0, 0)) +
ggtitle("Variance Explained of\nMitochondrial Genes") +
ylab("Percent")
ggsave(bar_proportions_mt, filename = paste0(outdir, "variance_explained_bar_mt_genes.png"), width = 4.5, height = 4.5)
ggsave(bar_proportions_mt, filename = paste0(outdir, "variance_explained_bar_mt_genes.pdf"), width = 4.5, height = 4.5)
## Figure of mt chromosome genes ##
icc_rb <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% Rb_genelist][order(percent_round)]$gene), on = "gene"]
icc_rb$grp <- factor(icc_rb$grp, levels = rev(selected_vars))
icc_rb$gene <- factor(icc_rb$gene, levels = unique(icc_rb$gene))
bar_proportions_rb <- ggplot(icc_rb, aes(x = gene, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = var_colors) +
scale_y_continuous(expand = c(0, 0)) +
ggtitle("Variance Explained\nof Ribosomal Genes")
ggsave(bar_proportions_rb, filename = paste0(outdir, "variance_explained_bar_rb_genes.png"), width = 10, height = 4)
ggsave(bar_proportions_rb, filename = paste0(outdir, "variance_explained_bar_rb_genes.pdf"), width = 10, height = 4)
### Plot Pluripotency Genes ###
pluri_genes <- fread(paste0(dir,"data/pluripotency_genes.tsv"), sep = "\t", col.names = "Gene_ID", header = FALSE)
pluri_genes <- GeneConversion[pluri_genes, on = "Gene_ID"]
icc_dt_pluri_genes <- icc_interaction_plus_dt[pluri_genes,on = c("gene")]
icc_dt_pluri_genes$grp <- factor(icc_dt_pluri_genes$grp, levels = rev(selected_vars))
icc_dt_pluri_genes <- icc_dt_pluri_genes[data.table(gene = icc_dt_pluri_genes[grp == "Residual"][order(percent)]$gene), on = "gene"]
icc_dt_pluri_genes$Gene_ID <- factor(icc_dt_pluri_genes$Gene_ID, levels = unique(icc_dt_pluri_genes$Gene_ID))
pPluri_Genes_Cont <- ggplot() +
geom_bar(data = icc_dt_pluri_genes, aes(Gene_ID, percent, fill = grp), position = "stack", stat = "identity", alpha = 0.75) +
theme_classic() +
# facet_wrap(Gene_ID ~ ., nrow = 3) +
scale_fill_manual(values = var_colors) +
theme(plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
ylab("Percent Gene Expression Variance Explained") +
ggtitle("Variance Explained of\nPluripotency Genes") +
theme(axis.title.x=element_blank())
ggsave(pPluri_Genes_Cont, filename = paste0(outdir, "Pluripotent_Gene_Variable_Contributions.png"), width = 6, height = 4.5)
ggsave(pPluri_Genes_Cont, filename = paste0(outdir, "Pluripotent_Gene_Variable_Contributions.pdf"), width = 6, height = 4.5)
##### check for variance explained for eQTL genes (from Kilpinen et al) that are #####
eqtls <- fread("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/eQTL_check/KilpinenOverlap/gene_snp_list.tsv", sep = "\t")
eqtls_icc <- icc_interaction_plus_dt[unique(eqtls[,"gene"]), on = "gene"]
eqtls_icc$grp <- factor(eqtls_icc$grp, levels = rev(vars))
eqtls_icc <- eqtls_icc[data.table(gene = eqtls_icc[grp == "Residual"][order(percent)]$gene), on = "gene"]
eqtls_icc$Gene_ID <- factor(eqtls_icc$Gene_ID, levels = unique(eqtls_icc$Gene_ID))
group_size_eqtl <- data.table(table(eqtls_icc$grp))
colnames(group_size_eqtl) <- c("grp", "size")
group_size_eqtl$grp_size <- paste0(group_size_eqtl$grp, "\nN = ", group_size_eqtl$size)
eqtls_icc <- group_size_eqtl[eqtls_icc, on = "grp"]
grp_size_order_eqtl <- c("Line\nN = 2371", "Village\nN = 1836", "Site\nN = 2461", "Replicate\nN = 869", "Line:Village\nN = 367", "Line:Site\nN = 911", "Village:Site\nN = 898","Replicate:Village\nN = 305", "Replicate:Line\nN = 25", "Replicate:Site\nN = 78", "Residual\nN = 2542")
eqtls_icc$grp_size <- factor(eqtls_icc$grp_size, levels = grp_size_order_eqtl)
eqtls_icc_1pct <- eqtls_icc
for (ensg in unique(eqtls_icc$gene)){
if (!any(eqtls_icc[gene == ensg & grp != "Residual"]$percent > 1)){
eqtls_icc_1pct <- eqtls_icc_1pct[gene != ensg]
}
}
eqtls_icc_1pct_grouped_list <- list()
for (ensg in unique(eqtls_icc_1pct$gene)){
group <- eqtls_icc_1pct[gene == ensg & grp != "Residual"][which.max(percent)]$grp
eqtls_icc_1pct_grouped_list[[group]][[ensg]] <- eqtls_icc_1pct[gene == ensg]
}
eqtls_icc_1pct_grouped <- lapply(eqtls_icc_1pct_grouped_list, function(x) do.call(rbind, x))
eqtls_icc_1pct_grouped <- lapply(names(eqtls_icc_1pct_grouped), function(x){
eqtls_icc_1pct_grouped[[x]]$largest_contributor <- x
return(eqtls_icc_1pct_grouped[[x]])
})
eqtls_icc_1pct_grouped_dt <- do.call(rbind, eqtls_icc_1pct_grouped)
eqtls_icc_1pct_grouped_dt$largest_contributor <- factor(eqtls_icc_1pct_grouped_dt$largest_contributor, levels = c("Line", "Village", "Site", "Line:Village", "Line:Site", "Village:Site", "Replicate:Village"))
pPluri_Genes_largest_Cont_eqtl <- ggplot() +
geom_bar(data = eqtls_icc_1pct_grouped_dt, aes(Gene_ID, percent, fill = factor(grp, levels = rev(vars))), position = "stack", stat = "identity", alpha = 0.75) +
theme_classic() +
facet_grid(. ~ largest_contributor, scales = "free_x", space = "free_x") +
scale_fill_manual(values = var_colors) +
ylab("Percent Gene Expression Variance Explained") +
theme(axis.title.x=element_blank(),
axis.text.x = element_blank(),
panel.spacing.x=unit(0, "lines"),
axis.ticks.x = element_blank()) +
geom_hline(yintercept = 1, linetype = "dashed")
# scale_y_discrete(expand = c(0.03, 0))
# scale_x_discrete(expand = c(0.03, 0))
ggsave(pPluri_Genes_largest_Cont_eqtl, filename = paste0(outdir, "eQTL_Genes_Variance_Contributions_1pct_largest_cont.png"), width = 10, height = 4)
ggsave(pPluri_Genes_largest_Cont_eqtl, filename = paste0(outdir, "eQTL_Genes_Variance_Contributions_1pct_largest_cont.pdf"), width = 10, height = 4)
# ### Count number of each chromosome/gene category type
# ### numbers are the numbers of that category that where a significant percent of variance is explained by this variable
# ### percent of that category that where a significant percent of variance is explained by this variable
# x_number <- lapply(genes_list, function(x){
# length(which(x %in% X_chromosome_genes$gene_id))
# })
# x_percent <- lapply(genes_list, function(x){
# length(which(x %in% X_chromosome_genes$gene_id))/length(X_chromosome_genes$gene_id)
# })
# y_number <- lapply(genes_list, function(x){
# length(which(x %in% Y_chromosome_genes$gene_id))
# })
# y_percent <- lapply(genes_list, function(x){
# length(which(x %in% Y_chromosome_genes$gene_id))/length(Y_chromosome_genes$gene_id)
# })
# mt_number <- lapply(genes_list, function(x){
# length(which(x %in% MT_chromosome_genes$gene_id))
# })
# mt_percent <- lapply(genes_list, function(x){
# length(which(x %in% MT_chromosome_genes$gene_id))/length(MT_chromosome_genes$gene_id)
# })
# rb_number <- lapply(genes_list, function(x){
# length(which(x %in% RbGeneList$ENSG))
# })
# rb_percent <- lapply(genes_list, function(x){
# length(which(x %in% RbGeneList$ENSG))/length(RbGeneList$ENSG)
# })
# ### for > 1% var explained
# ### Count number of each chromosome/gene category type
# x_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% X_chromosome_genes$gene_id))
# })
# names(x_number_1) <- vars
# x_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% X_chromosome_genes$gene_id))/length(X_chromosome_genes$gene_id)
# })
# names(x_percent_1) <- vars
# y_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% Y_chromosome_genes$gene_id))
# })
# names(y_number_1) <- vars
# y_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% Y_chromosome_genes$gene_id))/length(Y_chromosome_genes$gene_id)
# })
# names(y_percent_1) <- vars
# mt_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% MT_chromosome_genes$gene_id))
# })
# names(mt_number_1) <- vars
# mt_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% MT_chromosome_genes$gene_id))/length( MT_chromosome_genes$gene_id)
# })
# names(mt_percent_1) <- vars
# rb_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% RbGeneList$ENSG))
# })
# names(rb_number_1) <- vars
# rb_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% RbGeneList$ENSG))/length(RbGeneList$ENSG)
# })
# names(rb_percent_1) <- vars
### Pathway analysis ###
geneList <- lapply(genes_list, function(x){
tmp <- bitr(x, fromType = "ENSEMBL",
toType = c("ENTREZID"),
OrgDb = org.Hs.eg.db)$ENTREZID
tmp[!is.na(tmp)]
})
gg <- list()
kk <- list()
df = as.data.frame(org.Hs.egGO)
go_gene_list = unique(sort(df$gene_id))
dfk = as.data.frame(org.Hs.egPATH)
kegg_gene_list = unique(sort(dfk$gene_id))
for (group in c("Line", "Village", "Cryopreserved", "Replicate","Line:Village", "Line:Cryopreserved", "Village:Cryopreserved", "Replicate:Village", "Replicate:Line", "Replicate:Cryopreserved", "Residual")){
kk[[group]] <- enrichKEGG(gene = geneList[[group]],
universe = geneList[[group]],
organism = 'hsa',
pvalueCutoff = 0.05,
keyType = 'ncbi-geneid')
gg[[group]] <- groupGO(gene = geneList[[group]],
OrgDb = org.Hs.eg.db,
readable = TRUE)
}
hsGO <- godata('org.Hs.eg.db', ont="MF")
sim_results <- list()
vars <- c("Line", "Village", "Cryopreserved", "Replicate","Village:Line", "Line:Cryopreserved", "Village:Cryopreserved", "Replicate:Village", "Replicate:Line", "Replicate:Cryopreserved")
for (group1 in vars){
print(group1)
for (group2 in vars[(grep(paste0("^",group1, "$"), vars) + 1): length(vars)]){
print(group2)
sim_results[[group1]][[group2]] <- clusterSim(geneList[[group1]], geneList[[group2]], semData=hsGO, measure="Wang", combine="BMA")
}
}
# genes2rerun <- c(character())
# for (g in unique(icc_dt$gene)){
# print(g)
# genes2rerun <- c(genes2rerun, as.character(unique(icc_dt[gene == g][P > 0.05/(nrow(icc_dt[gene == g])-1)]$gene)))
# }
# for (gene in genes2rerun){
# print(gene)
# # unlink(paste0(icc_dir,gene,"_icc.rds"))
# print(file.exists(paste0(icc_dir,gene,"_icc.rds")))
# unlink(paste0("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/variance_partition_post_review/gene_separated/fit_models/",gene,"_fitted_models.rds"))
# unlink(paste0("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/variance_partition_post_review/gene_separated/residuals4qtl/",gene,"_residuals4qtl.rds"))
# }
|
/multi-passage/Variance/variance_partition_multipassage_combine.R
|
no_license
|
powellgenomicslab/iPSC_Village_scripts
|
R
| false | false | 41,664 |
r
|
##### Reason: combine the results for the variance explained by different factors for each gene
##### Author: Drew Neavin
##### Date: 14 March, 2022
##### Load in libraries #####
library(data.table)
library(tidyverse)
library(ggridges)
library(raincloudplots)
library(ggdist)
library(clusterProfiler)
library(org.Hs.eg.db)
library(GOSemSim)
library(RColorBrewer)
##### Set up directories #####
dir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/"
icc_dir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance_integratedSCT/gene_separated/icc/"
icc_dir2 <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance/gene_separated/icc/"
icc_interaction_dir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance_integratedSCT/gene_separated/icc_interaction/"
outdir <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/variance_integratedSCT/combined/"
outdir_comparison <- "/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/multi-passage/Variance/comparison/"
dir.create(outdir, recursive = TRUE)
dir.create(outdir_comparison, recursive = TRUE)
vars <- c("Line", "Passage", "Line:Passage", "Residual")
selected_vars <- c("Line", "Passage", "Line:Passage", "Residual")
var_colors <- c("#4734a9", "#78c0fe", "#97cf8a", "gray80")
names(var_colors) <- vars
var_colors <- var_colors[selected_vars]
##### Get list of icc files #####
icc_files <- list.files(icc_dir, pattern= ".rds")
# icc_files2 <- list.files(icc_dir2)
##### Read in icc results #####
icc_results_list <- lapply(icc_files, function(x){
readRDS(paste0(icc_dir,x))
})
names(icc_results_list) <- icc_files
# icc_results_list2 <- lapply(icc_files2, function(x){
# readRDS(paste0(icc_dir2,x))
# })
# names(icc_results_list2) <- icc_files2
##### Get list of icc interaction files #####
icc_interaction_files <- list.files(icc_interaction_dir, pattern = "_icc.rds")
##### Read in icc results #####
icc_interaction_results_list <- lapply(icc_interaction_files, function(x){
readRDS(paste0(icc_interaction_dir,x))
})
names(icc_interaction_results_list) <- icc_interaction_files
##### Merge icc results into a single data.table #####
icc_dt <- do.call(rbind, icc_results_list)
# icc_dt2 <- do.call(rbind, icc_results_list2)
# colnames(icc_dt2) <- paste0("integrate_sct_", colnames(icc_dt2))
# icc_dt_joined <- icc_dt[icc_dt2, on = c("grp" = "integrate_sct_grp", "gene" = "integrate_sct_gene")]
# icc_dt_joined$diff <- icc_dt_joined$percent - icc_dt_joined$integrate_sct_percent
# max(na.omit(icc_dt_joined$diff))
# icc_dt_joined[diff == max(na.omit(icc_dt_joined$diff))]
# icc_dt_joined[gene == "ENSG00000106153"]
# diff_dist <- ggplot(icc_dt_joined, aes(diff)) +
# geom_histogram() +
# facet_wrap(vars(grp))
# # theme_classic()
# ggsave(diff_dist, filename = paste0(outdir_comparison, "diff_histogram.png"))
# scatter <- ggplot(icc_dt_joined, aes(percent,integrate_sct_percent)) +
# geom_point() +
# facet_wrap(vars(grp), scales = "free") +
# theme_classic()
# ggsave(scatter, filename = paste0(outdir_comparison, "scatter_correlation.png"), height = 4.5)
# icc_dt_joined_long <- melt(icc_dt_joined, id.vars = c("grp", "gene"),measure.vars = c("percent", "integrate_sct_percent"))
# dist <- ggplot(icc_dt_joined_long, aes(value)) +
# geom_histogram() +
# facet_grid(grp ~ variable) +
# theme_classic()
# ggsave(dist, filename = paste0(outdir_comparison, "histogram.png"))
# ### want to use the integrate_sct_percent
# ### compared the two methods and appears that fitting when have been separately sct assessed => Line effect well correlated but time is much less (and not well correlated between the two methods) so likely inducing Time effects from normalizing all together
icc_dt$percent_round <- round(icc_dt$percent)
icc_dt$grp <- gsub("Time", "Passage", icc_dt$grp)
icc_dt$grp <- factor(icc_dt$grp, levels= rev(c("Line", "Passage", "Line:Passage", "Residual")))
group_size <- data.table(table(icc_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_dt <- group_size[icc_dt, on = "grp"]
icc_dt$grp_size <- factor(icc_dt$grp_size, levels = unique(group_size$grp_size))
##### Merge icc_interaction results into a single data.table #####
icc_interaction_dt <- do.call(rbind, icc_interaction_results_list)
icc_interaction_dt$percent_round <- round(icc_interaction_dt$percent)
icc_interaction_dt$grp <- gsub("Time", "Passage", icc_interaction_dt$grp)
icc_interaction_dt$grp <- factor(icc_interaction_dt$grp, levels= rev(c("Line", "Passage", "Line:Passage", "Residual")))
group_size <- data.table(table(icc_interaction_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_interaction_dt <- group_size[icc_interaction_dt, on = "grp"]
icc_interaction_dt$grp_size <- factor(icc_interaction_dt$grp_size, levels = unique(group_size$grp_size))
### *** Need to add individual effects without interaction in to interaction dt *** ###
icc_interaction_plus_dt <- rbind(icc_interaction_dt, icc_dt[!(gene %in% icc_interaction_dt$gene)])
group_size <- data.table(table(icc_interaction_plus_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_interaction_plus_dt <- group_size[icc_interaction_plus_dt, on = "grp"]
icc_interaction_plus_dt$grp_size <- factor(icc_interaction_plus_dt$grp_size, levels = unique(group_size$grp_size))
var_explained_manuscript <- icc_interaction_plus_dt[,c("grp", "percent", "P", "gene")]
colnames(var_explained_manuscript) <- c("Covariate", "Percent_Variance_Explained", "P", "ENSG")
##### Add gene IDs for easy identification downstream #####
GeneConversion1 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/DRENEA_1/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion2 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/Village_B_1_week/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion <- unique(rbind(GeneConversion1, GeneConversion2))
GeneConversion <- GeneConversion[!duplicated(GeneConversion$X1),]
GeneConversion$X3 <- NULL
colnames(GeneConversion) <- c("ENSG", "Gene_ID")
GeneConversion <- data.table(GeneConversion)
### Add the gene IDs to the icc_dt ###
var_explained_manuscript <- GeneConversion[var_explained_manuscript, on =c("ENSG")]
fwrite(var_explained_manuscript, paste0(outdir, "multi-passage_variance_explained_manuscript.tsv"), sep = "\t")
##### Check difference in percent explained with and without interactions #####
icc_interaction_dt_joined <- icc_dt[icc_interaction_dt, on = c("grp", "gene")]
icc_interaction_dt_joined$difference <- icc_interaction_dt_joined$percent - icc_interaction_dt_joined$i.percent
pRaincloud_dif <- ggplot(icc_interaction_dt_joined, aes(x = difference, y = factor(grp_size, levels = rev(levels(grp_size))), fill = factor(grp, levels = rev(selected_vars)))) +
geom_density_ridges(stat = "binline", bins = 90, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.03, 0)) +
scale_fill_manual(values = var_colors)
ggsave(pRaincloud_dif, filename = paste0(outdir, "variance_explained_interaction_difference_raincloud.png"), height = 8, width = 7)
ggsave(pRaincloud_dif, filename = paste0(outdir, "variance_explained_interaction_difference_raincloud.pdf"), height = 8, width = 7)
##### Make a figure of stacked variance explained #####
### Order based on line variance explained ###
genes_list <- list()
for (group in c("Line", "Passage", "Line:Passage", "Residual")){
genes_list[[group]] <- icc_dt[grp == group][rev(order(percent_round))]$gene
}
genes <- unique(unlist(genes_list))
icc_dt$gene <- factor(icc_dt$gene, levels = genes)
icc_dt$grp <- factor(icc_dt$grp, levels= rev(c("Line", "Passage", "Line:Passage", "Residual")))
## First on line percent, then village percent ##
bar_proportions <- ggplot(icc_dt, aes(x = gene, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity") +
theme_classic() +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
scale_fill_manual(values = var_colors)
ggsave(bar_proportions, filename = paste0(outdir, "variance_explained_bar.png"), width = 20)
### Try boxplot ###
boxplot <- ggplot(icc_dt, aes(x = factor(grp, levels = rev(levels(grp))), y = percent, fill = factor(grp, levels = rev(levels(grp))), color = factor(grp, levels = rev(levels(grp))))) +
geom_boxplot(alpha = 0.5, size = 0.5) +
theme_classic() +
xlab("Covariate") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
legend.position="none") +
scale_fill_manual(values = var_colors) +
scale_color_manual(values = var_colors)
ggsave(boxplot, filename = paste0(outdir, "variance_explained_box.png"), height = 3, width = 2)
### Try ridgplots ###
pRidges <- ggplot(icc_dt[grp != "Residual"], aes(x = percent, y = factor(grp, levels = rev(levels(grp))), fill = factor(grp, levels = rev(levels(grp))))) +
geom_density_ridges(stat = "binline", bins = 200, scale = 0.95, draw_baseline = FALSE) +
# geom_density_ridges() +
theme_classic()
ggsave(pRidges, filename = paste0(outdir, "variance_explained_ridge.png"), height = 8, width = 10)
### Try ridgplots ###
pRidges_pop <- ggplot(icc_dt[grp != "Residual"][percent > 10], aes(x = percent, y = factor(grp, levels = rev(levels(grp))), fill = factor(grp, levels = rev(levels(grp))))) +
geom_density_ridges(stat = "binline", bins = 180, scale = 0.95, draw_baseline = FALSE) +
# geom_density_ridges() +
theme_classic()
ggsave(pRidges_pop, filename = paste0(outdir, "variance_explained_ridge_pop.png"), height = 8, width = 10)
# pRaincloud <- ggplot(icc_dt, aes(x = percent, y = factor(grp_size, levels = rev(levels(grp_size))), fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(stat = "binline", bins = 90, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
# geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors)
pRaincloud <- ggplot(icc_dt, aes(x = percent, y = factor(grp_size, levels = rev(levels(grp_size))), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.1, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud, filename = paste0(outdir, "variance_explained_raincloud.png"), height = 2, width = 5)
ggsave(pRaincloud, filename = paste0(outdir, "variance_explained_raincloud.pdf"), height = 2, width = 5)
icc_interaction_plus_dt$grp_size <- factor(icc_interaction_plus_dt$grp_size, levels = c("Line\nN = 12076", "Passage\nN = 3620", "Line:Passage\nN = 2033", "Residual\nN = 12076"))
# pRaincloud_interaction <- ggplot(icc_interaction_plus_dt, aes(x = percent, y = grp_size, fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(size = 0.1, stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity.., fill = factor(grp, levels = rev(vars))), alpha = 0.75) +
# geom_boxplot(outlier.shape=20, size = 0.1,width = .15, outlier.size = 0.01, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors) +
# scale_color_manual(values = var_colors) +
# geom_vline(xintercept = 1,color = "grey70", size = 0.4, lty="11")
pRaincloud_interaction <- ggplot(icc_interaction_plus_dt, aes(x = percent, y = factor(grp_size, levels = levels(grp_size)), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.1, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud_interaction, filename = paste0(outdir, "variance_explained_raincloud_interaction.png"), height = 2, width = 4)
ggsave(pRaincloud_interaction, filename = paste0(outdir, "variance_explained_raincloud_interaction.pdf"), height = 2, width = 4)
icc_interaction_sig_list <- list()
for (ensg in unique(icc_interaction_plus_dt$gene)){
icc_interaction_sig_list[[ensg]] <- icc_interaction_plus_dt[gene == ensg][P < 0.05/(nrow(icc_interaction_plus_dt[gene == ensg])-1)]
icc_interaction_sig_list[[ensg]] <- rbind(icc_interaction_sig_list[[ensg]], icc_interaction_plus_dt[gene == ensg & grp == "Residual"])
}
icc_interaction_sig_dt <- do.call(rbind, icc_interaction_sig_list)
group_size <- data.table(table(icc_interaction_sig_dt$grp))
colnames(group_size) <- c("grp", "size")
group_size$grp_size <- paste0(group_size$grp, "\nN = ", group_size$size)
icc_interaction_sig_dt <- group_size[icc_interaction_sig_dt, on = "grp"]
icc_interaction_sig_dt$grp_size <- factor(icc_interaction_sig_dt$grp_size, levels = unique(group_size$grp_size))
grp_size_order <- c("Line\nN = 12076", "Passage\nN = 3620", "Line:Passage\nN = 2033", "Residual\nN = 12076")
mean(icc_interaction_sig_dt[grp == "Line"]$percent)
mean(icc_interaction_sig_dt[grp == "Passage"]$percent)
mean(icc_interaction_sig_dt[grp == "Line:Passage"]$percent)
mean(icc_interaction_sig_dt[grp == "Line" & percent > 1]$percent)
mean(icc_interaction_sig_dt[grp == "Passage" & percent > 1]$percent)
mean(icc_interaction_sig_dt[grp == "Line:Passage" & percent > 1]$percent)
# pRaincloud_interaction_sig <- ggplot(icc_interaction_sig_dt, aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
# geom_boxplot(size = 0.5,width = .15, outlier.size = 0.15, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors) +
# geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
pRaincloud_interaction_sig <- ggplot(icc_interaction_sig_dt, aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.07, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud_interaction_sig, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant.png"), height = 2, width = 4)
ggsave(pRaincloud_interaction_sig, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant.pdf"), height = 2, width = 4)
total <- icc_interaction_sig_dt[,.(count = .N), by = .(grp)]
total_less1pct <- icc_interaction_sig_dt[percent <= 1][,.(count_less_1pct = .N), by = .(grp)]
total_less5pct <- icc_interaction_sig_dt[percent <= 5][,.(count_less_5pct = .N), by = .(grp)]
total_less10pct <- icc_interaction_sig_dt[percent <= 10][,.(count_less_10pct = .N), by = .(grp)]
summary <- total[total_less1pct, on = "grp"]
summary <- summary[total_less5pct, on = "grp"]
summary <- summary[total_less10pct, on = "grp"]
summary$count_greater_1pct <- summary$count - summary$count_less_1pct
summary$count_greater_5pct <- summary$count - summary$count_less_5pct
summary$count_greater_10pct <- summary$count - summary$count_less_10pct
summary$percent_1pct <- (summary$count_less_1pct/summary$count)*100
summary$percent_5pct <- (summary$count_less_5pct/summary$count)*100
summary$percent_10pct <- (summary$count_less_10pct/summary$count)*100
# pRaincloud_interaction_sig_1pct <- ggplot(icc_interaction_sig_dt[percent >= 1], aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
# geom_density_ridges(stat = "binline", bins = 90, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
# geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
# coord_cartesian(xlim = c(1.2, NA), clip = "off") +
# theme_classic() +
# theme(axis.title.y=element_blank()) +
# xlab("Percent Variance Explained") +
# scale_y_discrete(expand = c(0.03, 0)) +
# scale_fill_manual(values = var_colors) +
# geom_vline(xintercept = 1, linetype = "dashed", color = "firebrick3")
pRaincloud_interaction_sig_1pct <- ggplot(icc_interaction_sig_dt[percent >= 1], aes(x = percent, y = factor(grp_size, levels = grp_size_order), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(size = 0.1,stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..)) +
geom_point(size =1, position = position_nudge(y=-0.09), shape = "|", aes(color = factor(grp, levels = rev(vars)))) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.07, 0)) +
scale_fill_manual(values = var_colors, name = "Variable") +
scale_color_manual(values = var_colors, name = "Variable") +
geom_vline(xintercept = 1, lty="11", color = "grey50", size = 0.5)
ggsave(pRaincloud_interaction_sig_1pct, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_1pct.png"), height = 2, width = 4)
ggsave(pRaincloud_interaction_sig_1pct, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_1pct.pdf"), height = 2, width = 4)
##### Pull just the significant variances genome-wide #####
icc_interaction_plus_dt$fdr <- p.adjust(icc_interaction_plus_dt$P, method="fdr")
icc_interaction_sig_gw_dt <- icc_interaction_plus_dt[fdr < 0.05 | is.na(fdr)]
group_size_sig_gw <- data.table(table(icc_interaction_sig_gw_dt$grp))
colnames(group_size_sig_gw) <- c("grp", "size")
group_size_sig_gw$grp_size <- paste0(group_size_sig_gw$grp, "\nN = ", formatC(group_size_sig_gw$size, format="d", big.mark=","))
icc_interaction_sig_gw_dt <- group_size_sig_gw[icc_interaction_sig_gw_dt, on = "grp"]
icc_interaction_sig_gw_dt$grp_size <- factor(icc_interaction_sig_gw_dt$grp_size, levels = unique(group_size_sig_gw$grp_size))
group_size_sig_gw_order <- c("Line\nN = 750", "Passage\nN = 750", "Line:Passage\nN = 619", "Residual\nN = 750")
pRaincloud_interaction_sig_gw <- ggplot(icc_interaction_sig_gw_dt, aes(x = percent, y = factor(grp_size, levels = group_size_sig_gw_order), fill = factor(grp, levels = rev(vars)))) +
geom_density_ridges(stat = "binline", bins = 100, scale = 0.7, draw_baseline = FALSE, aes(height =..ndensity..), alpha = 0.75) +
geom_boxplot(size = 0.5,width = .15, outlier.size = 0.25, position = position_nudge(y=-0.12), alpha = 0.75) +
coord_cartesian(xlim = c(1.2, NA), clip = "off") +
theme_classic() +
theme(axis.title.y=element_blank()) +
xlab("Percent Variance Explained") +
scale_y_discrete(expand = c(0.03, 0)) +
scale_fill_manual(values = var_colors) +
geom_vline(xintercept = 1, linetype = "dashed", color = "firebrick3") +
labs(fill="Covariate")
ggsave(pRaincloud_interaction_sig_gw, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_genome_wide.png"), height = 8, width = 7)
ggsave(pRaincloud_interaction_sig_gw, filename = paste0(outdir, "variance_explained_raincloud_interaction_significant_genome_wide.pdf"), height = 8, width = 7)
icc_interaction_sig_dt[gene == "ENSG00000106153"]
icc_dt[gene == "ENSG00000106153"]
icc_interaction_plus_dt[gene == "ENSG00000106153"]
icc_interaction_sig_gw_dt[gene == "ENSG00000106153"]
icc_interaction_sig_gw_dt2[gene == "ENSG00000106153"]
##### Add gene IDs for easy identification downstream #####
GeneConversion1 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/DRENEA_1/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion2 <- read_delim("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/data/Expression_200128_A00152_0196_BH3HNFDSXY/GE/Village_B_1_week/outs/filtered_feature_bc_matrix/features.tsv.gz", col_names = F, delim = "\t")
GeneConversion <- unique(rbind(GeneConversion1, GeneConversion2))
GeneConversion <- GeneConversion[!duplicated(GeneConversion$X1),]
GeneConversion$X3 <- NULL
colnames(GeneConversion) <- c("gene", "Gene_ID")
GeneConversion <- data.table(GeneConversion)
### Add the gene IDs to the icc_dt ###
icc_interaction_sig_gw_dt <- GeneConversion[icc_interaction_sig_gw_dt, on = "gene"]
icc_interaction_sig_gw_dt[grp == "Cryopreserved"& percent_round > 1][rev(order(percent))]$Gene_ID
head(icc_interaction_sig_gw_dt[grp == "Cryopreserved" & percent_round > 1][rev(order(percent))][,c("Gene_ID", "percent_round")], n = 50)
icc_interaction_sig_gw_dt[grp == "Line"][rev(order(percent))]$Gene_ID
head(icc_interaction_sig_gw_dt[grp == "Line" & percent_round > 1][rev(order(percent))][,c("Gene_ID", "percent_round")], n = 50)
icc_interaction_sig_gw_dt[grp == "Village"][rev(order(percent))]$Gene_ID
head(icc_interaction_sig_gw_dt[grp == "Village" & percent_round > 1][rev(order(percent))][,c("Gene_ID", "percent_round")], n = 50)
fwrite(icc_interaction_sig_gw_dt, paste0(outdir, "sig_results.tsv.gz"), sep = "\t", compress = "gzip")
## Highlight
## X chromosome genes - wouldn't expect these to be Line-biased because expressed by both males and females
## Y chromosome genes - should be line-biased because expressed by only males and have some male(s) and some female(s)
## mt genes
## ribosomal genes
## look at gsea and kegg pathways for each
## Read in gtf used as reference and pull just X, Y or MT chromosome genes from it, use ribosomal file for rb genes
gtf <- fread("/directflow/GWCCGPipeline/projects/reference/refdata-cellranger-GRCh38-3.0.0/genes/genes.gtf", sep = "\t", autostart = 6, header = FALSE)
gtf_genes <- gtf[!(grep("transcript_id", V9))]
gtf_genes$V9 <- gsub("gene_id \"", "",gtf_genes$V9 ) %>%
gsub("\"; gene_version \"", ";", .) %>%
gsub("\"; gene_name \"", ";", .) %>%
gsub("\"; gene_source \"", ";", .) %>%
gsub("\"; gene_biotype \"", ";", .) %>%
gsub("\"", "", .)
gtf_genes[, c("gene_id", "gene_version", "gene_name", "gene_source", "gene_biotype") := data.table(str_split_fixed(V9,";", 5))]
icc_interaction_plus_dt <- GeneConversion[icc_interaction_plus_dt, on = "gene"]
X_chromosome_genes <- gtf_genes[V1 == "X"]
X_genelist <- X_chromosome_genes$gene_id[X_chromosome_genes$gene_id %in% genes]
Y_chromosome_genes <- gtf_genes[V1 == "Y"]
Y_genelist <- Y_chromosome_genes$gene_id[Y_chromosome_genes$gene_id %in% genes]
MT_chromosome_genes <- gtf_genes[V1 == "MT"]
MT_genelist <- MT_chromosome_genes$gene_id[MT_chromosome_genes$gene_id %in% genes]
RbGeneList <- read.delim(file = "/directflow/SCCGGroupShare/projects/DrewNeavin/References/RibosomalGeneList_GeneID_ENSG.txt")
Rb_genelist <- RbGeneList$ENSG[RbGeneList$ENSG %in% genes]
### Make stacked bar plots of the variance explained by different factors for these gene groups
## Figure of x chromosome genes ##
icc_x <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% X_genelist][order(percent_round)]$gene), on = "gene"]
icc_x$grp <- factor(icc_x$grp, levels = rev(selected_vars))
icc_x$gene <- factor(icc_x$gene, levels = unique(icc_x$gene))
bar_proportions_x <- ggplot(icc_x, aes(x = gene, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = var_colors) +
ggtitle("Variance Explained of\nX Chromosome Genes")
ggsave(bar_proportions_x, filename = paste0(outdir, "variance_explained_bar_x_genes.png"), width = 20)
## Figure of y chromosome genes ##
icc_y <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% Y_genelist][order(percent_round)]$gene), on = "gene"]
icc_y$grp <- factor(icc_y$grp, levels = rev(selected_vars))
icc_y$gene <- factor(icc_y$gene, levels = unique(icc_y$gene))
icc_y$Gene_ID <- factor(icc_y$Gene_ID, levels = unique(icc_y$Gene_ID))
bar_proportions_y <- ggplot(icc_y, aes(x = Gene_ID, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
# axis.text.x=element_blank(),
# axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
scale_fill_manual(values = var_colors) +
scale_y_continuous(expand = c(0, 0)) +
ggtitle("Variance Explained of\nY Chromosome Genes") +
ylab("Percent")
ggsave(bar_proportions_y, filename = paste0(outdir, "variance_explained_bar_y_genes.png"), width = 4.5, height = 4.5)
ggsave(bar_proportions_y, filename = paste0(outdir, "variance_explained_bar_y_genes.pdf"), width = 4.5, height = 4.5)
## Figure of mt chromosome genes ##
icc_mt <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% MT_genelist][order(percent_round)]$gene), on = "gene"]
icc_mt$grp <- factor(icc_mt$grp, levels = rev(selected_vars))
icc_mt$gene <- factor(icc_mt$gene, levels = unique(icc_mt$gene))
icc_mt$Gene_ID <- factor(icc_mt$Gene_ID, levels = unique(icc_mt$Gene_ID))
bar_proportions_mt <- ggplot(icc_mt, aes(x = Gene_ID, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
# axis.text.x=element_blank(),
# axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
scale_fill_manual(values = var_colors) +
scale_y_continuous(expand = c(0, 0)) +
ggtitle("Variance Explained of\nMitochondrial Genes") +
ylab("Percent")
ggsave(bar_proportions_mt, filename = paste0(outdir, "variance_explained_bar_mt_genes.png"), width = 4.5, height = 4.5)
ggsave(bar_proportions_mt, filename = paste0(outdir, "variance_explained_bar_mt_genes.pdf"), width = 4.5, height = 4.5)
## Figure of mt chromosome genes ##
icc_rb <- icc_interaction_plus_dt[data.table(gene = icc_interaction_plus_dt[grp == "Residual"][gene %in% Rb_genelist][order(percent_round)]$gene), on = "gene"]
icc_rb$grp <- factor(icc_rb$grp, levels = rev(selected_vars))
icc_rb$gene <- factor(icc_rb$gene, levels = unique(icc_rb$gene))
bar_proportions_rb <- ggplot(icc_rb, aes(x = gene, y = percent, fill = grp)) +
geom_bar(position="stack", stat="identity", alpha = 0.75) +
theme_classic() +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = var_colors) +
scale_y_continuous(expand = c(0, 0)) +
ggtitle("Variance Explained\nof Ribosomal Genes")
ggsave(bar_proportions_rb, filename = paste0(outdir, "variance_explained_bar_rb_genes.png"), width = 10, height = 4)
ggsave(bar_proportions_rb, filename = paste0(outdir, "variance_explained_bar_rb_genes.pdf"), width = 10, height = 4)
### Plot Pluripotency Genes ###
pluri_genes <- fread(paste0(dir,"data/pluripotency_genes.tsv"), sep = "\t", col.names = "Gene_ID", header = FALSE)
pluri_genes <- GeneConversion[pluri_genes, on = "Gene_ID"]
icc_dt_pluri_genes <- icc_interaction_plus_dt[pluri_genes,on = c("gene")]
icc_dt_pluri_genes$grp <- factor(icc_dt_pluri_genes$grp, levels = rev(selected_vars))
icc_dt_pluri_genes <- icc_dt_pluri_genes[data.table(gene = icc_dt_pluri_genes[grp == "Residual"][order(percent)]$gene), on = "gene"]
icc_dt_pluri_genes$Gene_ID <- factor(icc_dt_pluri_genes$Gene_ID, levels = unique(icc_dt_pluri_genes$Gene_ID))
pPluri_Genes_Cont <- ggplot() +
geom_bar(data = icc_dt_pluri_genes, aes(Gene_ID, percent, fill = grp), position = "stack", stat = "identity", alpha = 0.75) +
theme_classic() +
# facet_wrap(Gene_ID ~ ., nrow = 3) +
scale_fill_manual(values = var_colors) +
theme(plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
ylab("Percent Gene Expression Variance Explained") +
ggtitle("Variance Explained of\nPluripotency Genes") +
theme(axis.title.x=element_blank())
ggsave(pPluri_Genes_Cont, filename = paste0(outdir, "Pluripotent_Gene_Variable_Contributions.png"), width = 6, height = 4.5)
ggsave(pPluri_Genes_Cont, filename = paste0(outdir, "Pluripotent_Gene_Variable_Contributions.pdf"), width = 6, height = 4.5)
##### check for variance explained for eQTL genes (from Kilpinen et al) that are #####
eqtls <- fread("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/eQTL_check/KilpinenOverlap/gene_snp_list.tsv", sep = "\t")
eqtls_icc <- icc_interaction_plus_dt[unique(eqtls[,"gene"]), on = "gene"]
eqtls_icc$grp <- factor(eqtls_icc$grp, levels = rev(vars))
eqtls_icc <- eqtls_icc[data.table(gene = eqtls_icc[grp == "Residual"][order(percent)]$gene), on = "gene"]
eqtls_icc$Gene_ID <- factor(eqtls_icc$Gene_ID, levels = unique(eqtls_icc$Gene_ID))
group_size_eqtl <- data.table(table(eqtls_icc$grp))
colnames(group_size_eqtl) <- c("grp", "size")
group_size_eqtl$grp_size <- paste0(group_size_eqtl$grp, "\nN = ", group_size_eqtl$size)
eqtls_icc <- group_size_eqtl[eqtls_icc, on = "grp"]
grp_size_order_eqtl <- c("Line\nN = 2371", "Village\nN = 1836", "Site\nN = 2461", "Replicate\nN = 869", "Line:Village\nN = 367", "Line:Site\nN = 911", "Village:Site\nN = 898","Replicate:Village\nN = 305", "Replicate:Line\nN = 25", "Replicate:Site\nN = 78", "Residual\nN = 2542")
eqtls_icc$grp_size <- factor(eqtls_icc$grp_size, levels = grp_size_order_eqtl)
eqtls_icc_1pct <- eqtls_icc
for (ensg in unique(eqtls_icc$gene)){
if (!any(eqtls_icc[gene == ensg & grp != "Residual"]$percent > 1)){
eqtls_icc_1pct <- eqtls_icc_1pct[gene != ensg]
}
}
eqtls_icc_1pct_grouped_list <- list()
for (ensg in unique(eqtls_icc_1pct$gene)){
group <- eqtls_icc_1pct[gene == ensg & grp != "Residual"][which.max(percent)]$grp
eqtls_icc_1pct_grouped_list[[group]][[ensg]] <- eqtls_icc_1pct[gene == ensg]
}
eqtls_icc_1pct_grouped <- lapply(eqtls_icc_1pct_grouped_list, function(x) do.call(rbind, x))
eqtls_icc_1pct_grouped <- lapply(names(eqtls_icc_1pct_grouped), function(x){
eqtls_icc_1pct_grouped[[x]]$largest_contributor <- x
return(eqtls_icc_1pct_grouped[[x]])
})
eqtls_icc_1pct_grouped_dt <- do.call(rbind, eqtls_icc_1pct_grouped)
eqtls_icc_1pct_grouped_dt$largest_contributor <- factor(eqtls_icc_1pct_grouped_dt$largest_contributor, levels = c("Line", "Village", "Site", "Line:Village", "Line:Site", "Village:Site", "Replicate:Village"))
pPluri_Genes_largest_Cont_eqtl <- ggplot() +
geom_bar(data = eqtls_icc_1pct_grouped_dt, aes(Gene_ID, percent, fill = factor(grp, levels = rev(vars))), position = "stack", stat = "identity", alpha = 0.75) +
theme_classic() +
facet_grid(. ~ largest_contributor, scales = "free_x", space = "free_x") +
scale_fill_manual(values = var_colors) +
ylab("Percent Gene Expression Variance Explained") +
theme(axis.title.x=element_blank(),
axis.text.x = element_blank(),
panel.spacing.x=unit(0, "lines"),
axis.ticks.x = element_blank()) +
geom_hline(yintercept = 1, linetype = "dashed")
# scale_y_discrete(expand = c(0.03, 0))
# scale_x_discrete(expand = c(0.03, 0))
ggsave(pPluri_Genes_largest_Cont_eqtl, filename = paste0(outdir, "eQTL_Genes_Variance_Contributions_1pct_largest_cont.png"), width = 10, height = 4)
ggsave(pPluri_Genes_largest_Cont_eqtl, filename = paste0(outdir, "eQTL_Genes_Variance_Contributions_1pct_largest_cont.pdf"), width = 10, height = 4)
# ### Count number of each chromosome/gene category type
# ### numbers are the numbers of that category that where a significant percent of variance is explained by this variable
# ### percent of that category that where a significant percent of variance is explained by this variable
# x_number <- lapply(genes_list, function(x){
# length(which(x %in% X_chromosome_genes$gene_id))
# })
# x_percent <- lapply(genes_list, function(x){
# length(which(x %in% X_chromosome_genes$gene_id))/length(X_chromosome_genes$gene_id)
# })
# y_number <- lapply(genes_list, function(x){
# length(which(x %in% Y_chromosome_genes$gene_id))
# })
# y_percent <- lapply(genes_list, function(x){
# length(which(x %in% Y_chromosome_genes$gene_id))/length(Y_chromosome_genes$gene_id)
# })
# mt_number <- lapply(genes_list, function(x){
# length(which(x %in% MT_chromosome_genes$gene_id))
# })
# mt_percent <- lapply(genes_list, function(x){
# length(which(x %in% MT_chromosome_genes$gene_id))/length(MT_chromosome_genes$gene_id)
# })
# rb_number <- lapply(genes_list, function(x){
# length(which(x %in% RbGeneList$ENSG))
# })
# rb_percent <- lapply(genes_list, function(x){
# length(which(x %in% RbGeneList$ENSG))/length(RbGeneList$ENSG)
# })
# ### for > 1% var explained
# ### Count number of each chromosome/gene category type
# x_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% X_chromosome_genes$gene_id))
# })
# names(x_number_1) <- vars
# x_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% X_chromosome_genes$gene_id))/length(X_chromosome_genes$gene_id)
# })
# names(x_percent_1) <- vars
# y_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% Y_chromosome_genes$gene_id))
# })
# names(y_number_1) <- vars
# y_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% Y_chromosome_genes$gene_id))/length(Y_chromosome_genes$gene_id)
# })
# names(y_percent_1) <- vars
# mt_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% MT_chromosome_genes$gene_id))
# })
# names(mt_number_1) <- vars
# mt_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% MT_chromosome_genes$gene_id))/length( MT_chromosome_genes$gene_id)
# })
# names(mt_percent_1) <- vars
# rb_number_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% RbGeneList$ENSG))
# })
# names(rb_number_1) <- vars
# rb_percent_1 <- lapply(vars, function(group){
# genes <- icc_dt[grp == group][rev(order(percent_round))][percent > 1]$gene
# length(which(genes %in% RbGeneList$ENSG))/length(RbGeneList$ENSG)
# })
# names(rb_percent_1) <- vars
### Pathway analysis ###
geneList <- lapply(genes_list, function(x){
tmp <- bitr(x, fromType = "ENSEMBL",
toType = c("ENTREZID"),
OrgDb = org.Hs.eg.db)$ENTREZID
tmp[!is.na(tmp)]
})
gg <- list()
kk <- list()
df = as.data.frame(org.Hs.egGO)
go_gene_list = unique(sort(df$gene_id))
dfk = as.data.frame(org.Hs.egPATH)
kegg_gene_list = unique(sort(dfk$gene_id))
for (group in c("Line", "Village", "Cryopreserved", "Replicate","Line:Village", "Line:Cryopreserved", "Village:Cryopreserved", "Replicate:Village", "Replicate:Line", "Replicate:Cryopreserved", "Residual")){
kk[[group]] <- enrichKEGG(gene = geneList[[group]],
universe = geneList[[group]],
organism = 'hsa',
pvalueCutoff = 0.05,
keyType = 'ncbi-geneid')
gg[[group]] <- groupGO(gene = geneList[[group]],
OrgDb = org.Hs.eg.db,
readable = TRUE)
}
hsGO <- godata('org.Hs.eg.db', ont="MF")
sim_results <- list()
vars <- c("Line", "Village", "Cryopreserved", "Replicate","Village:Line", "Line:Cryopreserved", "Village:Cryopreserved", "Replicate:Village", "Replicate:Line", "Replicate:Cryopreserved")
for (group1 in vars){
print(group1)
for (group2 in vars[(grep(paste0("^",group1, "$"), vars) + 1): length(vars)]){
print(group2)
sim_results[[group1]][[group2]] <- clusterSim(geneList[[group1]], geneList[[group2]], semData=hsGO, measure="Wang", combine="BMA")
}
}
# genes2rerun <- c(character())
# for (g in unique(icc_dt$gene)){
# print(g)
# genes2rerun <- c(genes2rerun, as.character(unique(icc_dt[gene == g][P > 0.05/(nrow(icc_dt[gene == g])-1)]$gene)))
# }
# for (gene in genes2rerun){
# print(gene)
# # unlink(paste0(icc_dir,gene,"_icc.rds"))
# print(file.exists(paste0(icc_dir,gene,"_icc.rds")))
# unlink(paste0("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/variance_partition_post_review/gene_separated/fit_models/",gene,"_fitted_models.rds"))
# unlink(paste0("/directflow/SCCGGroupShare/projects/DrewNeavin/iPSC_Village/output/variance_partition_post_review/gene_separated/residuals4qtl/",gene,"_residuals4qtl.rds"))
# }
|
library(h2o)
setwd(".../Kaggle")
train = read.csv("train.csv",header=TRUE,stringsAsFactors = F)
test = read.csv("test.csv",header=TRUE,stringsAsFactors = F)
id_train=train[1]
id_test=test[1]
train = train[,-1] ## remove the 'id' col
test = test[,-1] ## remove the 'id' col
MultiLogLoss <- function(act, pred)
{
eps = 1e-15;
nr <- nrow(pred)
pred = matrix(sapply( pred, function(x) max(eps,x)), nrow = nr)
pred = matrix(sapply( pred, function(x) min(1-eps,x)), nrow = nr)
ll = sum(act*log(pred))
ll = ll * -1/(nrow(act))
return(ll);
}
train_x = train[,-ncol(train)] ## This remove 'id' column
train_x = as.matrix(train_x) ## This just change the format
train_x = matrix(as.numeric(train_x),nrow(train_x),ncol(train_x)) ## This just change the format (change to numeric)
train_y = train[,ncol(train)]
train_y = gsub('Class_','',train_y) ## This change the 'Class_' into numbers
train_y_fac = as.factor(train_y) #R's RF assums type of factor for classif
train_y_num = as.integer(train_y) #xgboost take features in [0,numOfClass)
train_y_matrix = matrix(0,nrow=nrow(train),ncol=9)
for (x in 1:nrow(train)){
train_y_matrix[x,train_y_num[x]]=1
}
train <- cbind(train_x,train_y_matrix)
test_x = test[,-ncol(test)] ## This remove 'id' column
test_x = as.matrix(test_x) ## This just change the format
test_x = matrix(as.numeric(test_x),nrow(test_x),ncol(test_x)) ## This just change the format (change to numeric)
test_y = test[,ncol(test)]
test_y = gsub('Class_','',test_y) ## This change the 'Class_' into numbers
test_y_fac = as.factor(test_y) #xgboost take features in [0,numOfClass)
test_y_num = as.integer(test_y)
test_y_matrix = matrix(0,nrow=nrow(test),ncol=9)
for (x in 1:nrow(test)){
test_y_matrix[x,test_y_num[x]]=1
}
test<- cbind(test_x,test_y_matrix)
# Launch h2o on localhost, using all cores
localH2O = h2o.init()
h2oServer <- h2o.init(nthreads = -1)
train.hex <- as.h2o(object=train)
dim(train.hex)
test.hex <- as.h2o(object=test)
dim(test.hex)
######################################################################
### load data sets and create train/validation split
######################################################################
######################################################################
### parameter tuning with random search
######################################################################
mylogloss_list=0
myparam_list=0
models <- c()
pred <- 0
for (i in 1:9) {
ptm <- proc.time()
rand_activation <- c("RectifierWithDropout", "MaxoutWithDropout")[sample(1:2,1)]
rand_numlayers <- sample(2:3,1)
rand_hidden <- c(sample(90:800, rand_numlayers, T))
rand_l1 <- runif(1, 0, 1e-3)
rand_l2 <- runif(1, 0, 1e-2)
rand_hidden_dropout <- c(runif(rand_numlayers, 0, 0.5))
rand_input_dropout <- runif(1, 0, 0.5)
rand_rho <- runif(1, 0.9, 0.999)
rand_epsilon <- runif(1, 1e-10, 1e-4)
rand_rate <- runif(1, 0.005, 0.02)
rand_rate_decay <- runif(1, 0, 0.66)
rand_momentum <- runif(1, 0, 0.5)
rand_momentum_ramp <- runif(1, 1e-7, 1e-5)
dlmodel <- h2o.deeplearning(x = 1:93,
y = 93+i,
training_frame = train.hex,
validation_frame = test.hex,
rho = rand_rho, epsilon = rand_epsilon,
rate = rand_rate,
rate_decay = rand_rate_decay,
nesterov_accelerated_gradient = T,
momentum_start = rand_momentum,
momentum_ramp = rand_momentum_ramp,
activation = rand_activation,
hidden = rand_hidden,
l1 = rand_l1,
l2 = rand_l2,
input_dropout_ratio = rand_input_dropout,
hidden_dropout_ratios = rand_hidden_dropout,
epochs = 20
)
models <- c(models, dlmodel)
pred_buffer <- as.data.frame(h2o.predict(dlmodel, train.hex))
#pred <- as.data.frame(h2o.predict(dlmodel, test.hex))
#pred_buffer <-round(pred$predict)
actual = matrix(0,nrow=nrow(train),ncol=9)
for (x in 1:nrow(train)){
actual[x,train_y_num[x]]=1
}
pred_matrix = matrix(0,nrow=nrow(actual),ncol=ncol(actual))
for (x in 1:nrow(actual)){
if ((pred_buffer[x]<10) && (pred_buffer[x]>0))
{
pred_matrix[x,pred_buffer[x]]=1
}
}
mylogloss <- MultiLogLoss(actual, pred_matrix)
ptm2 <- proc.time()-ptm
message(mylogloss, " __ calculation costs ", ptm2[1])
#myparam_list=rbind(myparam_list,param_xgb)
mylogloss_list= rbind(mylogloss_list,mylogloss)
}
|
/[R] Step1_nn_h2o_randomSearch.R
|
no_license
|
gokul180288/-Kaggle-OttoGroup
|
R
| false | false | 4,959 |
r
|
library(h2o)
setwd(".../Kaggle")
train = read.csv("train.csv",header=TRUE,stringsAsFactors = F)
test = read.csv("test.csv",header=TRUE,stringsAsFactors = F)
id_train=train[1]
id_test=test[1]
train = train[,-1] ## remove the 'id' col
test = test[,-1] ## remove the 'id' col
MultiLogLoss <- function(act, pred)
{
eps = 1e-15;
nr <- nrow(pred)
pred = matrix(sapply( pred, function(x) max(eps,x)), nrow = nr)
pred = matrix(sapply( pred, function(x) min(1-eps,x)), nrow = nr)
ll = sum(act*log(pred))
ll = ll * -1/(nrow(act))
return(ll);
}
train_x = train[,-ncol(train)] ## This remove 'id' column
train_x = as.matrix(train_x) ## This just change the format
train_x = matrix(as.numeric(train_x),nrow(train_x),ncol(train_x)) ## This just change the format (change to numeric)
train_y = train[,ncol(train)]
train_y = gsub('Class_','',train_y) ## This change the 'Class_' into numbers
train_y_fac = as.factor(train_y) #R's RF assums type of factor for classif
train_y_num = as.integer(train_y) #xgboost take features in [0,numOfClass)
train_y_matrix = matrix(0,nrow=nrow(train),ncol=9)
for (x in 1:nrow(train)){
train_y_matrix[x,train_y_num[x]]=1
}
train <- cbind(train_x,train_y_matrix)
test_x = test[,-ncol(test)] ## This remove 'id' column
test_x = as.matrix(test_x) ## This just change the format
test_x = matrix(as.numeric(test_x),nrow(test_x),ncol(test_x)) ## This just change the format (change to numeric)
test_y = test[,ncol(test)]
test_y = gsub('Class_','',test_y) ## This change the 'Class_' into numbers
test_y_fac = as.factor(test_y) #xgboost take features in [0,numOfClass)
test_y_num = as.integer(test_y)
test_y_matrix = matrix(0,nrow=nrow(test),ncol=9)
for (x in 1:nrow(test)){
test_y_matrix[x,test_y_num[x]]=1
}
test<- cbind(test_x,test_y_matrix)
# Launch h2o on localhost, using all cores
localH2O = h2o.init()
h2oServer <- h2o.init(nthreads = -1)
train.hex <- as.h2o(object=train)
dim(train.hex)
test.hex <- as.h2o(object=test)
dim(test.hex)
######################################################################
### load data sets and create train/validation split
######################################################################
######################################################################
### parameter tuning with random search
######################################################################
mylogloss_list=0
myparam_list=0
models <- c()
pred <- 0
for (i in 1:9) {
ptm <- proc.time()
rand_activation <- c("RectifierWithDropout", "MaxoutWithDropout")[sample(1:2,1)]
rand_numlayers <- sample(2:3,1)
rand_hidden <- c(sample(90:800, rand_numlayers, T))
rand_l1 <- runif(1, 0, 1e-3)
rand_l2 <- runif(1, 0, 1e-2)
rand_hidden_dropout <- c(runif(rand_numlayers, 0, 0.5))
rand_input_dropout <- runif(1, 0, 0.5)
rand_rho <- runif(1, 0.9, 0.999)
rand_epsilon <- runif(1, 1e-10, 1e-4)
rand_rate <- runif(1, 0.005, 0.02)
rand_rate_decay <- runif(1, 0, 0.66)
rand_momentum <- runif(1, 0, 0.5)
rand_momentum_ramp <- runif(1, 1e-7, 1e-5)
dlmodel <- h2o.deeplearning(x = 1:93,
y = 93+i,
training_frame = train.hex,
validation_frame = test.hex,
rho = rand_rho, epsilon = rand_epsilon,
rate = rand_rate,
rate_decay = rand_rate_decay,
nesterov_accelerated_gradient = T,
momentum_start = rand_momentum,
momentum_ramp = rand_momentum_ramp,
activation = rand_activation,
hidden = rand_hidden,
l1 = rand_l1,
l2 = rand_l2,
input_dropout_ratio = rand_input_dropout,
hidden_dropout_ratios = rand_hidden_dropout,
epochs = 20
)
models <- c(models, dlmodel)
pred_buffer <- as.data.frame(h2o.predict(dlmodel, train.hex))
#pred <- as.data.frame(h2o.predict(dlmodel, test.hex))
#pred_buffer <-round(pred$predict)
actual = matrix(0,nrow=nrow(train),ncol=9)
for (x in 1:nrow(train)){
actual[x,train_y_num[x]]=1
}
pred_matrix = matrix(0,nrow=nrow(actual),ncol=ncol(actual))
for (x in 1:nrow(actual)){
if ((pred_buffer[x]<10) && (pred_buffer[x]>0))
{
pred_matrix[x,pred_buffer[x]]=1
}
}
mylogloss <- MultiLogLoss(actual, pred_matrix)
ptm2 <- proc.time()-ptm
message(mylogloss, " __ calculation costs ", ptm2[1])
#myparam_list=rbind(myparam_list,param_xgb)
mylogloss_list= rbind(mylogloss_list,mylogloss)
}
|
# Load train data and look for good parameters using grid search on a subset of the training set
source('load_and_clean.R')
source('imputation.R')
source('typing.R')
train = full_train[1:53460, ]
test = full_train[53461:59400, ]
library(ranger)
library(caret)
# Manual Search
control <- trainControl(method="cv", number=5, search="grid")
tunegrid <- expand.grid(mtry=c(13:15))
ntree <- 1500
print(paste("CV for ", ntree, " trees"))
set.seed(1)
rf_gridsearch_1 <- train(status_group~., data=train, method="ranger", tuneGrid=tunegrid, trControl=control, num.trees=ntree, verbose=TRUE)
print(rf_gridsearch_1)
plot(rf_gridsearch_1)
|
/15_var/rf_cv.R
|
no_license
|
mbahri/pumpitup
|
R
| false | false | 632 |
r
|
# Load train data and look for good parameters using grid search on a subset of the training set
source('load_and_clean.R')
source('imputation.R')
source('typing.R')
train = full_train[1:53460, ]
test = full_train[53461:59400, ]
library(ranger)
library(caret)
# Manual Search
control <- trainControl(method="cv", number=5, search="grid")
tunegrid <- expand.grid(mtry=c(13:15))
ntree <- 1500
print(paste("CV for ", ntree, " trees"))
set.seed(1)
rf_gridsearch_1 <- train(status_group~., data=train, method="ranger", tuneGrid=tunegrid, trControl=control, num.trees=ntree, verbose=TRUE)
print(rf_gridsearch_1)
plot(rf_gridsearch_1)
|
#normal distribution mean=80, sd=10
x <- seq(40, 120, length=300)
x
y <- dnorm(x, mean=80, sd=10)
y
plot(x, y)
plot(x, y, type="l")
plot(x, y, type="l", col="red")
#lines(x, dnorm(x, mean=80, sd=25), col="blue")
#a. probability between 65~75
x2 <- seq(65, 75, length=200)
y2 <- dnorm(x2, mean=80, sd=10)
polygon(c(65,x2,75), c(0, y2, 0), col="gray")
pnorm(75, mean=80, sd=10)-pnorm(65, mean=80, sd=10)
#pnorm
#qnorm
#dnorm
#rnorm
#b. probability of over 92
#2 Ways
#First
pnorm(92, mean=80, sd=10, lower.tail=FALSE)
#Second
1-pnorm(92, mean=80, sd=10)
#c. probability of less than 68
pnorm(68, mean=80, sd=10)
#d. cutoff that seqarates the bottom 30%
qnorm(0.3, mean=80, sd=10)
#e. 80th percentile
qnorm(0.8, mean=80, sd=10)
#f. cutoffs that cantatin the middle 60%
qnorm(0.8, mean=80, sd=10)
qnorm(0.2, mean=80, sd=10)
#To verify that it is correct
80-qnorm(0.8, mean=80, sd=10)
80-qnorm(0.2, mean=80, sd=10)
|
/15. pnorm, qnorm, 정규분포, normal distribution.R
|
no_license
|
hallymer/R_Programming_Season1
|
R
| false | false | 917 |
r
|
#normal distribution mean=80, sd=10
x <- seq(40, 120, length=300)
x
y <- dnorm(x, mean=80, sd=10)
y
plot(x, y)
plot(x, y, type="l")
plot(x, y, type="l", col="red")
#lines(x, dnorm(x, mean=80, sd=25), col="blue")
#a. probability between 65~75
x2 <- seq(65, 75, length=200)
y2 <- dnorm(x2, mean=80, sd=10)
polygon(c(65,x2,75), c(0, y2, 0), col="gray")
pnorm(75, mean=80, sd=10)-pnorm(65, mean=80, sd=10)
#pnorm
#qnorm
#dnorm
#rnorm
#b. probability of over 92
#2 Ways
#First
pnorm(92, mean=80, sd=10, lower.tail=FALSE)
#Second
1-pnorm(92, mean=80, sd=10)
#c. probability of less than 68
pnorm(68, mean=80, sd=10)
#d. cutoff that seqarates the bottom 30%
qnorm(0.3, mean=80, sd=10)
#e. 80th percentile
qnorm(0.8, mean=80, sd=10)
#f. cutoffs that cantatin the middle 60%
qnorm(0.8, mean=80, sd=10)
qnorm(0.2, mean=80, sd=10)
#To verify that it is correct
80-qnorm(0.8, mean=80, sd=10)
80-qnorm(0.2, mean=80, sd=10)
|
###########################
####### DESCRIPTION #######
###########################
# Description goes here.
rm (list = ls())
suppressPackageStartupMessages(library("plyr"))
suppressPackageStartupMessages(library("doParallel"))
source("/home/antonio/Desktop/BigData/codes/functions.R") # load the functions
# Specify working directory: (The wd MUST contain 2 subfolders: "Downalod" and "Clean")
directory = "/home/antonio/Desktop/BigData/data"
setwd(paste0(directory,"/Clean"))
# Getting filenames
filename <- list.files(getwd(), pattern = ".*txt$")
#filename = filename[1:50] # only for test!
# Aggregate Data
nodes <- detectCores()
cl <- makePSOCKcluster(nodes)
registerDoParallel(cl)
a_ply(.data = filename,
.fun = aggregate_data,
.parallel = TRUE,
.margins = 1)
stopCluster(cl)
|
/06_aggregate_cleaned_data.R
|
no_license
|
ciulloA/BigData
|
R
| false | false | 807 |
r
|
###########################
####### DESCRIPTION #######
###########################
# Description goes here.
rm (list = ls())
suppressPackageStartupMessages(library("plyr"))
suppressPackageStartupMessages(library("doParallel"))
source("/home/antonio/Desktop/BigData/codes/functions.R") # load the functions
# Specify working directory: (The wd MUST contain 2 subfolders: "Downalod" and "Clean")
directory = "/home/antonio/Desktop/BigData/data"
setwd(paste0(directory,"/Clean"))
# Getting filenames
filename <- list.files(getwd(), pattern = ".*txt$")
#filename = filename[1:50] # only for test!
# Aggregate Data
nodes <- detectCores()
cl <- makePSOCKcluster(nodes)
registerDoParallel(cl)
a_ply(.data = filename,
.fun = aggregate_data,
.parallel = TRUE,
.margins = 1)
stopCluster(cl)
|
#options <- NULL
#options$DT <- 11
#options$percentile <- 5
#options$showPlots <- 0 # for show plots
#options$showPlots <- 1 # not show plots
#load("c:/temp/4Heston.Rdata")
# y <- xxx
HestonModel <- function(y,options) {
# define parameters
lastError <- 1
fSigma <- 0
nK <- 100
# find theta
varX <- array(NA, dim = options$DT)
for (i in 1:options$DT) { varX[i] <- sum((diff(y, lag = i))^2)/(length(y) - 1- i) }
lastError <- 1
fSigma <- 0
while(lastError > fSigma) {
options$DT <- options$DT -1
theta <- sum(varX[1:options$DT]*c(1:options$DT))/(options$DT*(options$DT+1)*(2*options$DT+1)/6)
lastError <- abs(varX[options$DT] - theta*options$DT)
fSigma <- 1.5*sd(varX[1:options$DT] - theta*c(1:options$DT))
}
if (options$showPlots == 0) {
windows()
plot(c(1:options$DT),varX[1:options$DT])
lines( c(1:options$DT), theta*c(1:options$DT), lwd=2, col="blue")
grid()
}
ecf <- array(0, dim = c(options$DT,nK))
k <- array(0, dim = c(options$DT,nK))
nKth <- array(0, dim = options$DT)
for (i in 1:options$DT) {
xxx <- ECF(diff(y, lag = i),nK)
ecf[i,] <- xxx[[1]]
k[i,] <- xxx[[2]]
nKth[i] <- xxx[[3]]
}
xxx <- HestonFitK(ecf, k, nKth, c(1:options$DT), theta, options)
a <- xxx[[1]]
g <- xxx[[2]]
x <- array(NA, dim = c(options$DT,101))
PDFX <- array(NA, dim = c(options$DT,101))
xAv <- array(NA, dim = c(options$DT,50))
CPDF <- array(NA, dim = c(options$DT,50))
prct <- array(NA, dim = options$DT)
for (i in 1:options$DT) {
xxx <- HestonX(a,g,theta,k[i,nKth[i]],i)
x[i,] <-xxx[[1]]
PDFX[i,] <-xxx[[2]]
xxx <- percentile(x[i,],PDFX[i,],options)
xAv[i,] <- xxx[[1]]
CPDF[i,] <- xxx[[2]]
prct[i] <- xxx[[3]]
}
if (options$showPlots == 0) {
cols <- rainbow(options$DT)
Xrange <- c(-max(abs(diff(y, lag = options$DT))), max(abs(diff(y, lag = options$DT))))
Yrange <- c(0,1)
windows()
plot(Xrange,Yrange, type = "n", xlab = "Delta Value (M$)", ylab = "CPDF",
main = bquote(paste("Heston Fit CPDF: ", gamma == .(format(g, digits = 3)), ", ",
alpha == .(format(a, digits = 3)), ", ", theta == .(format(theta, digits = 3)))))
for(i in 1:options$DT) {
ySort <- sort(diff(y, lag = i))
quantiles <- quantile(ySort, probs = c(0.01*options$percentile, 1-0.01*options$percentile))
CP <- (c(1:length(ySort))-0.5)/length(ySort)
points(ySort,CP, lwd = 2, col = cols[i])
lines(-xAv[i,],CPDF[i,], lwd = 2, col = cols[i])
lines(xAv[i,],(1-CPDF[i,]), lwd = 2, col = cols[i])
abline(v = - prct[i], lwd = 1, col = cols[i])
abline(v = prct[i], pch = 22, lwd = 1, col = cols[i])
abline(v = quantiles[1], pch = 22, lwd = 1, col = cols[i])
abline(v = quantiles[2], pch = 22, lwd = 1, col = cols[i])
}
grid()
windows()
Yrange <- c(1e-3,max(PDFX))
plot(Xrange,Yrange, type = "n", log = "y", xlab = "Delta Value (M$)", ylab = "PDF",
main = bquote(paste("Heston Fit PDF: ", gamma == .(format(g, digits = 3)), ", ",
alpha == .(format(a, digits = 3)), ", ", theta == .(format(theta, digits = 3)))))
for(i in 1: options$DT) {
lines(x[i,],PDFX[i,], lwd = 3, col = cols[i])
lines(-1*x[i,],PDFX[i,], lwd = 3, col = cols[i])
abline(v = prct[i], lwd = 3, col = cols[i])
abline(v = -prct[i], lwd = 3, col = cols[i])
}
grid()
}
return(list(a,g,x,PDFX,prct))
}
percentile <- function(x,PDFX,options) {
# browser()
CPDF <- array(0, dim = ((length(x)-1)/2))
Xav <- array(0, dim = ((length(x)-1)/2))
m <- 0
for (i in ((length(x)-1)/2):1){
m <- m + 1
X <- c(x[2*i+1],x[2*i],x[2*i-1])
Y <- c(PDFX[2*i+1],PDFX[2*i],PDFX[2*i-1])
xxx <- parabolicCoeff(X,Y)
dInt <- (X[1]-X[3])*((xxx[[1]]/3)*(X[3]*X[3] + X[3]*X[1]+ X[1]*X[1]) + (xxx[[2]]/2)*(X[3]+X[1]) + xxx[[3]])
Xav[m] <- X[3]
if( m == 1){ CPDF[m] <- dInt }
if (m > 1) {
CPDF[m] <- CPDF[m-1] +dInt
if(CPDF[m] > 0.01*options$percentile & CPDF[m-1] < 0.01*options$percentile)
xPrct <- (X[3]+(X[1]-X[3])*(CPDF[m] - 0.01*options$percentile)/dInt)
}
}
return(list(Xav,CPDF,xPrct))
}
parabolicCoeff <- function(x,y) {
R21 <- (y[2]-y[1])/(x[2]-x[1])
R32 <- (y[3]-y[2])/(x[3]-x[2])
A <- (R21-R32)/(x[1]-x[3])
B <- R21-A*(x[2]+x[1])
C <- y[1]-A*x[1]*x[1]-B*x[1]
return(list(A,B,C))
}
# Heston Function in x-space
HestonX <- function(a,g,theta,kMax,DT) {
while (PDFkHeston(a,g,theta,kMax,DT) > 1e-5) # find kMax
kMax <- kMax + 10
dx <- 0.2/kMax
xMax <- 100/kMax
dK <- 0.1/xMax
nK <- 2*round(round(kMax/dK)/2)
nKp1 <- nK + 1
k <- dK*c(0:nK)
PDFK <- array(0, dim = nKp1)
IntFun <- array(0, dim = nKp1)
for(i in 1:nKp1)
PDFK[i] <- PDFkHeston(a,g,theta,k[i],DT)
nx <- 100
dx <- xMax/nx
# find the x limit
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*xMax)*PDFK[j]
PDFxMax <- 1/pi*Simpson(IntFun,nKp1,dK)
while(PDFxMax < 2e-5){
xMax <- xMax - dx
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*xMax)*PDFK[j]
PDFxMax <- 1/pi*Simpson(IntFun,nKp1,dK)
}
while(PDFxMax > 2e-5){
xMax <- xMax + dx
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*xMax)*PDFK[j]
PDFxMax <- 1/pi*Simpson(IntFun,nKp1,dK)
}
dx <- xMax/nx
x <- dx*c(0:nx)
PDFX <- array(0, dim = (nx +1))
for( i in 1:(nx+1)) {
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*x[i])*PDFK[j]
PDFX[i] <- 1/pi*Simpson(IntFun,nKp1,dK);
}
return(list(x,PDFX))
}
Simpson <- function(intFunction,N,dx) {
indEven <- 2*c(1:((N-1)/2))
indOdd <- 1 + 2*c(1:((N-2)/2))
intRes <- (dx/3)*(intFunction[1]+intFunction[N] + 4*sum(intFunction[indEven]) + 2*sum(intFunction[indOdd]))
return(intRes)
}
# Heston Fit
HestonFitK <- function(ecf,k,nKth,DT,theta,options){
# browser()
a <- 1
nFactor <- 5
gX <- 1/sqrt(min(DT)*max(DT))
chiX <- cfVSecf(ecf,k,nKth,DT,a,gX,theta,options$showPlots)
while (nFactor > 0) {
gMin <- gX/nFactor
gMax <- gX*nFactor
chiMin <- cfVSecf(ecf,k,nKth,DT,a,gMin,theta,1)
chiMax <- cfVSecf(ecf,k,nKth,DT,a,gMax,theta,1)
nIt <- 0
if(chiMin > chiX & chiMax > chiX ) {
nFactor <- 0
while(nIt < 20){
nIt <- nIt + 1
gXX <- (gMin + gMax)/2
chiXX <- cfVSecf(ecf,k,nKth,DT,a,gXX,theta,1)
if(gXX > gX) {
if(chiXX < chiX) {
gMin <- gX
chiMin <- chiX
gX <- gXX
chiX <- chiXX
} else {
gMax <- gXX
chiMax <- chiXX
}
} else {
if(chiXX < chiX) {
gMax <- gX
chiMax <- chiX
gX <- gXX
chiX <- chiXX
} else {
gMin <- gXX
chiMin <- chiXX
}
}
if( gMax - gMin < 0.002 | nIt == 20){
gX <- (gMax+gMin)/2
chiX <- cfVSecf(ecf,k,nKth,DT,a,gX,theta,options$showPlots)
break;
}
}
} else {
if(chiMin < chiMax) {
gMax <- gX
chiMax <- gMax
gX <- gMin
chiX <- chiMin
gMin <- gMin/nFactor
chiMin <- cfVSecf(ecf,k,nKth,DT,a,gMin,theta,1)
} else {
gMin <- gX
chiMin <- chiX
gX <- gMax
chiX <- chiMax
gMax <- gMax*nFactor
chiMax <- cfVSecf(ecf,k,nKth,DT,a,gMax,theta,1)
}
}
}
return(list(a,gX,chiX))
}
# Characteristic vs Emprical Characteristic Functiotions
cfVSecf <- function(ecf,k,nKth,DT,a,g,theta,nFlagFig) {
chi <- 0
cf <- array(NA, dim = c(length(DT),max(nKth)))
# browser()
for (iDT in 1:length(DT)) {
for (iK in 1:nKth[iDT]) {
cf[iDT,iK] <- PDFkHeston(a,g,theta,k[iDT,iK],DT[iDT])
dCF <- cf[iDT,iK] - ecf[iDT,iK]
chi <- chi + dCF*dCF
}
}
if(nFlagFig == 0) {
windows()
plot(k[1,],ecf[1,], type = "n",
main = bquote(paste("CF vs ECF,", chi == .(format(chi, digits = 3)), ", ",
gamma == .(format(g, digits = 3)), ", ", alpha == .(format(a, digits = 3)))),
xlab = "k", ylab = "CF")
for (iDT in 1:length(DT)){
points(k[iDT,1:nKth[iDT]], ecf[iDT,1:nKth[iDT]], lwd = 3, col = "red")
lines(k[iDT,1:nKth[iDT]], cf[iDT,1:nKth[iDT]], lwd = 3, col = "blue")
}
grid()
}
return(chi)
}
PDFkHeston <- function(a,g,theta,k,DT) {
if (k == 0) {
Ftk <- 0
} else {
gt <- g*DT
omega <- sqrt(1 + 2*k*k*theta/(g*a))
omegaGammaTo2 <- omega*gt/2
if (omegaGammaTo2 > 10) {
Ftk <- gt/2*(1-omega) - log((omega*omega+2*omega+1)/(4*omega))
} else {
Ftk <- gt/2 - log(cosh(omegaGammaTo2) + (omega*omega + 1)/(2*omega)*sinh(omegaGammaTo2))
}
}
return(exp(a*Ftk))
}
ECF <- function(dx,nK) {
ecf <- array(0, dim = nK)
k <- array(0, dim = nK)
dxMax <- max(abs(dx))
nIt <- 1
while(nIt < 10) {
kMax <- 20*nIt/dxMax
dK <- kMax/(nK-1)
k = dK * c(0:(nK-1))
ecf[1] <- length(dx)
for (ik in (2:nK) ) {
for (idx in 1:length(dx))
ecf[ik] <- ecf[ik] + cos(k[ik]*dx[idx])
}
ecf <- ecf/ecf[1]
if( ecf[nK] < 0.1)
break
nIt <- nIt + 1
}
nKth <- nK
for (iK in 2:nK ) {
if ( ecf[iK] < 0.05 ){
nKth <- iK-1
break
}
}
return(list(ecf,k,nKth))
}
|
/R Extension/RMG/Finance/Heston/HestonModel.R
|
no_license
|
uhasan1/QLExtension-backup
|
R
| false | false | 9,299 |
r
|
#options <- NULL
#options$DT <- 11
#options$percentile <- 5
#options$showPlots <- 0 # for show plots
#options$showPlots <- 1 # not show plots
#load("c:/temp/4Heston.Rdata")
# y <- xxx
HestonModel <- function(y,options) {
# define parameters
lastError <- 1
fSigma <- 0
nK <- 100
# find theta
varX <- array(NA, dim = options$DT)
for (i in 1:options$DT) { varX[i] <- sum((diff(y, lag = i))^2)/(length(y) - 1- i) }
lastError <- 1
fSigma <- 0
while(lastError > fSigma) {
options$DT <- options$DT -1
theta <- sum(varX[1:options$DT]*c(1:options$DT))/(options$DT*(options$DT+1)*(2*options$DT+1)/6)
lastError <- abs(varX[options$DT] - theta*options$DT)
fSigma <- 1.5*sd(varX[1:options$DT] - theta*c(1:options$DT))
}
if (options$showPlots == 0) {
windows()
plot(c(1:options$DT),varX[1:options$DT])
lines( c(1:options$DT), theta*c(1:options$DT), lwd=2, col="blue")
grid()
}
ecf <- array(0, dim = c(options$DT,nK))
k <- array(0, dim = c(options$DT,nK))
nKth <- array(0, dim = options$DT)
for (i in 1:options$DT) {
xxx <- ECF(diff(y, lag = i),nK)
ecf[i,] <- xxx[[1]]
k[i,] <- xxx[[2]]
nKth[i] <- xxx[[3]]
}
xxx <- HestonFitK(ecf, k, nKth, c(1:options$DT), theta, options)
a <- xxx[[1]]
g <- xxx[[2]]
x <- array(NA, dim = c(options$DT,101))
PDFX <- array(NA, dim = c(options$DT,101))
xAv <- array(NA, dim = c(options$DT,50))
CPDF <- array(NA, dim = c(options$DT,50))
prct <- array(NA, dim = options$DT)
for (i in 1:options$DT) {
xxx <- HestonX(a,g,theta,k[i,nKth[i]],i)
x[i,] <-xxx[[1]]
PDFX[i,] <-xxx[[2]]
xxx <- percentile(x[i,],PDFX[i,],options)
xAv[i,] <- xxx[[1]]
CPDF[i,] <- xxx[[2]]
prct[i] <- xxx[[3]]
}
if (options$showPlots == 0) {
cols <- rainbow(options$DT)
Xrange <- c(-max(abs(diff(y, lag = options$DT))), max(abs(diff(y, lag = options$DT))))
Yrange <- c(0,1)
windows()
plot(Xrange,Yrange, type = "n", xlab = "Delta Value (M$)", ylab = "CPDF",
main = bquote(paste("Heston Fit CPDF: ", gamma == .(format(g, digits = 3)), ", ",
alpha == .(format(a, digits = 3)), ", ", theta == .(format(theta, digits = 3)))))
for(i in 1:options$DT) {
ySort <- sort(diff(y, lag = i))
quantiles <- quantile(ySort, probs = c(0.01*options$percentile, 1-0.01*options$percentile))
CP <- (c(1:length(ySort))-0.5)/length(ySort)
points(ySort,CP, lwd = 2, col = cols[i])
lines(-xAv[i,],CPDF[i,], lwd = 2, col = cols[i])
lines(xAv[i,],(1-CPDF[i,]), lwd = 2, col = cols[i])
abline(v = - prct[i], lwd = 1, col = cols[i])
abline(v = prct[i], pch = 22, lwd = 1, col = cols[i])
abline(v = quantiles[1], pch = 22, lwd = 1, col = cols[i])
abline(v = quantiles[2], pch = 22, lwd = 1, col = cols[i])
}
grid()
windows()
Yrange <- c(1e-3,max(PDFX))
plot(Xrange,Yrange, type = "n", log = "y", xlab = "Delta Value (M$)", ylab = "PDF",
main = bquote(paste("Heston Fit PDF: ", gamma == .(format(g, digits = 3)), ", ",
alpha == .(format(a, digits = 3)), ", ", theta == .(format(theta, digits = 3)))))
for(i in 1: options$DT) {
lines(x[i,],PDFX[i,], lwd = 3, col = cols[i])
lines(-1*x[i,],PDFX[i,], lwd = 3, col = cols[i])
abline(v = prct[i], lwd = 3, col = cols[i])
abline(v = -prct[i], lwd = 3, col = cols[i])
}
grid()
}
return(list(a,g,x,PDFX,prct))
}
percentile <- function(x,PDFX,options) {
# browser()
CPDF <- array(0, dim = ((length(x)-1)/2))
Xav <- array(0, dim = ((length(x)-1)/2))
m <- 0
for (i in ((length(x)-1)/2):1){
m <- m + 1
X <- c(x[2*i+1],x[2*i],x[2*i-1])
Y <- c(PDFX[2*i+1],PDFX[2*i],PDFX[2*i-1])
xxx <- parabolicCoeff(X,Y)
dInt <- (X[1]-X[3])*((xxx[[1]]/3)*(X[3]*X[3] + X[3]*X[1]+ X[1]*X[1]) + (xxx[[2]]/2)*(X[3]+X[1]) + xxx[[3]])
Xav[m] <- X[3]
if( m == 1){ CPDF[m] <- dInt }
if (m > 1) {
CPDF[m] <- CPDF[m-1] +dInt
if(CPDF[m] > 0.01*options$percentile & CPDF[m-1] < 0.01*options$percentile)
xPrct <- (X[3]+(X[1]-X[3])*(CPDF[m] - 0.01*options$percentile)/dInt)
}
}
return(list(Xav,CPDF,xPrct))
}
parabolicCoeff <- function(x,y) {
R21 <- (y[2]-y[1])/(x[2]-x[1])
R32 <- (y[3]-y[2])/(x[3]-x[2])
A <- (R21-R32)/(x[1]-x[3])
B <- R21-A*(x[2]+x[1])
C <- y[1]-A*x[1]*x[1]-B*x[1]
return(list(A,B,C))
}
# Heston Function in x-space
HestonX <- function(a,g,theta,kMax,DT) {
while (PDFkHeston(a,g,theta,kMax,DT) > 1e-5) # find kMax
kMax <- kMax + 10
dx <- 0.2/kMax
xMax <- 100/kMax
dK <- 0.1/xMax
nK <- 2*round(round(kMax/dK)/2)
nKp1 <- nK + 1
k <- dK*c(0:nK)
PDFK <- array(0, dim = nKp1)
IntFun <- array(0, dim = nKp1)
for(i in 1:nKp1)
PDFK[i] <- PDFkHeston(a,g,theta,k[i],DT)
nx <- 100
dx <- xMax/nx
# find the x limit
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*xMax)*PDFK[j]
PDFxMax <- 1/pi*Simpson(IntFun,nKp1,dK)
while(PDFxMax < 2e-5){
xMax <- xMax - dx
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*xMax)*PDFK[j]
PDFxMax <- 1/pi*Simpson(IntFun,nKp1,dK)
}
while(PDFxMax > 2e-5){
xMax <- xMax + dx
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*xMax)*PDFK[j]
PDFxMax <- 1/pi*Simpson(IntFun,nKp1,dK)
}
dx <- xMax/nx
x <- dx*c(0:nx)
PDFX <- array(0, dim = (nx +1))
for( i in 1:(nx+1)) {
for (j in 1:nKp1)
IntFun[j] <- cos(k[j]*x[i])*PDFK[j]
PDFX[i] <- 1/pi*Simpson(IntFun,nKp1,dK);
}
return(list(x,PDFX))
}
Simpson <- function(intFunction,N,dx) {
indEven <- 2*c(1:((N-1)/2))
indOdd <- 1 + 2*c(1:((N-2)/2))
intRes <- (dx/3)*(intFunction[1]+intFunction[N] + 4*sum(intFunction[indEven]) + 2*sum(intFunction[indOdd]))
return(intRes)
}
# Heston Fit
HestonFitK <- function(ecf,k,nKth,DT,theta,options){
# browser()
a <- 1
nFactor <- 5
gX <- 1/sqrt(min(DT)*max(DT))
chiX <- cfVSecf(ecf,k,nKth,DT,a,gX,theta,options$showPlots)
while (nFactor > 0) {
gMin <- gX/nFactor
gMax <- gX*nFactor
chiMin <- cfVSecf(ecf,k,nKth,DT,a,gMin,theta,1)
chiMax <- cfVSecf(ecf,k,nKth,DT,a,gMax,theta,1)
nIt <- 0
if(chiMin > chiX & chiMax > chiX ) {
nFactor <- 0
while(nIt < 20){
nIt <- nIt + 1
gXX <- (gMin + gMax)/2
chiXX <- cfVSecf(ecf,k,nKth,DT,a,gXX,theta,1)
if(gXX > gX) {
if(chiXX < chiX) {
gMin <- gX
chiMin <- chiX
gX <- gXX
chiX <- chiXX
} else {
gMax <- gXX
chiMax <- chiXX
}
} else {
if(chiXX < chiX) {
gMax <- gX
chiMax <- chiX
gX <- gXX
chiX <- chiXX
} else {
gMin <- gXX
chiMin <- chiXX
}
}
if( gMax - gMin < 0.002 | nIt == 20){
gX <- (gMax+gMin)/2
chiX <- cfVSecf(ecf,k,nKth,DT,a,gX,theta,options$showPlots)
break;
}
}
} else {
if(chiMin < chiMax) {
gMax <- gX
chiMax <- gMax
gX <- gMin
chiX <- chiMin
gMin <- gMin/nFactor
chiMin <- cfVSecf(ecf,k,nKth,DT,a,gMin,theta,1)
} else {
gMin <- gX
chiMin <- chiX
gX <- gMax
chiX <- chiMax
gMax <- gMax*nFactor
chiMax <- cfVSecf(ecf,k,nKth,DT,a,gMax,theta,1)
}
}
}
return(list(a,gX,chiX))
}
# Characteristic vs Emprical Characteristic Functiotions
cfVSecf <- function(ecf,k,nKth,DT,a,g,theta,nFlagFig) {
chi <- 0
cf <- array(NA, dim = c(length(DT),max(nKth)))
# browser()
for (iDT in 1:length(DT)) {
for (iK in 1:nKth[iDT]) {
cf[iDT,iK] <- PDFkHeston(a,g,theta,k[iDT,iK],DT[iDT])
dCF <- cf[iDT,iK] - ecf[iDT,iK]
chi <- chi + dCF*dCF
}
}
if(nFlagFig == 0) {
windows()
plot(k[1,],ecf[1,], type = "n",
main = bquote(paste("CF vs ECF,", chi == .(format(chi, digits = 3)), ", ",
gamma == .(format(g, digits = 3)), ", ", alpha == .(format(a, digits = 3)))),
xlab = "k", ylab = "CF")
for (iDT in 1:length(DT)){
points(k[iDT,1:nKth[iDT]], ecf[iDT,1:nKth[iDT]], lwd = 3, col = "red")
lines(k[iDT,1:nKth[iDT]], cf[iDT,1:nKth[iDT]], lwd = 3, col = "blue")
}
grid()
}
return(chi)
}
PDFkHeston <- function(a,g,theta,k,DT) {
if (k == 0) {
Ftk <- 0
} else {
gt <- g*DT
omega <- sqrt(1 + 2*k*k*theta/(g*a))
omegaGammaTo2 <- omega*gt/2
if (omegaGammaTo2 > 10) {
Ftk <- gt/2*(1-omega) - log((omega*omega+2*omega+1)/(4*omega))
} else {
Ftk <- gt/2 - log(cosh(omegaGammaTo2) + (omega*omega + 1)/(2*omega)*sinh(omegaGammaTo2))
}
}
return(exp(a*Ftk))
}
ECF <- function(dx,nK) {
ecf <- array(0, dim = nK)
k <- array(0, dim = nK)
dxMax <- max(abs(dx))
nIt <- 1
while(nIt < 10) {
kMax <- 20*nIt/dxMax
dK <- kMax/(nK-1)
k = dK * c(0:(nK-1))
ecf[1] <- length(dx)
for (ik in (2:nK) ) {
for (idx in 1:length(dx))
ecf[ik] <- ecf[ik] + cos(k[ik]*dx[idx])
}
ecf <- ecf/ecf[1]
if( ecf[nK] < 0.1)
break
nIt <- nIt + 1
}
nKth <- nK
for (iK in 2:nK ) {
if ( ecf[iK] < 0.05 ){
nKth <- iK-1
break
}
}
return(list(ecf,k,nKth))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mcmcChain.R
\name{.infer_param_dims}
\alias{.infer_param_dims}
\title{Infer original dimensions of parameter (per iteration) from colnames}
\usage{
.infer_param_dims(cnames)
}
\arguments{
\item{cnames}{List of column names}
}
\value{
Numeric vector (nrow, ncol)
}
\description{
Used to avoid writing colnames directly to HDF5 as attribute, which fails
for large parameters (e.g. Y)
}
\keyword{internal}
|
/man/dot-infer_param_dims.Rd
|
permissive
|
JunqiangWang/BayesSpace
|
R
| false | true | 481 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mcmcChain.R
\name{.infer_param_dims}
\alias{.infer_param_dims}
\title{Infer original dimensions of parameter (per iteration) from colnames}
\usage{
.infer_param_dims(cnames)
}
\arguments{
\item{cnames}{List of column names}
}
\value{
Numeric vector (nrow, ncol)
}
\description{
Used to avoid writing colnames directly to HDF5 as attribute, which fails
for large parameters (e.g. Y)
}
\keyword{internal}
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 40821
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 30289
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 30289
c
c Input Parameter (command line, file):
c input filename QBFLIB/Kronegger-Pfandler-Pichler/dungeon/dungeon_i10-m10-u10-v0.pddl_planlen=70.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 14947
c no.of clauses 40821
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 30289
c
c QBFLIB/Kronegger-Pfandler-Pichler/dungeon/dungeon_i10-m10-u10-v0.pddl_planlen=70.qdimacs 14947 40821 E1 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 44 45 46 47 48 49 50 51 52 53 55 56 57 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 119 120 121 122 123 124 125 126 127 128 129 130 131 132 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 172 173 174 175 176 177 178 179 224 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947] 0 10 4406 30289 RED
|
/code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/Kronegger-Pfandler-Pichler/dungeon/dungeon_i10-m10-u10-v0.pddl_planlen=70/dungeon_i10-m10-u10-v0.pddl_planlen=70.R
|
no_license
|
arey0pushpa/dcnf-autarky
|
R
| false | false | 56,114 |
r
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 40821
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 30289
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 30289
c
c Input Parameter (command line, file):
c input filename QBFLIB/Kronegger-Pfandler-Pichler/dungeon/dungeon_i10-m10-u10-v0.pddl_planlen=70.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 14947
c no.of clauses 40821
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 30289
c
c QBFLIB/Kronegger-Pfandler-Pichler/dungeon/dungeon_i10-m10-u10-v0.pddl_planlen=70.qdimacs 14947 40821 E1 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 38 39 40 41 42 44 45 46 47 48 49 50 51 52 53 55 56 57 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 119 120 121 122 123 124 125 126 127 128 129 130 131 132 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 172 173 174 175 176 177 178 179 224 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947] 0 10 4406 30289 RED
|
\name{diffFiles}
\alias{diffFiles}
\title{
Names of Files Showing Differences
}
\description{
List all files that show differences between control and test output
(as red pixels).
}
\usage{
diffFiles(x)
}
\arguments{
\item{x}{
A \code{"gdiffComparison"} object, as created by
\code{\link{gdiff}} or \code{\link{gdiffCompare}}.
}
}
\value{
A character vector of file names (with paths).
}
\author{
Paul Murrell
}
\seealso{
\code{\link{gdiff}} and
\code{\link{gdiffCompare}}.
}
\examples{
f1 <- function() plot(1)
f2 <- function() plot(2)
\donttest{
result <- gdiff(list(control=f1, test=f2), name="f",
controlDir=file.path(tempdir(), "Control"),
testDir=file.path(tempdir(), "Test"),
compareDir=file.path(tempdir(), "Compare"))
result
diffFiles(result)
}
}
\keyword{ dplot }
\concept{ visual testing }
|
/man/diffFiles.Rd
|
no_license
|
pmur002/gdiff
|
R
| false | false | 877 |
rd
|
\name{diffFiles}
\alias{diffFiles}
\title{
Names of Files Showing Differences
}
\description{
List all files that show differences between control and test output
(as red pixels).
}
\usage{
diffFiles(x)
}
\arguments{
\item{x}{
A \code{"gdiffComparison"} object, as created by
\code{\link{gdiff}} or \code{\link{gdiffCompare}}.
}
}
\value{
A character vector of file names (with paths).
}
\author{
Paul Murrell
}
\seealso{
\code{\link{gdiff}} and
\code{\link{gdiffCompare}}.
}
\examples{
f1 <- function() plot(1)
f2 <- function() plot(2)
\donttest{
result <- gdiff(list(control=f1, test=f2), name="f",
controlDir=file.path(tempdir(), "Control"),
testDir=file.path(tempdir(), "Test"),
compareDir=file.path(tempdir(), "Compare"))
result
diffFiles(result)
}
}
\keyword{ dplot }
\concept{ visual testing }
|
6*5
d<-"5"
d
a<-4
a
a*2
d*2
d*2
10%%3
x <- 50
x
x <- c(50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80)
x
x <- c(150,200,210)
x
dbl_var <- c(1, 2.5, 4.5)
I will be there at 2 pm.
dbl_var <- c(1, 2.5, 4.5, "xyz")
rep(1,10)
"abc" "st+-cydtsyndsklhnl"
pi
rep(3,3)
seq(2,6, by=3)
x <- c(1,2,3,4,5)
y<- c(5,6,7,8,9)
x*y
sqrt(y)
y[5]
a=5
b=2
a%%b
x%%y
y%%x
a%%5
y[-5]
y<3
y[y<9]=2
y
Df_new<-data.frame(height1=c(150,160,149,246,235),weight=c(65,72,79,90,100))
df <- data.frame(x = 1:3, y = c("a","b", "c"))
abc <- data.frame(x = 1:3, y = c("a", "b", "c"))
df[c(2,3),2]
Df_new[c(3,5),c(1,2)]
Df_new[3,2]
Df_new[4,]
Df_new[4,1:2]
Df_new[4,c(1,3)]
Df_new[c(1,3),'height1']
df[c(1,3),c("x","y")]
Df_new$height1
|
/myfirst_project.R
|
no_license
|
jaspal52119/my_first_datascience_project
|
R
| false | false | 932 |
r
|
6*5
d<-"5"
d
a<-4
a
a*2
d*2
d*2
10%%3
x <- 50
x
x <- c(50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80,50,60,80)
x
x <- c(150,200,210)
x
dbl_var <- c(1, 2.5, 4.5)
I will be there at 2 pm.
dbl_var <- c(1, 2.5, 4.5, "xyz")
rep(1,10)
"abc" "st+-cydtsyndsklhnl"
pi
rep(3,3)
seq(2,6, by=3)
x <- c(1,2,3,4,5)
y<- c(5,6,7,8,9)
x*y
sqrt(y)
y[5]
a=5
b=2
a%%b
x%%y
y%%x
a%%5
y[-5]
y<3
y[y<9]=2
y
Df_new<-data.frame(height1=c(150,160,149,246,235),weight=c(65,72,79,90,100))
df <- data.frame(x = 1:3, y = c("a","b", "c"))
abc <- data.frame(x = 1:3, y = c("a", "b", "c"))
df[c(2,3),2]
Df_new[c(3,5),c(1,2)]
Df_new[3,2]
Df_new[4,]
Df_new[4,1:2]
Df_new[4,c(1,3)]
Df_new[c(1,3),'height1']
df[c(1,3),c("x","y")]
Df_new$height1
|
library(data.table)
library(sparkline)
# ====準備部分====
source(file = "01_Settings/Path.R", local = T, encoding = "UTF-8")
# 感染者ソーステーブルを取得
byDate <- fread(paste0(DATA_PATH, "byDate.csv"), header = T)
byDate[is.na(byDate)] <- 0
byDate$date <- lapply(byDate[, 1], function(x) {
as.Date(as.character(x), format = "%Y%m%d")
})
# 死亡データ
death <- fread(paste0(DATA_PATH, "death.csv"))
death[is.na(death)] <- 0
# 文言データを取得
lang <- fread(paste0(DATA_PATH, "lang.csv"))
langCode <- "ja"
# 都道府県
provinceCode <- fread(paste0(DATA_PATH, "prefectures.csv"))
provinceSelector <- provinceCode$id
names(provinceSelector) <- provinceCode$`name-ja`
provinceAttr <- fread(paste0(DATA_PATH, "Signate/prefMaster.csv"))
provinceAttr[, 都道府県略称 := 都道府県]
provinceAttr[, 都道府県略称 := gsub("県", "", 都道府県略称)]
provinceAttr[, 都道府県略称 := gsub("府", "", 都道府県略称)]
provinceAttr[, 都道府県略称 := gsub("東京都", "東京", 都道府県略称)]
# 色設定
lightRed <- "#F56954"
middleRed <- "#DD4B39"
darkRed <- "#B03C2D"
lightYellow <- "#F8BF76"
middleYellow <- "#F39C11"
darkYellow <- "#DB8B0A"
lightGreen <- "#00A65A"
middleGreen <- "#01A65A"
darkGreen <- "#088448"
superDarkGreen <- "#046938"
lightNavy <- "#5A6E82"
middelNavy <- "#001F3F"
darkNavy <- "#001934"
lightGrey <- "#F5F5F5"
lightBlue <- "#7BD6F5"
middleBlue <- "#00C0EF"
darkBlue <- "#00A7D0"
# ====各都道府県のサマリーテーブル====
# ランキングカラムを作成
# cumDt <- cumsum(byDate[, c(2:48, 50)])
# rankDt <- data.table(t(apply(-cumDt, 1, function(x){rank(x, ties.method = 'min')})))
# rankDt[, colnames(rankDt) := shift(.SD, fill = 0) - .SD, .SDcols = colnames(rankDt)]
#
# rankDt[rankDt == 0] <- '-'
# rankDt[, colnames(rankDt) := ifelse(.SD > 0, paste0('+', .SD), .SD), .SDcols = colnames(rankDt)]
print("新規なし継続日数カラム作成")
zeroContinuousDay <- stack(lapply(byDate[, 2:ncol(byDate)], function(region) {
continuousDay <- 0
for (x in region) {
if (x == 0) {
continuousDay <- continuousDay + 1
} else {
continuousDay <- 0
}
}
return(continuousDay - 1)
}))
print("感染確認カラム作成")
total <- colSums(byDate[, 2:ncol(byDate)])
print("新規カラム作成")
today <- colSums(byDate[nrow(byDate), 2:ncol(byDate)])
print("昨日までカラム作成")
untilToday <- colSums(byDate[1:nrow(byDate) - 1, 2:ncol(byDate)])
print("感染者推移カラム作成")
dateSpan <- 21
diffSparkline <- sapply(2:ncol(byDate), function(i) {
# 新規値
value <- byDate[(nrow(byDate) - dateSpan):nrow(byDate), i, with = F][[1]]
# 累計値
cumsumValue <- c(cumsum(byDate[, i, with = F])[(nrow(byDate) - dateSpan):nrow(byDate)])[[1]]
# 日付
date <- byDate[(nrow(byDate) - dateSpan):nrow(byDate), 1, with = F][[1]]
colorMapSetting <- rep("#E7ADA6", length(value))
colorMapSetting[length(value)] <- darkRed
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(value) - 1)
# 新規
diff <- sparkline(
values = value,
type = "bar",
chartRangeMin = 0,
width = 80,
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 新規{{value}}名",
tooltipValueLookups = list(
names = namesSetting
),
colorMap = colorMapSetting
)
# 累計
cumsumSpk <- sparkline(
values = cumsumValue,
type = "line",
width = 80,
fillColor = F,
lineColor = darkRed,
tooltipFormat = "<span style='color: {{color}}'>●</span> 累計{{y}}名"
)
return(as.character(htmltools::as.tags(spk_composite(diff, cumsumSpk))))
})
print("新規回復者カラム作成")
mhlwSummary <- fread(file = "50_Data/MHLW/summary.csv")
mhlwSummary$日付 <- as.Date(as.character(mhlwSummary$日付), "%Y%m%d")
mhlwSummary[order(日付), dischargedDiff := 退院者 - shift(退院者), by = "都道府県名"]
print("回復推移")
dischargedDiffSparkline <- sapply(colnames(byDate)[2:48], function(region) {
data <- mhlwSummary[`都道府県名` == region]
# 新規
span <- nrow(data) - dateSpan
value <- data$dischargedDiff[ifelse(span < 0, 0, span):nrow(data)]
# 日付
date <- data$日付[ifelse(span < 0, 0, span):nrow(data)]
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(date) - 1)
if (length(value) > 0) {
diff <- spk_chr(
values = value,
type = "bar",
width = 80,
barColor = middleGreen,
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 新規回復{{value}}名",
tooltipValueLookups = list(
names = namesSetting
)
)
} else {
diff <- NA
}
return(diff)
})
print("死亡カラム作成")
deathByRegion <- stack(colSums(death[, 2:ncol(byDate)]))
print("感染者内訳")
detailSparkLineDt <- mhlwSummary[日付 == max(日付)]
detailSparkLine <- sapply(detailSparkLineDt$都道府県名, function(region) {
# 速報値との差分処理
regionNew <- ifelse(region == "空港検疫", "検疫職員", region)
confirmed <- ifelse(total[names(total) == regionNew][[1]] > detailSparkLineDt[都道府県名 == region, 陽性者],
total[names(total) == regionNew][[1]],
detailSparkLineDt[都道府県名 == region, 陽性者]
)
spk_chr(
type = "pie",
values = c(
confirmed - sum(detailSparkLineDt[都道府県名 == region, .(入院中, 退院者, 死亡者)], na.rm = T) -
ifelse(region == "クルーズ船", 40, 0),
detailSparkLineDt[都道府県名 == region, 入院中],
detailSparkLineDt[都道府県名 == region, 退院者],
detailSparkLineDt[都道府県名 == region, 死亡者]
),
sliceColors = c(middleRed, middleYellow, middleGreen, darkNavy),
tooltipFormat = '<span style="color: {{color}}">●</span> {{offset:names}}<br>{{value}} 名 ({{percent.1}}%)',
tooltipValueLookups = list(
names = list(
"0" = "情報待ち陽性者",
"1" = "入院者",
"2" = "回復者",
"3" = "死亡者"
)
)
)
})
print("二倍時間集計")
dt <- byDate[, 2:ncol(byDate)]
halfCount <- colSums(dt) / 2
dt <- cumsum(dt)
doubleTimeDay <- lapply(seq(halfCount), function(index) {
prefDt <- dt[, index, with = F]
nrow(prefDt[c(prefDt > halfCount[index])])
})
names(doubleTimeDay) <- names(dt)
# 回復者総数
totalDischarged <- mhlwSummary[日付 == max(日付), .(都道府県名, 退院者)]
colnames(totalDischarged) <- c("region", "totalDischarged")
print("都道府県別PCRデータ作成")
mhlwSummary[, 前日比 := 検査人数 - shift(検査人数), by = c("都道府県名")]
mhlwSummary[, 週間平均移動 := round(frollmean(前日比, 7), 0), by = c("都道府県名")]
mhlwSummary[, 陽性率 := round(陽性者 / 検査人数 * 100, 1)]
pcrByRegionToday <- mhlwSummary[日付 == max(日付)]
pcrDiffSparkline <- sapply(pcrByRegionToday$都道府県名, function(region) {
data <- mhlwSummary[都道府県名 == region]
# 新規
span <- nrow(data) - dateSpan
value <- data$前日比[ifelse(span < 0, 0, span):nrow(data)]
# 日付
date <- data$日付[ifelse(span < 0, 0, span):nrow(data)]
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(date) - 1)
if (length(value) > 0) {
diff <- spk_chr(
values = value,
type = "bar",
width = 80,
barColor = middleYellow,
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 新規{{value}}",
tooltipValueLookups = list(
names = namesSetting
)
)
} else {
diff <- NA
}
return(diff)
})
positiveRatioSparkline <- sapply(pcrByRegionToday$都道府県名, function(region) {
data <- mhlwSummary[都道府県名 == region]
# 新規
span <- nrow(data) - dateSpan
value <- data$陽性率[ifelse(span < 0, 0, span):nrow(data)]
# 日付
date <- data$日付[ifelse(span < 0, 0, span):nrow(data)]
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(date) - 1)
if (length(value) > 0) {
diff <- spk_chr(
values = value,
type = "line",
width = 80,
lineColor = darkRed,
fillColor = "#f2b3aa",
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 陽性率:{{y}}%",
tooltipValueLookups = list(
names = namesSetting
)
)
} else {
diff <- NA
}
return(diff)
})
pcrByRegionToday$検査数推移 <- pcrDiffSparkline
pcrByRegionToday$陽性率推移 <- positiveRatioSparkline
print("テーブル作成")
totalToday <- paste(sprintf("%06d", total), total, today, sep = "|")
mergeDt <- data.table(
region = names(total),
count = total,
today = today,
totalToday = totalToday,
untilToday = untilToday,
diff = diffSparkline,
dischargeDiff = "",
detailBullet = "",
death = deathByRegion$values,
zeroContinuousDay = zeroContinuousDay$values,
doubleTimeDay = doubleTimeDay
)
mergeDt <- merge(mergeDt, totalDischarged, all.x = T, sort = F)
signateSub <- provinceAttr[, .(都道府県略称, 人口)]
colnames(signateSub) <- c("region", "population")
mergeDt <- merge(mergeDt, signateSub, all.x = T, sort = F)
mergeDt[, perMillion := round(count / (population / 1000000), 0)]
mergeDt[, perMillionDeath := round(death / (population / 1000000), 0)]
for (i in mergeDt$region) {
mergeDt[region == i]$dischargeDiff <- dischargedDiffSparkline[i][[1]]
mergeDt[region == i]$detailBullet <- detailSparkLine[i][[1]]
}
# グルーピング
groupList <- list(
"北海道・東北" = provinceAttr[都道府県コード %in% 1:7]$都道府県略称,
"関東" = provinceAttr[都道府県コード %in% 8:14]$都道府県略称,
"中部" = provinceAttr[都道府県コード %in% 15:23]$都道府県略称,
"近畿" = provinceAttr[都道府県コード %in% 24:30]$都道府県略称,
"中国" = provinceAttr[都道府県コード %in% 31:35]$都道府県略称,
"四国" = provinceAttr[都道府県コード %in% 36:39]$都道府県略称,
"九州・沖縄" = provinceAttr[都道府県コード %in% 40:47]$都道府県略称,
"他" = colnames(byDate)[(ncol(byDate) - 3):ncol(byDate)]
)
mergeDt$group = ""
for (i in seq(nrow(mergeDt))) {
mergeDt[i]$group <- names(which(lapply(groupList, function(x) { mergeDt$region[i] %in% x }) == T))
}
# 面積あたりの感染者数
area <- fread(paste0(DATA_PATH, "Collection/area.csv"))
area[, 都道府県略称 := 都道府県]
area[, 都道府県略称 := gsub("県", "", 都道府県略称)]
area[, 都道府県略称 := gsub("府", "", 都道府県略称)]
area[, 都道府県略称 := gsub("東京都", "東京", 都道府県略称)]
mergeDt <- merge(mergeDt, area, by.x = "region", by.y = "都道府県略称", all.x = T, no.dups = T, sort = F)
mergeDt[, perArea := round(sqrt(可住地面積 / count), 2)]
mergeDt[, `:=` (コード = NULL, 都道府県 = NULL, 可住地面積 = NULL, 可住地面積割合 = NULL, 宅地面積 = NULL, 宅地面積割合 = NULL)]
pcrByRegionToday[, `:=` (dischargedDiff = NULL)]
mergeDt <- merge(mergeDt, pcrByRegionToday, by.x = "region", by.y = "都道府県名", all.x = T, no.dups = T, sort = F)
active <- mergeDt$陽性者 - mergeDt$退院者 - ifelse(is.na(mergeDt$死亡者), 0, mergeDt$死亡者)
mergeDt[, `:=` (日付 = NULL, 陽性者 = NULL, 入院中 = NULL, 退院者 = NULL, 死亡者 = NULL, 確認中 = NULL, 分類 = NULL)]
mergeDt[, 百万人あたり := round(検査人数 / (population / 1000000), 0)]
mergeDt[, population := NULL]
# 現在患者数
mergeDt$active <- active
mergeDt[active < 0, active := 0] # チャーター便の単独対応
mergeDt[region == "クルーズ船", active := active - 40] # クルーズ船の単独対応
# 13個特定警戒都道府県
alertPref <-
c(
# "東京",
# "大阪",
# "北海道",
# "茨城",
# "埼玉",
# "千葉",
# "神奈川",
# "石川",
# "岐阜",
# "愛知",
# "京都",
# "兵庫",
# "福岡"
)
for(i in seq(nrow(mergeDt))) {
if (mergeDt[i]$region %in% alertPref) {
mergeDt[i]$region <- paste0("<i style='color:#DD4B39;' class=\"fa fa-exclamation-triangle\"></i>", "<span style='float:right;'>", mergeDt[i]$region, "</span>")
} else if (mergeDt[i]$active == 0 && !is.na(mergeDt[i]$active)) {
mergeDt[i]$region <- paste0("<i style='color:#01A65A;' class=\"fa fa-check-circle\"></i>", "<span style='float:right;'>", mergeDt[i]$region, "</span>")
} else {
mergeDt[i]$region <- paste0("<span style='float:right;'>", mergeDt[i]$region, "</span>")
}
}
# 自治体名前ソート用
prefNameId <- sprintf('%02d', seq(2:ncol(byDate)))
mergeDt[, region := paste0(prefNameId, "|", region)]
# オーダー
# setorder(mergeDt, - count)
# 読み取り時のエラーを回避するため
mergeDt[, diff := gsub("\\n", "", diff)]
mergeDt[, dischargeDiff := gsub("\\n", "", dischargeDiff)]
mergeDt[, detailBullet := gsub("\\n", "", detailBullet)]
mergeDt[, 検査数推移 := gsub("\\n", "", 検査数推移)]
mergeDt[, 陽性率推移 := gsub("\\n", "", 陽性率推移)]
# クルーズ船とチャーター便データ除外
# mergeDt <- mergeDt[!grepl(pattern = paste0(lang[[langCode]][35:36], collapse = "|"), x = mergeDt$region)]
print("テーブル出力")
fwrite(x = mergeDt, file = paste0(DATA_PATH, "Generated/resultSummaryTable.ja.csv"), sep = "@", quote = F)
source(file = "00_System/CreateTable.Translate.R")
# ====マップ用のデータ作成====
dt <- data.frame(date = byDate$date)
for (i in 2:ncol(byDate)) {
dt[, i] <- cumsum(byDate[, i, with = F])
}
dt <- reshape2::melt(dt, id.vars = "date")
dt <- data.table(dt)
mapDt <- dt[!(variable %in% c("クルーズ船", "伊客船", "チャーター便", "検疫職員"))]
# マップデータ用意
mapDt <- merge(x = mapDt, y = provinceCode, by.x = "variable", by.y = "name-ja", all = T)
mapDt <- merge(x = mapDt, y = provinceAttr, by.x = "variable", by.y = "都道府県略称", all = T)
# 必要なカラムを保存
mapDt <- mapDt[, .(date, variable, 都道府県, `name-en`, value, regions, lat, lng)]
# カラム名変更
colnames(mapDt) <- c("date", "ja", "full_ja", "en", "count", "regions", "lat", "lng")
fwrite(x = mapDt, file = paste0(DATA_PATH, "result.map.csv"))
|
/00_System/CreateTable.R
|
permissive
|
YTLogos/2019-ncov-japan
|
R
| false | false | 14,293 |
r
|
library(data.table)
library(sparkline)
# ====準備部分====
source(file = "01_Settings/Path.R", local = T, encoding = "UTF-8")
# 感染者ソーステーブルを取得
byDate <- fread(paste0(DATA_PATH, "byDate.csv"), header = T)
byDate[is.na(byDate)] <- 0
byDate$date <- lapply(byDate[, 1], function(x) {
as.Date(as.character(x), format = "%Y%m%d")
})
# 死亡データ
death <- fread(paste0(DATA_PATH, "death.csv"))
death[is.na(death)] <- 0
# 文言データを取得
lang <- fread(paste0(DATA_PATH, "lang.csv"))
langCode <- "ja"
# 都道府県
provinceCode <- fread(paste0(DATA_PATH, "prefectures.csv"))
provinceSelector <- provinceCode$id
names(provinceSelector) <- provinceCode$`name-ja`
provinceAttr <- fread(paste0(DATA_PATH, "Signate/prefMaster.csv"))
provinceAttr[, 都道府県略称 := 都道府県]
provinceAttr[, 都道府県略称 := gsub("県", "", 都道府県略称)]
provinceAttr[, 都道府県略称 := gsub("府", "", 都道府県略称)]
provinceAttr[, 都道府県略称 := gsub("東京都", "東京", 都道府県略称)]
# 色設定
lightRed <- "#F56954"
middleRed <- "#DD4B39"
darkRed <- "#B03C2D"
lightYellow <- "#F8BF76"
middleYellow <- "#F39C11"
darkYellow <- "#DB8B0A"
lightGreen <- "#00A65A"
middleGreen <- "#01A65A"
darkGreen <- "#088448"
superDarkGreen <- "#046938"
lightNavy <- "#5A6E82"
middelNavy <- "#001F3F"
darkNavy <- "#001934"
lightGrey <- "#F5F5F5"
lightBlue <- "#7BD6F5"
middleBlue <- "#00C0EF"
darkBlue <- "#00A7D0"
# ====各都道府県のサマリーテーブル====
# ランキングカラムを作成
# cumDt <- cumsum(byDate[, c(2:48, 50)])
# rankDt <- data.table(t(apply(-cumDt, 1, function(x){rank(x, ties.method = 'min')})))
# rankDt[, colnames(rankDt) := shift(.SD, fill = 0) - .SD, .SDcols = colnames(rankDt)]
#
# rankDt[rankDt == 0] <- '-'
# rankDt[, colnames(rankDt) := ifelse(.SD > 0, paste0('+', .SD), .SD), .SDcols = colnames(rankDt)]
print("新規なし継続日数カラム作成")
zeroContinuousDay <- stack(lapply(byDate[, 2:ncol(byDate)], function(region) {
continuousDay <- 0
for (x in region) {
if (x == 0) {
continuousDay <- continuousDay + 1
} else {
continuousDay <- 0
}
}
return(continuousDay - 1)
}))
print("感染確認カラム作成")
total <- colSums(byDate[, 2:ncol(byDate)])
print("新規カラム作成")
today <- colSums(byDate[nrow(byDate), 2:ncol(byDate)])
print("昨日までカラム作成")
untilToday <- colSums(byDate[1:nrow(byDate) - 1, 2:ncol(byDate)])
print("感染者推移カラム作成")
dateSpan <- 21
diffSparkline <- sapply(2:ncol(byDate), function(i) {
# 新規値
value <- byDate[(nrow(byDate) - dateSpan):nrow(byDate), i, with = F][[1]]
# 累計値
cumsumValue <- c(cumsum(byDate[, i, with = F])[(nrow(byDate) - dateSpan):nrow(byDate)])[[1]]
# 日付
date <- byDate[(nrow(byDate) - dateSpan):nrow(byDate), 1, with = F][[1]]
colorMapSetting <- rep("#E7ADA6", length(value))
colorMapSetting[length(value)] <- darkRed
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(value) - 1)
# 新規
diff <- sparkline(
values = value,
type = "bar",
chartRangeMin = 0,
width = 80,
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 新規{{value}}名",
tooltipValueLookups = list(
names = namesSetting
),
colorMap = colorMapSetting
)
# 累計
cumsumSpk <- sparkline(
values = cumsumValue,
type = "line",
width = 80,
fillColor = F,
lineColor = darkRed,
tooltipFormat = "<span style='color: {{color}}'>●</span> 累計{{y}}名"
)
return(as.character(htmltools::as.tags(spk_composite(diff, cumsumSpk))))
})
print("新規回復者カラム作成")
mhlwSummary <- fread(file = "50_Data/MHLW/summary.csv")
mhlwSummary$日付 <- as.Date(as.character(mhlwSummary$日付), "%Y%m%d")
mhlwSummary[order(日付), dischargedDiff := 退院者 - shift(退院者), by = "都道府県名"]
print("回復推移")
dischargedDiffSparkline <- sapply(colnames(byDate)[2:48], function(region) {
data <- mhlwSummary[`都道府県名` == region]
# 新規
span <- nrow(data) - dateSpan
value <- data$dischargedDiff[ifelse(span < 0, 0, span):nrow(data)]
# 日付
date <- data$日付[ifelse(span < 0, 0, span):nrow(data)]
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(date) - 1)
if (length(value) > 0) {
diff <- spk_chr(
values = value,
type = "bar",
width = 80,
barColor = middleGreen,
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 新規回復{{value}}名",
tooltipValueLookups = list(
names = namesSetting
)
)
} else {
diff <- NA
}
return(diff)
})
print("死亡カラム作成")
deathByRegion <- stack(colSums(death[, 2:ncol(byDate)]))
print("感染者内訳")
detailSparkLineDt <- mhlwSummary[日付 == max(日付)]
detailSparkLine <- sapply(detailSparkLineDt$都道府県名, function(region) {
# 速報値との差分処理
regionNew <- ifelse(region == "空港検疫", "検疫職員", region)
confirmed <- ifelse(total[names(total) == regionNew][[1]] > detailSparkLineDt[都道府県名 == region, 陽性者],
total[names(total) == regionNew][[1]],
detailSparkLineDt[都道府県名 == region, 陽性者]
)
spk_chr(
type = "pie",
values = c(
confirmed - sum(detailSparkLineDt[都道府県名 == region, .(入院中, 退院者, 死亡者)], na.rm = T) -
ifelse(region == "クルーズ船", 40, 0),
detailSparkLineDt[都道府県名 == region, 入院中],
detailSparkLineDt[都道府県名 == region, 退院者],
detailSparkLineDt[都道府県名 == region, 死亡者]
),
sliceColors = c(middleRed, middleYellow, middleGreen, darkNavy),
tooltipFormat = '<span style="color: {{color}}">●</span> {{offset:names}}<br>{{value}} 名 ({{percent.1}}%)',
tooltipValueLookups = list(
names = list(
"0" = "情報待ち陽性者",
"1" = "入院者",
"2" = "回復者",
"3" = "死亡者"
)
)
)
})
print("二倍時間集計")
dt <- byDate[, 2:ncol(byDate)]
halfCount <- colSums(dt) / 2
dt <- cumsum(dt)
doubleTimeDay <- lapply(seq(halfCount), function(index) {
prefDt <- dt[, index, with = F]
nrow(prefDt[c(prefDt > halfCount[index])])
})
names(doubleTimeDay) <- names(dt)
# 回復者総数
totalDischarged <- mhlwSummary[日付 == max(日付), .(都道府県名, 退院者)]
colnames(totalDischarged) <- c("region", "totalDischarged")
print("都道府県別PCRデータ作成")
mhlwSummary[, 前日比 := 検査人数 - shift(検査人数), by = c("都道府県名")]
mhlwSummary[, 週間平均移動 := round(frollmean(前日比, 7), 0), by = c("都道府県名")]
mhlwSummary[, 陽性率 := round(陽性者 / 検査人数 * 100, 1)]
pcrByRegionToday <- mhlwSummary[日付 == max(日付)]
pcrDiffSparkline <- sapply(pcrByRegionToday$都道府県名, function(region) {
data <- mhlwSummary[都道府県名 == region]
# 新規
span <- nrow(data) - dateSpan
value <- data$前日比[ifelse(span < 0, 0, span):nrow(data)]
# 日付
date <- data$日付[ifelse(span < 0, 0, span):nrow(data)]
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(date) - 1)
if (length(value) > 0) {
diff <- spk_chr(
values = value,
type = "bar",
width = 80,
barColor = middleYellow,
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 新規{{value}}",
tooltipValueLookups = list(
names = namesSetting
)
)
} else {
diff <- NA
}
return(diff)
})
positiveRatioSparkline <- sapply(pcrByRegionToday$都道府県名, function(region) {
data <- mhlwSummary[都道府県名 == region]
# 新規
span <- nrow(data) - dateSpan
value <- data$陽性率[ifelse(span < 0, 0, span):nrow(data)]
# 日付
date <- data$日付[ifelse(span < 0, 0, span):nrow(data)]
namesSetting <- as.list(date)
names(namesSetting) <- 0:(length(date) - 1)
if (length(value) > 0) {
diff <- spk_chr(
values = value,
type = "line",
width = 80,
lineColor = darkRed,
fillColor = "#f2b3aa",
tooltipFormat = "{{offset:names}}<br><span style='color: {{color}}'>●</span> 陽性率:{{y}}%",
tooltipValueLookups = list(
names = namesSetting
)
)
} else {
diff <- NA
}
return(diff)
})
pcrByRegionToday$検査数推移 <- pcrDiffSparkline
pcrByRegionToday$陽性率推移 <- positiveRatioSparkline
print("テーブル作成")
totalToday <- paste(sprintf("%06d", total), total, today, sep = "|")
mergeDt <- data.table(
region = names(total),
count = total,
today = today,
totalToday = totalToday,
untilToday = untilToday,
diff = diffSparkline,
dischargeDiff = "",
detailBullet = "",
death = deathByRegion$values,
zeroContinuousDay = zeroContinuousDay$values,
doubleTimeDay = doubleTimeDay
)
mergeDt <- merge(mergeDt, totalDischarged, all.x = T, sort = F)
signateSub <- provinceAttr[, .(都道府県略称, 人口)]
colnames(signateSub) <- c("region", "population")
mergeDt <- merge(mergeDt, signateSub, all.x = T, sort = F)
mergeDt[, perMillion := round(count / (population / 1000000), 0)]
mergeDt[, perMillionDeath := round(death / (population / 1000000), 0)]
for (i in mergeDt$region) {
mergeDt[region == i]$dischargeDiff <- dischargedDiffSparkline[i][[1]]
mergeDt[region == i]$detailBullet <- detailSparkLine[i][[1]]
}
# グルーピング
groupList <- list(
"北海道・東北" = provinceAttr[都道府県コード %in% 1:7]$都道府県略称,
"関東" = provinceAttr[都道府県コード %in% 8:14]$都道府県略称,
"中部" = provinceAttr[都道府県コード %in% 15:23]$都道府県略称,
"近畿" = provinceAttr[都道府県コード %in% 24:30]$都道府県略称,
"中国" = provinceAttr[都道府県コード %in% 31:35]$都道府県略称,
"四国" = provinceAttr[都道府県コード %in% 36:39]$都道府県略称,
"九州・沖縄" = provinceAttr[都道府県コード %in% 40:47]$都道府県略称,
"他" = colnames(byDate)[(ncol(byDate) - 3):ncol(byDate)]
)
mergeDt$group = ""
for (i in seq(nrow(mergeDt))) {
mergeDt[i]$group <- names(which(lapply(groupList, function(x) { mergeDt$region[i] %in% x }) == T))
}
# 面積あたりの感染者数
area <- fread(paste0(DATA_PATH, "Collection/area.csv"))
area[, 都道府県略称 := 都道府県]
area[, 都道府県略称 := gsub("県", "", 都道府県略称)]
area[, 都道府県略称 := gsub("府", "", 都道府県略称)]
area[, 都道府県略称 := gsub("東京都", "東京", 都道府県略称)]
mergeDt <- merge(mergeDt, area, by.x = "region", by.y = "都道府県略称", all.x = T, no.dups = T, sort = F)
mergeDt[, perArea := round(sqrt(可住地面積 / count), 2)]
mergeDt[, `:=` (コード = NULL, 都道府県 = NULL, 可住地面積 = NULL, 可住地面積割合 = NULL, 宅地面積 = NULL, 宅地面積割合 = NULL)]
pcrByRegionToday[, `:=` (dischargedDiff = NULL)]
mergeDt <- merge(mergeDt, pcrByRegionToday, by.x = "region", by.y = "都道府県名", all.x = T, no.dups = T, sort = F)
active <- mergeDt$陽性者 - mergeDt$退院者 - ifelse(is.na(mergeDt$死亡者), 0, mergeDt$死亡者)
mergeDt[, `:=` (日付 = NULL, 陽性者 = NULL, 入院中 = NULL, 退院者 = NULL, 死亡者 = NULL, 確認中 = NULL, 分類 = NULL)]
mergeDt[, 百万人あたり := round(検査人数 / (population / 1000000), 0)]
mergeDt[, population := NULL]
# 現在患者数
mergeDt$active <- active
mergeDt[active < 0, active := 0] # チャーター便の単独対応
mergeDt[region == "クルーズ船", active := active - 40] # クルーズ船の単独対応
# 13個特定警戒都道府県
alertPref <-
c(
# "東京",
# "大阪",
# "北海道",
# "茨城",
# "埼玉",
# "千葉",
# "神奈川",
# "石川",
# "岐阜",
# "愛知",
# "京都",
# "兵庫",
# "福岡"
)
for(i in seq(nrow(mergeDt))) {
if (mergeDt[i]$region %in% alertPref) {
mergeDt[i]$region <- paste0("<i style='color:#DD4B39;' class=\"fa fa-exclamation-triangle\"></i>", "<span style='float:right;'>", mergeDt[i]$region, "</span>")
} else if (mergeDt[i]$active == 0 && !is.na(mergeDt[i]$active)) {
mergeDt[i]$region <- paste0("<i style='color:#01A65A;' class=\"fa fa-check-circle\"></i>", "<span style='float:right;'>", mergeDt[i]$region, "</span>")
} else {
mergeDt[i]$region <- paste0("<span style='float:right;'>", mergeDt[i]$region, "</span>")
}
}
# 自治体名前ソート用
prefNameId <- sprintf('%02d', seq(2:ncol(byDate)))
mergeDt[, region := paste0(prefNameId, "|", region)]
# オーダー
# setorder(mergeDt, - count)
# 読み取り時のエラーを回避するため
mergeDt[, diff := gsub("\\n", "", diff)]
mergeDt[, dischargeDiff := gsub("\\n", "", dischargeDiff)]
mergeDt[, detailBullet := gsub("\\n", "", detailBullet)]
mergeDt[, 検査数推移 := gsub("\\n", "", 検査数推移)]
mergeDt[, 陽性率推移 := gsub("\\n", "", 陽性率推移)]
# クルーズ船とチャーター便データ除外
# mergeDt <- mergeDt[!grepl(pattern = paste0(lang[[langCode]][35:36], collapse = "|"), x = mergeDt$region)]
print("テーブル出力")
fwrite(x = mergeDt, file = paste0(DATA_PATH, "Generated/resultSummaryTable.ja.csv"), sep = "@", quote = F)
source(file = "00_System/CreateTable.Translate.R")
# ====マップ用のデータ作成====
dt <- data.frame(date = byDate$date)
for (i in 2:ncol(byDate)) {
dt[, i] <- cumsum(byDate[, i, with = F])
}
dt <- reshape2::melt(dt, id.vars = "date")
dt <- data.table(dt)
mapDt <- dt[!(variable %in% c("クルーズ船", "伊客船", "チャーター便", "検疫職員"))]
# マップデータ用意
mapDt <- merge(x = mapDt, y = provinceCode, by.x = "variable", by.y = "name-ja", all = T)
mapDt <- merge(x = mapDt, y = provinceAttr, by.x = "variable", by.y = "都道府県略称", all = T)
# 必要なカラムを保存
mapDt <- mapDt[, .(date, variable, 都道府県, `name-en`, value, regions, lat, lng)]
# カラム名変更
colnames(mapDt) <- c("date", "ja", "full_ja", "en", "count", "regions", "lat", "lng")
fwrite(x = mapDt, file = paste0(DATA_PATH, "result.map.csv"))
|
## ---- geographic-WGS84, echo=FALSE, message=FALSE, results='hide'--------
# read grat shapefile
worldGrat30 <- readOGR(dsn="../../Global/Boundaries/ne_110m_graticules_all",
layer="ne_110m_graticules_30")
# convert to dataframe
worldGrat30_df <- fortify(worldGrat30)
#import box
wgs84Box <- readOGR("../../Global/Boundaries/ne_110m_graticules_all",
layer="ne_110m_wgs84_bounding_box")
wgs84Box_df<- fortify(wgs84Box)
#plot data
ggplot(wgs84Box_df, aes(long,lat, group=group)) +
geom_polygon(fill="white") +
xlab("Longitude (Degrees)") + ylab("Latitude (Degrees)") +
ggtitle("World Map - Geographic WGS84 (lat/lon)") +
geom_polygon(data=worldBound_df, aes(long,lat, group=group, fill=hole))+
geom_path(data=worldGrat30, aes(long, lat, group=group, fill=NULL), linetype="dashed", color="grey50") +
labs(title="World map + graticule (longlat)") +
coord_equal() +
scale_fill_manual(values=c("black", "white"), guide="none") # change colors &
|
/code/R/dc-spatio-temporal-intro/05-geographic-vs-projected-CRS.R
|
no_license
|
statkclee/NEON-R-Spatio-Temporal-Data-and-Management-Intro
|
R
| false | false | 1,008 |
r
|
## ---- geographic-WGS84, echo=FALSE, message=FALSE, results='hide'--------
# read grat shapefile
worldGrat30 <- readOGR(dsn="../../Global/Boundaries/ne_110m_graticules_all",
layer="ne_110m_graticules_30")
# convert to dataframe
worldGrat30_df <- fortify(worldGrat30)
#import box
wgs84Box <- readOGR("../../Global/Boundaries/ne_110m_graticules_all",
layer="ne_110m_wgs84_bounding_box")
wgs84Box_df<- fortify(wgs84Box)
#plot data
ggplot(wgs84Box_df, aes(long,lat, group=group)) +
geom_polygon(fill="white") +
xlab("Longitude (Degrees)") + ylab("Latitude (Degrees)") +
ggtitle("World Map - Geographic WGS84 (lat/lon)") +
geom_polygon(data=worldBound_df, aes(long,lat, group=group, fill=hole))+
geom_path(data=worldGrat30, aes(long, lat, group=group, fill=NULL), linetype="dashed", color="grey50") +
labs(title="World map + graticule (longlat)") +
coord_equal() +
scale_fill_manual(values=c("black", "white"), guide="none") # change colors &
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{rx_state}
\alias{rx_state}
\title{State regex}
\format{A character string (length 1).}
\usage{
rx_state
}
\description{
The regex string to extract state string preceding ZIP code.
}
\keyword{datasets}
|
/man/rx_state.Rd
|
permissive
|
Yanqi-Xu/campfin
|
R
| false | true | 308 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{rx_state}
\alias{rx_state}
\title{State regex}
\format{A character string (length 1).}
\usage{
rx_state
}
\description{
The regex string to extract state string preceding ZIP code.
}
\keyword{datasets}
|
shinyUI(
fluidPage(
# output
plotOutput("grafico"),
# código para aparecer uma imagem
div(img(src = "img_maneira.png", width = "50%"), style = "text-align: center"),
br(), br(),
# código para baixar um arquivo
a(href = "pdf_interessante.pdf", "Clique aqui", target="_blank"), "parar baixar um pdf interessante."
)
)
|
/shiny/leitura e imagens/ui.R
|
no_license
|
daianemarcolino/dataVisualizationR
|
R
| false | false | 385 |
r
|
shinyUI(
fluidPage(
# output
plotOutput("grafico"),
# código para aparecer uma imagem
div(img(src = "img_maneira.png", width = "50%"), style = "text-align: center"),
br(), br(),
# código para baixar um arquivo
a(href = "pdf_interessante.pdf", "Clique aqui", target="_blank"), "parar baixar um pdf interessante."
)
)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/5.2-build.R
\name{buildANN}
\alias{buildANN}
\title{Build Artificial Neural Network Model}
\usage{
buildANN(object, top = 0, ...)
}
\arguments{
\item{object}{An \code{ExprsArray} object. The training set.}
\item{top}{A numeric scalar or character vector. A numeric scalar indicates
the number of top features that should undergo feature selection. A character vector
indicates specifically which features by name should undergo feature selection.
Set \code{top = 0} to include all features. A numeric vector can also be used
to indicate specific features by location, similar to a character vector.}
\item{...}{Arguments passed to the detailed function.}
}
\value{
Returns an \code{ExprsModel} object.
}
\description{
\code{buildANN} builds a model using the \code{nnet} function
from the \code{nnet} package.
}
|
/man/buildANN.Rd
|
no_license
|
tpq/exprso
|
R
| false | true | 893 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/5.2-build.R
\name{buildANN}
\alias{buildANN}
\title{Build Artificial Neural Network Model}
\usage{
buildANN(object, top = 0, ...)
}
\arguments{
\item{object}{An \code{ExprsArray} object. The training set.}
\item{top}{A numeric scalar or character vector. A numeric scalar indicates
the number of top features that should undergo feature selection. A character vector
indicates specifically which features by name should undergo feature selection.
Set \code{top = 0} to include all features. A numeric vector can also be used
to indicate specific features by location, similar to a character vector.}
\item{...}{Arguments passed to the detailed function.}
}
\value{
Returns an \code{ExprsModel} object.
}
\description{
\code{buildANN} builds a model using the \code{nnet} function
from the \code{nnet} package.
}
|
library("magrittr")
# helper to shoot a review
webshoot_review <- function(review_url, package_name, path){
comment_id <- stringr::str_replace(review_url, ".*issuecomment", "issuecomment")
webshot::webshot(review_url,
selector = ".js-comment-container",
file = paste0(package, ".png"))
}
# helper to shoot the whole thread
webshoot_thread <- function(issue_url, package_name, path){
webshot::webshot(issue_url,
selector = "#show_issue",
file = paste0(path, package, "_whole_issue.png"))
}
# helper to shoot the upper info
webshoot_upper <- function(issue_url, package_name, path){
webshot::webshot(issue_url,
selector = "#partial-discussion-header",
file = paste0(path, package, "_upper.png"),
expand = c(10, 10, 600, 10))
}
# helper to shoot the first answer
webshoot_first_response <- function(issue_url, package_name, path){
webshot::webshot(issue_url,
selector = ".js-comment-container:nth-of-type(2)",
file = paste0(path, package, "_first_response.png"),
expand = c(10, 10, 10, 10))
}
shoot_package_onboarding <- function(package_name, path = "screenshots/"){
# airtable data
airtable <- airtabler::airtable("appZIB8hgtvjoV99D", "Reviews")
airtable <- airtable$Reviews$select_all()
review_info <- dplyr::filter(airtable, package == package_name)
issue_url <- dplyr::pull(review_info, onboarding_url) %>% unique()
review_urls <- dplyr::pull(review_info, review_url)
webshoot_thread(issue_url, package_name, path)
webshoot_meta(issue_url, package_name, path)
purrr::walk(review_urls, webshoot_review, package_name, path)
}
|
/B_analysts_sources_github/maelle/shoot_onboarding/webshoot_onboarding.R
|
no_license
|
Irbis3/crantasticScrapper
|
R
| false | false | 1,753 |
r
|
library("magrittr")
# helper to shoot a review
webshoot_review <- function(review_url, package_name, path){
comment_id <- stringr::str_replace(review_url, ".*issuecomment", "issuecomment")
webshot::webshot(review_url,
selector = ".js-comment-container",
file = paste0(package, ".png"))
}
# helper to shoot the whole thread
webshoot_thread <- function(issue_url, package_name, path){
webshot::webshot(issue_url,
selector = "#show_issue",
file = paste0(path, package, "_whole_issue.png"))
}
# helper to shoot the upper info
webshoot_upper <- function(issue_url, package_name, path){
webshot::webshot(issue_url,
selector = "#partial-discussion-header",
file = paste0(path, package, "_upper.png"),
expand = c(10, 10, 600, 10))
}
# helper to shoot the first answer
webshoot_first_response <- function(issue_url, package_name, path){
webshot::webshot(issue_url,
selector = ".js-comment-container:nth-of-type(2)",
file = paste0(path, package, "_first_response.png"),
expand = c(10, 10, 10, 10))
}
shoot_package_onboarding <- function(package_name, path = "screenshots/"){
# airtable data
airtable <- airtabler::airtable("appZIB8hgtvjoV99D", "Reviews")
airtable <- airtable$Reviews$select_all()
review_info <- dplyr::filter(airtable, package == package_name)
issue_url <- dplyr::pull(review_info, onboarding_url) %>% unique()
review_urls <- dplyr::pull(review_info, review_url)
webshoot_thread(issue_url, package_name, path)
webshoot_meta(issue_url, package_name, path)
purrr::walk(review_urls, webshoot_review, package_name, path)
}
|
#Example 3, section 4.2, page 230
#if u=(2,3,-1,2) is a vector in R4 and c=-2, then find c*u :
u<-c(2,3,-1,2)
c=-2
final<- c*u
print(final)
|
/ashiq/R codes/chapter 4/example3_sec4_2.R
|
no_license
|
sahridhaya/BitPlease
|
R
| false | false | 141 |
r
|
#Example 3, section 4.2, page 230
#if u=(2,3,-1,2) is a vector in R4 and c=-2, then find c*u :
u<-c(2,3,-1,2)
c=-2
final<- c*u
print(final)
|
#' @title Sample Data for Multivariate Small Area Estimation with Difference Benchmarking with clustering
#' @description Dataset to simulate difference benchmarking of Multivariate Fay Herriot model for non-sampled area using clustering
#' This data is generated base on multivariate Fay Herriot model by these following steps:
#' \enumerate{
#' \item Generate explanatory variables \code{X1 and X2}. Take \eqn{\mu_{X1}}{\muX1} = \eqn{\mu_{X1}}{\muX1} = 10, \eqn{\sigma_{X11}}{\sigmaX11}=1, \eqn{\sigma_{X2}}{\sigmaX22}=2, and \eqn{\rho_{x}}{\rhox}= 1/2.
#' \cr Sampling error \code{e} is generated with the following \eqn{\sigma_{e11}}{\sigmae11} = 0.15, \eqn{\sigma_{e22}}{\sigmae22} = 0.25, \eqn{\sigma_{e33}}{\sigmae33} = 0.35, and \eqn{\rho_{e}}{\rhoe} = 1/2.
#' \cr For random effect \code{u}, we set \eqn{\sigma_{u11}}{\sigmau11}= 0.2, \eqn{\sigma_{u22}}{\sigmau22}= 0.6, and \eqn{\sigma_{u33}}{\sigmau33}= 1.8.
#' \cr For the weight we generate \code{w1 w2 w3} by set the \code{w1 ~ U(25,30)} , \code{w2 ~ U(25,30)}, \code{w3 ~ U(25,30)}
#' \cr Calculate direct estimation \code{Y1 Y2 Y3} where \eqn{Y_{i}}{Yi} = \eqn{X * \beta + u_{i} + e_{i}}{X\beta+ui+ei}
#' \cr \code{cl1 cl2 cl3} were obtained using K-Means clustering from the explanatory variables.
#' \item Then combine the direct estimations \code{Y1 Y2 Y3}, explanatory variables \code{X1 X2}, weights \code{w1 w2 w3}, and sampling varians covarians \code{v1 v12 v13 v2 v23 v3} in a data frame then named as datamsaeDB
#' }
#'
#' @format A data frame with 30 rows and 18 variables:
#' \describe{
#' \item{clY1}{cluster information of Y1}
#' \item{clY2}{cluster information of Y2}
#' \item{clY3}{cluster information of Y3}
#' \item{nonsample}{A column with logical values, \code{TRUE} if the area is non-sampled}
#' \item{Y1}{Direct Estimation of Y1}
#' \item{Y2}{Direct Estimation of Y2}
#' \item{Y3}{Direct Estimation of Y3}
#' \item{X1}{Auxiliary variable of X1}
#' \item{X2}{Auxiliary variable of X2}
#' \item{w1}{Known proportion of units in small areas of Y1}
#' \item{w2}{Known proportion of units in small areas of Y2}
#' \item{w3}{Known proportion of units in small areas of Y3}
#' \item{v1}{Sampling Variance of Y1}
#' \item{v12}{Sampling Covariance of Y1 and Y2}
#' \item{v13}{Sampling Covariance of Y1 and Y3}
#' \item{v2}{Sampling Variance of Y2}
#' \item{v23}{Sampling Covariance of Y2 and Y3}
#' \item{v3}{Sampling Variance of Y3}
#' }
#'
"datamsaeDBns"
|
/R/datamsaeDBns.R
|
no_license
|
cran/msaeDB
|
R
| false | false | 2,542 |
r
|
#' @title Sample Data for Multivariate Small Area Estimation with Difference Benchmarking with clustering
#' @description Dataset to simulate difference benchmarking of Multivariate Fay Herriot model for non-sampled area using clustering
#' This data is generated base on multivariate Fay Herriot model by these following steps:
#' \enumerate{
#' \item Generate explanatory variables \code{X1 and X2}. Take \eqn{\mu_{X1}}{\muX1} = \eqn{\mu_{X1}}{\muX1} = 10, \eqn{\sigma_{X11}}{\sigmaX11}=1, \eqn{\sigma_{X2}}{\sigmaX22}=2, and \eqn{\rho_{x}}{\rhox}= 1/2.
#' \cr Sampling error \code{e} is generated with the following \eqn{\sigma_{e11}}{\sigmae11} = 0.15, \eqn{\sigma_{e22}}{\sigmae22} = 0.25, \eqn{\sigma_{e33}}{\sigmae33} = 0.35, and \eqn{\rho_{e}}{\rhoe} = 1/2.
#' \cr For random effect \code{u}, we set \eqn{\sigma_{u11}}{\sigmau11}= 0.2, \eqn{\sigma_{u22}}{\sigmau22}= 0.6, and \eqn{\sigma_{u33}}{\sigmau33}= 1.8.
#' \cr For the weight we generate \code{w1 w2 w3} by set the \code{w1 ~ U(25,30)} , \code{w2 ~ U(25,30)}, \code{w3 ~ U(25,30)}
#' \cr Calculate direct estimation \code{Y1 Y2 Y3} where \eqn{Y_{i}}{Yi} = \eqn{X * \beta + u_{i} + e_{i}}{X\beta+ui+ei}
#' \cr \code{cl1 cl2 cl3} were obtained using K-Means clustering from the explanatory variables.
#' \item Then combine the direct estimations \code{Y1 Y2 Y3}, explanatory variables \code{X1 X2}, weights \code{w1 w2 w3}, and sampling varians covarians \code{v1 v12 v13 v2 v23 v3} in a data frame then named as datamsaeDB
#' }
#'
#' @format A data frame with 30 rows and 18 variables:
#' \describe{
#' \item{clY1}{cluster information of Y1}
#' \item{clY2}{cluster information of Y2}
#' \item{clY3}{cluster information of Y3}
#' \item{nonsample}{A column with logical values, \code{TRUE} if the area is non-sampled}
#' \item{Y1}{Direct Estimation of Y1}
#' \item{Y2}{Direct Estimation of Y2}
#' \item{Y3}{Direct Estimation of Y3}
#' \item{X1}{Auxiliary variable of X1}
#' \item{X2}{Auxiliary variable of X2}
#' \item{w1}{Known proportion of units in small areas of Y1}
#' \item{w2}{Known proportion of units in small areas of Y2}
#' \item{w3}{Known proportion of units in small areas of Y3}
#' \item{v1}{Sampling Variance of Y1}
#' \item{v12}{Sampling Covariance of Y1 and Y2}
#' \item{v13}{Sampling Covariance of Y1 and Y3}
#' \item{v2}{Sampling Variance of Y2}
#' \item{v23}{Sampling Covariance of Y2 and Y3}
#' \item{v3}{Sampling Variance of Y3}
#' }
#'
"datamsaeDBns"
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/profanity_by.R
\name{profanity_by}
\alias{profanity_by}
\title{Profanity Rate By Groups}
\usage{
profanity_by(text.var, by = NULL, group.names, ...)
}
\arguments{
\item{text.var}{The text variable. Also takes a \code{profanityr} or
\code{profanity_by} object.}
\item{by}{The grouping variable(s). Default \code{NULL} uses the original
row/element indices; if you used a column of 12 rows for \code{text.var}
these 12 rows will be used as the grouping variable. Also takes a single
grouping variable or a list of 1 or more grouping variables.}
\item{group.names}{A vector of names that corresponds to group. Generally
for internal use.}
\item{\ldots}{Other arguments passed to \code{\link[sentimentr]{profanity}}.}
}
\value{
Returns a \pkg{data.table} with grouping variables plus:
\itemize{
\item element_id - The id number of the original vector passed to \code{profanity}
\item sentence_id - The id number of the sentences within each \code{element_id}
\item word_count - Word count \code{\link[base]{sum}}med by grouping variable
\item profanity_count - The number of profanities used by grouping variable
\item sd - Standard deviation (\code{\link[stats]{sd}}) of the sentence level profanity rate by grouping variable
\item ave_profanity - Profanity rate
}
}
\description{
Approximate the profanity of text by grouping variable(s). For a
full description of the profanity detection algorithm see
\code{\link[sentimentr]{profanity}}. See \code{\link[sentimentr]{profanity}}
for more details about the algorithm, the profanity/valence shifter keys
that can be passed into the function, and other arguments that can be passed.
}
\section{Chaining}{
See the \code{\link[sentimentr]{sentiment_by}} for details about \pkg{sentimentr} chaining.
}
\examples{
\dontrun{
bw <- sample(lexicon::profanity_alvarez, 4)
mytext <- c(
sprintf('do you like this \%s? It is \%s. But I hate really bad dogs', bw[1], bw[2]),
'I am the best friend.',
NA,
sprintf('I \%s hate this \%s', bw[3], bw[4]),
"Do you really like it? I'm not happy"
)
## works on a character vector but not the preferred method avoiding the
## repeated cost of doing sentence boundary disambiguation every time
## `profanity` is run
profanity(mytext)
profanity_by(mytext)
## preferred method avoiding paying the cost
mytext <- get_sentences(mytext)
profanity_by(mytext)
get_sentences(profanity_by(mytext))
(myprofanity <- profanity_by(mytext))
stats::setNames(get_sentences(profanity_by(mytext)),
round(myprofanity[["ave_profanity"]], 3))
brady <- get_sentences(crowdflower_deflategate)
library(data.table)
bp <- profanity_by(brady)
crowdflower_deflategate[bp[ave_profanity > 0,]$element_id, ]
vulgars <- bp[["ave_profanity"]] > 0
stats::setNames(get_sentences(bp)[vulgars],
round(bp[["ave_profanity"]][vulgars], 3))
bt <- data.table(crowdflower_deflategate)[,
source := ifelse(grepl('^RT', text), 'retweet', 'OP')][,
belichick := grepl('\\\\bb[A-Za-z]+l[A-Za-z]*ch', text, ignore.case = TRUE)][]
prof_bel <- with(bt, profanity_by(text, by = list(source, belichick)))
plot(prof_bel)
}
}
\seealso{
Other profanity functions:
\code{\link{profanity}()}
}
\concept{profanity functions}
|
/man/profanity_by.Rd
|
no_license
|
cran/sentimentr
|
R
| false | true | 3,394 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/profanity_by.R
\name{profanity_by}
\alias{profanity_by}
\title{Profanity Rate By Groups}
\usage{
profanity_by(text.var, by = NULL, group.names, ...)
}
\arguments{
\item{text.var}{The text variable. Also takes a \code{profanityr} or
\code{profanity_by} object.}
\item{by}{The grouping variable(s). Default \code{NULL} uses the original
row/element indices; if you used a column of 12 rows for \code{text.var}
these 12 rows will be used as the grouping variable. Also takes a single
grouping variable or a list of 1 or more grouping variables.}
\item{group.names}{A vector of names that corresponds to group. Generally
for internal use.}
\item{\ldots}{Other arguments passed to \code{\link[sentimentr]{profanity}}.}
}
\value{
Returns a \pkg{data.table} with grouping variables plus:
\itemize{
\item element_id - The id number of the original vector passed to \code{profanity}
\item sentence_id - The id number of the sentences within each \code{element_id}
\item word_count - Word count \code{\link[base]{sum}}med by grouping variable
\item profanity_count - The number of profanities used by grouping variable
\item sd - Standard deviation (\code{\link[stats]{sd}}) of the sentence level profanity rate by grouping variable
\item ave_profanity - Profanity rate
}
}
\description{
Approximate the profanity of text by grouping variable(s). For a
full description of the profanity detection algorithm see
\code{\link[sentimentr]{profanity}}. See \code{\link[sentimentr]{profanity}}
for more details about the algorithm, the profanity/valence shifter keys
that can be passed into the function, and other arguments that can be passed.
}
\section{Chaining}{
See the \code{\link[sentimentr]{sentiment_by}} for details about \pkg{sentimentr} chaining.
}
\examples{
\dontrun{
bw <- sample(lexicon::profanity_alvarez, 4)
mytext <- c(
sprintf('do you like this \%s? It is \%s. But I hate really bad dogs', bw[1], bw[2]),
'I am the best friend.',
NA,
sprintf('I \%s hate this \%s', bw[3], bw[4]),
"Do you really like it? I'm not happy"
)
## works on a character vector but not the preferred method avoiding the
## repeated cost of doing sentence boundary disambiguation every time
## `profanity` is run
profanity(mytext)
profanity_by(mytext)
## preferred method avoiding paying the cost
mytext <- get_sentences(mytext)
profanity_by(mytext)
get_sentences(profanity_by(mytext))
(myprofanity <- profanity_by(mytext))
stats::setNames(get_sentences(profanity_by(mytext)),
round(myprofanity[["ave_profanity"]], 3))
brady <- get_sentences(crowdflower_deflategate)
library(data.table)
bp <- profanity_by(brady)
crowdflower_deflategate[bp[ave_profanity > 0,]$element_id, ]
vulgars <- bp[["ave_profanity"]] > 0
stats::setNames(get_sentences(bp)[vulgars],
round(bp[["ave_profanity"]][vulgars], 3))
bt <- data.table(crowdflower_deflategate)[,
source := ifelse(grepl('^RT', text), 'retweet', 'OP')][,
belichick := grepl('\\\\bb[A-Za-z]+l[A-Za-z]*ch', text, ignore.case = TRUE)][]
prof_bel <- with(bt, profanity_by(text, by = list(source, belichick)))
plot(prof_bel)
}
}
\seealso{
Other profanity functions:
\code{\link{profanity}()}
}
\concept{profanity functions}
|
#' Groups
#'
#' Function to get groups of users.
#'
#' @param email Email
#' @param apikey Your api key from settings in interface
#' @param domain Your domain in AmoCRM (xxx in xxx.amocrm.ru)
#' @param auth_list List with auth data, you can build from AmoAuthList
#' @include query_functions.R
#' @include unnest_functions.R
#' @export
#' @importFrom stats setNames
#' @importFrom httr GET
#' @importFrom httr content
#' @import dplyr
#' @return You'll get a groups.
#'
#' @references
#' Please \strong{READ} this:
#' \href{https://github.com/grkhr/amocrm/blob/master/md/AmoGroups.md}{Function documentation in Russian on GitHub}
#'
#' Also nice to read:
#' \href{https://www.amocrm.ru/developers/content/api/account}{AmoCRM official documentation}
#'
#' @examples
#' \dontrun{
#' groups <- AmoGroups(auth_list = auth_list)
#' }
AmoGroups <- function(email = NULL, apikey = NULL, domain = NULL, auth_list = NULL) {
if (!is.null(auth_list)) {
email <- auth_list$email
apikey <- auth_list$apikey
domain <- auth_list$domain
}
auth <- AmoAuth(email, apikey, domain, verbose=F)
if (auth != T) stop(auth)
answer <- GET(paste0("https://",domain,".amocrm.ru/api/v2/account?with=groups"))
dataRaw <- content(answer, "parsed", "application/json")
groups <- dataRaw$`_embedded`$groups
groups_df <- bind_rows(groups) %>% as.data.frame()
return(groups_df)
}
|
/R/AmoGroups.R
|
no_license
|
grkhr/amocrm
|
R
| false | false | 1,378 |
r
|
#' Groups
#'
#' Function to get groups of users.
#'
#' @param email Email
#' @param apikey Your api key from settings in interface
#' @param domain Your domain in AmoCRM (xxx in xxx.amocrm.ru)
#' @param auth_list List with auth data, you can build from AmoAuthList
#' @include query_functions.R
#' @include unnest_functions.R
#' @export
#' @importFrom stats setNames
#' @importFrom httr GET
#' @importFrom httr content
#' @import dplyr
#' @return You'll get a groups.
#'
#' @references
#' Please \strong{READ} this:
#' \href{https://github.com/grkhr/amocrm/blob/master/md/AmoGroups.md}{Function documentation in Russian on GitHub}
#'
#' Also nice to read:
#' \href{https://www.amocrm.ru/developers/content/api/account}{AmoCRM official documentation}
#'
#' @examples
#' \dontrun{
#' groups <- AmoGroups(auth_list = auth_list)
#' }
AmoGroups <- function(email = NULL, apikey = NULL, domain = NULL, auth_list = NULL) {
if (!is.null(auth_list)) {
email <- auth_list$email
apikey <- auth_list$apikey
domain <- auth_list$domain
}
auth <- AmoAuth(email, apikey, domain, verbose=F)
if (auth != T) stop(auth)
answer <- GET(paste0("https://",domain,".amocrm.ru/api/v2/account?with=groups"))
dataRaw <- content(answer, "parsed", "application/json")
groups <- dataRaw$`_embedded`$groups
groups_df <- bind_rows(groups) %>% as.data.frame()
return(groups_df)
}
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/auth_request.R
\name{auth_put_post_delete}
\alias{auth_put_post_delete}
\title{POST, PUT, or DELETE a resource with authenticated credentials.}
\usage{
auth_put_post_delete(method, url, encode = "multipart", body = as.list(NA))
}
\arguments{
\item{method}{a string indicating which HTTP method to use (post, put, or delete)}
\item{url}{The URL to be accessed via authenticated PUT}
\item{encode}{the type of encoding to use for the PUT body, defaults to 'multipart'}
\item{body}{a list of data to be included in the body of the PUT request}
}
\value{
the response object from the method
}
\description{
POST, PUT, or DELETE data to a URL using an HTTP request using authentication credentials
provided in a client certificate. Authenticated access depends on the suggested
PKIplus package. If the PKIplus package is not installed, then the request fails.
}
|
/dataone/man/auth_put_post_delete.Rd
|
permissive
|
KillEdision/rdataone
|
R
| false | false | 948 |
rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/auth_request.R
\name{auth_put_post_delete}
\alias{auth_put_post_delete}
\title{POST, PUT, or DELETE a resource with authenticated credentials.}
\usage{
auth_put_post_delete(method, url, encode = "multipart", body = as.list(NA))
}
\arguments{
\item{method}{a string indicating which HTTP method to use (post, put, or delete)}
\item{url}{The URL to be accessed via authenticated PUT}
\item{encode}{the type of encoding to use for the PUT body, defaults to 'multipart'}
\item{body}{a list of data to be included in the body of the PUT request}
}
\value{
the response object from the method
}
\description{
POST, PUT, or DELETE data to a URL using an HTTP request using authentication credentials
provided in a client certificate. Authenticated access depends on the suggested
PKIplus package. If the PKIplus package is not installed, then the request fails.
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/read_msgf_data.R
\name{read_msgf_data}
\alias{read_msgf_data}
\title{Reading MSGF Results. Generic.}
\usage{
read_msgf_data(path_to_MSGF_results, suffix = NULL)
}
\arguments{
\item{path_to_MSGF_results}{(path string) to directory with MSGF results for all datasets}
}
\value{
(MSnID) MSnID object
}
\description{
Reading MSGF output from a single directory
}
\examples{
path_to_MSGF_results <- system.file("extdata/global/msgf_output", package = "PlexedPiperTestData")
msnid <- read_msgf_data(path_to_MSGF_results)
print(msnid)
head(MSnID::psms(msnid))
}
|
/man/read_msgf_data.Rd
|
no_license
|
vladpetyuk/PlexedPiper
|
R
| false | true | 633 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/read_msgf_data.R
\name{read_msgf_data}
\alias{read_msgf_data}
\title{Reading MSGF Results. Generic.}
\usage{
read_msgf_data(path_to_MSGF_results, suffix = NULL)
}
\arguments{
\item{path_to_MSGF_results}{(path string) to directory with MSGF results for all datasets}
}
\value{
(MSnID) MSnID object
}
\description{
Reading MSGF output from a single directory
}
\examples{
path_to_MSGF_results <- system.file("extdata/global/msgf_output", package = "PlexedPiperTestData")
msnid <- read_msgf_data(path_to_MSGF_results)
print(msnid)
head(MSnID::psms(msnid))
}
|
# 3行以下で終わる分析の例:集計編|R言語ではじめるプログラミングとデータ分析
# 馬場真哉
# サンプルサイズの取得 --------------------------------------------------------------
# サンプルサイズの取得
sales_beef <- read.csv("2-9-1-sales-beef.csv")
nrow(sales_beef)
# 度数 ------------------------------------------------------------
# 2カテゴリの場合の度数
fish_chicken <- read.csv("2-9-5-fish-chicken.csv")
table(fish_chicken$sex)
table(fish_chicken$choice)
# memo:3カテゴリ以上の場合
favorite_food <- read.csv("2-9-6-favorite-food.csv")
table(favorite_food$sex)
table(favorite_food$favorite_food)
# 累積度数 -----------------------------------------------------------------
# 累積度数
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq <- table(favorite_food$favorite_food)
cumsum(freq)
# memo:関数を入れ子にする
# 以下のコードでも実行結果は変わらない
favorite_food <- read.csv("2-9-6-favorite-food.csv")
cumsum(table(favorite_food$favorite_food))
# memo:cumsum関数の補足
# 「1」が5つあるデータの累積値
cumsum(c(1, 1, 1, 1, 1))
# 「1から5の等差数列」の累積値
cumsum(c(1, 2, 3, 4, 5))
# 相対度数 --------------------------------------------------------------------
# 相対度数
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq <- table(favorite_food$favorite_food)
prop.table(freq)
# memo:prop.tableの補足
# prop.tableの例
prop.table(c(20, 30, 50))
# prop.tableを使わない方法
c(20, 30, 50) / sum(c(20, 30, 50))
# memo:累積相対度数
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq <- table(favorite_food$favorite_food)
prop <- prop.table(freq)
cumsum(prop)
# クロス集計 ----------------------------------------------------------
# 2カテゴリの場合のクロス集計
fish_chicken <- read.csv("2-9-5-fish-chicken.csv")
table(fish_chicken)
# memo:3カテゴリの場合
favorite_food <- read.csv("2-9-6-favorite-food.csv")
table(favorite_food)
# memo:prob.tableを使って合計値が1になるようにする
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq_cross <- table(favorite_food)
prop.table(freq_cross)
# クロス集計表⇔整然データの変換 ---------------------------------------------------------
# クロス集計表をデータフレームにする
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq_cross <- table(favorite_food)
as.data.frame(freq_cross)
# memo:データフレームをまたクロス集計表に変換する
# クロス集計(xtabs)
freq_df <- as.data.frame(freq_cross)
xtabs(
formula = Freq ~ sex + favorite_food,
data = freq_df
)
# 合計値 ---------------------------------------------------------------------
# 合計値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
sum(sales_beef$beef)
# memo:2列以上あるデータに対する合計値の計算
sales_population <- read.csv("2-9-3-sales-population.csv")
sum(sales_population$beef)
sum(sales_population$resident_population)
# 平均値 ---------------------------------------------------------------------
# 平均値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
mean(sales_beef$beef)
# memo:mean関数を使わないで平均値を計算する
sum_sales <- sum(sales_beef$beef)
sample_size <- nrow(sales_beef)
sum_sales / sample_size
# 不偏分散 --------------------------------------------------------------------
# 不偏分散
sales_beef <- read.csv("2-9-1-sales-beef.csv")
var(sales_beef$beef)
# memo:var関数を使わないで不偏分散を計算する
mean_sales <- mean(sales_beef$beef)
sample_size <- nrow(sales_beef)
sum((sales_beef$beef - mean_sales) ^ 2) / (sample_size - 1)
# 標準偏差 --------------------------------------------------------------------
# 標準偏差
sales_beef <- read.csv("2-9-1-sales-beef.csv")
sd(sales_beef$beef)
# memo:sd関数を使わないで標準偏差を計算する
var_sales <- var(sales_beef$beef)
sqrt(var_sales)
# データの並び替え ----------------------------------------------------------------
# データの並び替え
sales_beef <- read.csv("2-9-1-sales-beef.csv")
sort(sales_beef$beef)
# memo:降順に並び替える
sort(sales_beef$beef, decreasing = TRUE)
# memo:順位の取得と並び替え
# 元のデータ
sales_beef$beef
# 順位(昇順)
order(sales_beef$beef)
# 並び替え
sales_beef$beef[order(sales_beef$beef)]
# 最小・最大値 ------------------------------------------------------------------
# 最小・最大値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
min(sales_beef$beef)
max(sales_beef$beef)
# memo:データの範囲を取得する
range_sales <- range(sales_beef$beef)
range_sales
# 最小値の取得
range_sales[1]
# memo:minやmax関数を使わないで、最小・最大を求める
sort(sales_beef$beef)[1]
sort(sales_beef$beef)[nrow(sales_beef)]
# 中央値 ---------------------------------------------------------------------
# 中央値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
median(sales_beef$beef)
# memo:中央値の計算例
median(1:5)
median(1:4)
(30.9 + 31.6) / 2
# sort関数を使って中央値を求める
n <- nrow(sales_beef)
sorted <- sort(sales_beef$beef)
(sorted[n / 2] + sorted[(n / 2) + 1]) / 2
# パーセント点 ------------------------------------------------------------------
# パーセント点(分位点)
sales_beef <- read.csv("2-9-1-sales-beef.csv")
quantile(sales_beef$beef, probs = c(0.25, 0.75))
# memo:quantile関数を使って中央値を求める
quantile(sales_beef$beef, probs = 0.5)
# memo:パーセント点の計算例
quantile(0:100, probs = c(0.25, 0.5, 0.75))
quantile(0:10, probs = c(0.25, 0.5, 0.75))
# 四分位範囲 -------------------------------------------------------------------
# 四分位範囲
sales_beef <- read.csv("2-9-1-sales-beef.csv")
IQR(sales_beef$beef)
# memo:IQR関数を使わないで四分位範囲を求める
q1 <- quantile(sales_beef$beef, probs = 0.25)
q3 <- quantile(sales_beef$beef, probs = 0.75)
q3 - q1
# 要約統計量 -------------------------------------------------------------------
# 要約統計量
sales_beef <- read.csv("2-9-1-sales-beef.csv")
summary(sales_beef$beef)
# memo:列名を指定しない場合
summary(sales_beef)
# memo:2列以上のデータに対して適用した場合
sales_meat <- read.csv("2-9-4-sales-meat.csv")
summary(sales_meat)
# 行や列に対する一括処理(apply) ---------------------------------------------------------------
# 列に対する一括処理
sales_population <- read.csv("2-9-3-sales-population.csv")
apply(sales_population, 2, sum)
# memo:行に対する一括処理
sales_population <- read.csv("2-9-3-sales-population.csv")
apply(sales_population, 1, sum)
# リストに対する一括処理(lapply) -----------------------------------------------------
# リストを入力、リストを出力
sales_population <- read.csv("2-9-3-sales-population.csv")
lapply(sales_population, sum)
# リストに対する一括処理(sapply) -----------------------------------------------------
# リストを入力、行列を出力
sales_population <- read.csv("2-9-3-sales-population.csv")
sapply(sales_population, sum)
# カテゴリ別の集計値(tapply) --------------------------------------------------------------
# カテゴリ別の平均値
sales_meat <- read.csv("2-9-4-sales-meat.csv")
tapply(sales_meat$sales, sales_meat$category, mean)
# memo:カテゴリ別の要約統計量
tapply(sales_meat$sales, sales_meat$category, summary)
# 2つ以上のカテゴリ別に分けた集計値(tapply) -------------------------------------------------------
# ウールの種類別、糸の張力別の切断数合計値を得る
tapply(warpbreaks$breaks,
list(warpbreaks$wool, warpbreaks$tension),
mean)
|
/book-data/2-9-analysis-example-aggregation.R
|
no_license
|
katzkawai/book-r-programming-intro
|
R
| false | false | 7,975 |
r
|
# 3行以下で終わる分析の例:集計編|R言語ではじめるプログラミングとデータ分析
# 馬場真哉
# サンプルサイズの取得 --------------------------------------------------------------
# サンプルサイズの取得
sales_beef <- read.csv("2-9-1-sales-beef.csv")
nrow(sales_beef)
# 度数 ------------------------------------------------------------
# 2カテゴリの場合の度数
fish_chicken <- read.csv("2-9-5-fish-chicken.csv")
table(fish_chicken$sex)
table(fish_chicken$choice)
# memo:3カテゴリ以上の場合
favorite_food <- read.csv("2-9-6-favorite-food.csv")
table(favorite_food$sex)
table(favorite_food$favorite_food)
# 累積度数 -----------------------------------------------------------------
# 累積度数
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq <- table(favorite_food$favorite_food)
cumsum(freq)
# memo:関数を入れ子にする
# 以下のコードでも実行結果は変わらない
favorite_food <- read.csv("2-9-6-favorite-food.csv")
cumsum(table(favorite_food$favorite_food))
# memo:cumsum関数の補足
# 「1」が5つあるデータの累積値
cumsum(c(1, 1, 1, 1, 1))
# 「1から5の等差数列」の累積値
cumsum(c(1, 2, 3, 4, 5))
# 相対度数 --------------------------------------------------------------------
# 相対度数
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq <- table(favorite_food$favorite_food)
prop.table(freq)
# memo:prop.tableの補足
# prop.tableの例
prop.table(c(20, 30, 50))
# prop.tableを使わない方法
c(20, 30, 50) / sum(c(20, 30, 50))
# memo:累積相対度数
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq <- table(favorite_food$favorite_food)
prop <- prop.table(freq)
cumsum(prop)
# クロス集計 ----------------------------------------------------------
# 2カテゴリの場合のクロス集計
fish_chicken <- read.csv("2-9-5-fish-chicken.csv")
table(fish_chicken)
# memo:3カテゴリの場合
favorite_food <- read.csv("2-9-6-favorite-food.csv")
table(favorite_food)
# memo:prob.tableを使って合計値が1になるようにする
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq_cross <- table(favorite_food)
prop.table(freq_cross)
# クロス集計表⇔整然データの変換 ---------------------------------------------------------
# クロス集計表をデータフレームにする
favorite_food <- read.csv("2-9-6-favorite-food.csv")
freq_cross <- table(favorite_food)
as.data.frame(freq_cross)
# memo:データフレームをまたクロス集計表に変換する
# クロス集計(xtabs)
freq_df <- as.data.frame(freq_cross)
xtabs(
formula = Freq ~ sex + favorite_food,
data = freq_df
)
# 合計値 ---------------------------------------------------------------------
# 合計値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
sum(sales_beef$beef)
# memo:2列以上あるデータに対する合計値の計算
sales_population <- read.csv("2-9-3-sales-population.csv")
sum(sales_population$beef)
sum(sales_population$resident_population)
# 平均値 ---------------------------------------------------------------------
# 平均値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
mean(sales_beef$beef)
# memo:mean関数を使わないで平均値を計算する
sum_sales <- sum(sales_beef$beef)
sample_size <- nrow(sales_beef)
sum_sales / sample_size
# 不偏分散 --------------------------------------------------------------------
# 不偏分散
sales_beef <- read.csv("2-9-1-sales-beef.csv")
var(sales_beef$beef)
# memo:var関数を使わないで不偏分散を計算する
mean_sales <- mean(sales_beef$beef)
sample_size <- nrow(sales_beef)
sum((sales_beef$beef - mean_sales) ^ 2) / (sample_size - 1)
# 標準偏差 --------------------------------------------------------------------
# 標準偏差
sales_beef <- read.csv("2-9-1-sales-beef.csv")
sd(sales_beef$beef)
# memo:sd関数を使わないで標準偏差を計算する
var_sales <- var(sales_beef$beef)
sqrt(var_sales)
# データの並び替え ----------------------------------------------------------------
# データの並び替え
sales_beef <- read.csv("2-9-1-sales-beef.csv")
sort(sales_beef$beef)
# memo:降順に並び替える
sort(sales_beef$beef, decreasing = TRUE)
# memo:順位の取得と並び替え
# 元のデータ
sales_beef$beef
# 順位(昇順)
order(sales_beef$beef)
# 並び替え
sales_beef$beef[order(sales_beef$beef)]
# 最小・最大値 ------------------------------------------------------------------
# 最小・最大値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
min(sales_beef$beef)
max(sales_beef$beef)
# memo:データの範囲を取得する
range_sales <- range(sales_beef$beef)
range_sales
# 最小値の取得
range_sales[1]
# memo:minやmax関数を使わないで、最小・最大を求める
sort(sales_beef$beef)[1]
sort(sales_beef$beef)[nrow(sales_beef)]
# 中央値 ---------------------------------------------------------------------
# 中央値
sales_beef <- read.csv("2-9-1-sales-beef.csv")
median(sales_beef$beef)
# memo:中央値の計算例
median(1:5)
median(1:4)
(30.9 + 31.6) / 2
# sort関数を使って中央値を求める
n <- nrow(sales_beef)
sorted <- sort(sales_beef$beef)
(sorted[n / 2] + sorted[(n / 2) + 1]) / 2
# パーセント点 ------------------------------------------------------------------
# パーセント点(分位点)
sales_beef <- read.csv("2-9-1-sales-beef.csv")
quantile(sales_beef$beef, probs = c(0.25, 0.75))
# memo:quantile関数を使って中央値を求める
quantile(sales_beef$beef, probs = 0.5)
# memo:パーセント点の計算例
quantile(0:100, probs = c(0.25, 0.5, 0.75))
quantile(0:10, probs = c(0.25, 0.5, 0.75))
# 四分位範囲 -------------------------------------------------------------------
# 四分位範囲
sales_beef <- read.csv("2-9-1-sales-beef.csv")
IQR(sales_beef$beef)
# memo:IQR関数を使わないで四分位範囲を求める
q1 <- quantile(sales_beef$beef, probs = 0.25)
q3 <- quantile(sales_beef$beef, probs = 0.75)
q3 - q1
# 要約統計量 -------------------------------------------------------------------
# 要約統計量
sales_beef <- read.csv("2-9-1-sales-beef.csv")
summary(sales_beef$beef)
# memo:列名を指定しない場合
summary(sales_beef)
# memo:2列以上のデータに対して適用した場合
sales_meat <- read.csv("2-9-4-sales-meat.csv")
summary(sales_meat)
# 行や列に対する一括処理(apply) ---------------------------------------------------------------
# 列に対する一括処理
sales_population <- read.csv("2-9-3-sales-population.csv")
apply(sales_population, 2, sum)
# memo:行に対する一括処理
sales_population <- read.csv("2-9-3-sales-population.csv")
apply(sales_population, 1, sum)
# リストに対する一括処理(lapply) -----------------------------------------------------
# リストを入力、リストを出力
sales_population <- read.csv("2-9-3-sales-population.csv")
lapply(sales_population, sum)
# リストに対する一括処理(sapply) -----------------------------------------------------
# リストを入力、行列を出力
sales_population <- read.csv("2-9-3-sales-population.csv")
sapply(sales_population, sum)
# カテゴリ別の集計値(tapply) --------------------------------------------------------------
# カテゴリ別の平均値
sales_meat <- read.csv("2-9-4-sales-meat.csv")
tapply(sales_meat$sales, sales_meat$category, mean)
# memo:カテゴリ別の要約統計量
tapply(sales_meat$sales, sales_meat$category, summary)
# 2つ以上のカテゴリ別に分けた集計値(tapply) -------------------------------------------------------
# ウールの種類別、糸の張力別の切断数合計値を得る
tapply(warpbreaks$breaks,
list(warpbreaks$wool, warpbreaks$tension),
mean)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/animate_annual.R
\name{animate_annual}
\alias{animate_annual}
\title{Plot an animation of forest change within a given area of interest (AOI)}
\usage{
animate_annual(aoi, gfc_stack, out_dir = getwd(),
out_basename = "gfc_animation", site_name = "", type = "html",
height = 3, width = 3, dpi = 300)
}
\arguments{
\item{aoi}{one or more AOI polygons as a \code{SpatialPolygonsDataFrame}
object. If there is a 'label' field in the dataframe, it will be used to
label the polygons in the plots. If the AOI is not in the WGS84 geographic
coordinate system, it will be reprojected to WGS84.}
\item{gfc_stack}{a GFC product subset as a
\code{RasterStack} (as output by \code{\link{annual_stack}})}
\item{out_dir}{folder for animation output}
\item{out_basename}{basename to use when naming animation files}
\item{site_name}{name of the site (used in making title)}
\item{type}{type of animation to make. Can be either "gif" or "html"}
\item{height}{desired height of the animation GIF in inches}
\item{width}{desired width of the animation GIF in inches}
\item{dpi}{dots per inch for the output image}
}
\description{
Produces an animation of annual forest change in the area bounded by the
extent of a given AOI, or AOIs. The AOI polygon(s) is(are) also plotted on
the image. The \code{gfc_stack} must be pre-calculated using the
\code{\link{annual_stack}} function. The animation can be either an animated
GIF (if \code{type} is set to 'gif') or a series of '.png' files with a
corresponding '.html' webpage showing a simple viewer and the forest change
animation (if \code{type} is set to 'html'). The HTML option is recommended
as it requires no additional software to produce it. The animated GIF option
will only work if the imagemagicK software package is installed beforehand
(this is done outside of R).
}
\seealso{
\code{\link{annual_stack}}
}
|
/man/animate_annual.Rd
|
no_license
|
yfinegold/gfcanalysis
|
R
| false | true | 1,953 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/animate_annual.R
\name{animate_annual}
\alias{animate_annual}
\title{Plot an animation of forest change within a given area of interest (AOI)}
\usage{
animate_annual(aoi, gfc_stack, out_dir = getwd(),
out_basename = "gfc_animation", site_name = "", type = "html",
height = 3, width = 3, dpi = 300)
}
\arguments{
\item{aoi}{one or more AOI polygons as a \code{SpatialPolygonsDataFrame}
object. If there is a 'label' field in the dataframe, it will be used to
label the polygons in the plots. If the AOI is not in the WGS84 geographic
coordinate system, it will be reprojected to WGS84.}
\item{gfc_stack}{a GFC product subset as a
\code{RasterStack} (as output by \code{\link{annual_stack}})}
\item{out_dir}{folder for animation output}
\item{out_basename}{basename to use when naming animation files}
\item{site_name}{name of the site (used in making title)}
\item{type}{type of animation to make. Can be either "gif" or "html"}
\item{height}{desired height of the animation GIF in inches}
\item{width}{desired width of the animation GIF in inches}
\item{dpi}{dots per inch for the output image}
}
\description{
Produces an animation of annual forest change in the area bounded by the
extent of a given AOI, or AOIs. The AOI polygon(s) is(are) also plotted on
the image. The \code{gfc_stack} must be pre-calculated using the
\code{\link{annual_stack}} function. The animation can be either an animated
GIF (if \code{type} is set to 'gif') or a series of '.png' files with a
corresponding '.html' webpage showing a simple viewer and the forest change
animation (if \code{type} is set to 'html'). The HTML option is recommended
as it requires no additional software to produce it. The animated GIF option
will only work if the imagemagicK software package is installed beforehand
(this is done outside of R).
}
\seealso{
\code{\link{annual_stack}}
}
|
load_dataset <- function(fname)
{
read.csv(fname,header = TRUE,stringsAsFactors = FALSE)
}
|
/load_dataset.R
|
no_license
|
JAIR-VG/dissreg-tools
|
R
| false | false | 98 |
r
|
load_dataset <- function(fname)
{
read.csv(fname,header = TRUE,stringsAsFactors = FALSE)
}
|
# Table of VaR estimates for historical and simulated data
H2_VaR_table <- function(){
# Create matrix with the relative VaR estimates then name rows and cols
H2_VaR <- matrix(c(H2_VaR_1W_sim, H2_VaR_1M_sim, H2_VaR_2M_sim, H2_VaR_1W_hist, H2_VaR_1M_hist, H2_VaR_2M_hist, abs(H2_VaR_1W_hist - H2_VaR_1W_sim), abs(H2_VaR_1M_hist - H2_VaR_1M_sim), abs(H2_VaR_2M_hist - H2_VaR_2M_sim) ), nrow=3, ncol=3,byrow=TRUE)
H2_VaR <- H2_VaR %>% as.data.frame()
colnames(H2_VaR) <- c("One-Week", "One-Month", "Two-Months")
rownames(H2_VaR) <- c("FHS","Historical", "Difference")
# convert matrix into table
xtable(H2_VaR, caption = NULL, label = NULL, align = NULL, digits = 5,
display = NULL, auto = FALSE)
}
|
/Final Project/code/H2_VaR_table.R
|
no_license
|
Richard19leigh93/Financial-Econometrics
|
R
| false | false | 738 |
r
|
# Table of VaR estimates for historical and simulated data
H2_VaR_table <- function(){
# Create matrix with the relative VaR estimates then name rows and cols
H2_VaR <- matrix(c(H2_VaR_1W_sim, H2_VaR_1M_sim, H2_VaR_2M_sim, H2_VaR_1W_hist, H2_VaR_1M_hist, H2_VaR_2M_hist, abs(H2_VaR_1W_hist - H2_VaR_1W_sim), abs(H2_VaR_1M_hist - H2_VaR_1M_sim), abs(H2_VaR_2M_hist - H2_VaR_2M_sim) ), nrow=3, ncol=3,byrow=TRUE)
H2_VaR <- H2_VaR %>% as.data.frame()
colnames(H2_VaR) <- c("One-Week", "One-Month", "Two-Months")
rownames(H2_VaR) <- c("FHS","Historical", "Difference")
# convert matrix into table
xtable(H2_VaR, caption = NULL, label = NULL, align = NULL, digits = 5,
display = NULL, auto = FALSE)
}
|
/多元统计分析/综合评价.r
|
no_license
|
tiny-boat/my-R-code
|
R
| false | false | 2,060 |
r
| ||
#################Dotplots for SNPS###################
#takes 2 columns: gene and position.
Pathway_histo_pi3k_Akt <- read.csv(file = "Pathway_histo_pi3k-Akt.csv")
e <- ggplot(Pathway_histo_pi3k_Akt, aes(x = Gene, y = Distance, fill = Gene))
#genes
e + geom_dotplot(binaxis = "y", stackdir = "center", aes(color = Gene), method = "histodot", dotsize = 0.5, stackratio = 0.9, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic"), axis.text=element_text(size=15, colour = "#595959"), axis.title=element_text(size=16, face = "bold", , colour = "#595959" )) +
labs(y = "Distance from gene", x = "Gene", title = "PI3K-AKT") +
coord_flip() +
ylim(-100000, 100000)
#GWAS
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", aes(color = GWAS), fill = "white", method = "histodot", dotsize = 0.15, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
#violin genes
e + geom_violin(trim = FALSE) +
geom_dotplot(binaxis = "y", stackdir ="center", dotsize = 0.5, show.legend = FALSE) +
stat_summary(fun.data = "mean_sdl", fun.args = list(mult = 1), geom = "pointrange", color = "red", shape = 11) +
labs(y = "Distance from gene", x = "Gene", title = "PI3K-AKT") +
theme(axis.text.x = element_text(face = "italic")) +
ylim(-100000, 100000)
#HOFR
e <- ggplot(HOFR_dot, aes(x = GWAS, y = HOFR_dot$`Distance from Gene`))
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", color = "#B93442", fill = "#B93442", method = "histodot", dotsize = 0.3, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
#CH
e <- ggplot(CH_dot, aes(x = GWAS, y = CH_dot$`Distance from Gene`))
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", color = "#3453B9", fill = "#3453B9", method = "histodot", dotsize = 0.3, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
#LM
e <- ggplot(LM_dot, aes(x = GWAS, y = LM_dot$`Distance from Gene`))
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", color = "#3BAF43", fill = "#3BAF43", method = "histodot", dotsize = 0.3, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
|
/R_scripts/PLOT_Dot_plot_SNPS.R
|
no_license
|
ThomasHall1688/Bovine_multi-omic_integration
|
R
| false | false | 2,858 |
r
|
#################Dotplots for SNPS###################
#takes 2 columns: gene and position.
Pathway_histo_pi3k_Akt <- read.csv(file = "Pathway_histo_pi3k-Akt.csv")
e <- ggplot(Pathway_histo_pi3k_Akt, aes(x = Gene, y = Distance, fill = Gene))
#genes
e + geom_dotplot(binaxis = "y", stackdir = "center", aes(color = Gene), method = "histodot", dotsize = 0.5, stackratio = 0.9, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic"), axis.text=element_text(size=15, colour = "#595959"), axis.title=element_text(size=16, face = "bold", , colour = "#595959" )) +
labs(y = "Distance from gene", x = "Gene", title = "PI3K-AKT") +
coord_flip() +
ylim(-100000, 100000)
#GWAS
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", aes(color = GWAS), fill = "white", method = "histodot", dotsize = 0.15, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
#violin genes
e + geom_violin(trim = FALSE) +
geom_dotplot(binaxis = "y", stackdir ="center", dotsize = 0.5, show.legend = FALSE) +
stat_summary(fun.data = "mean_sdl", fun.args = list(mult = 1), geom = "pointrange", color = "red", shape = 11) +
labs(y = "Distance from gene", x = "Gene", title = "PI3K-AKT") +
theme(axis.text.x = element_text(face = "italic")) +
ylim(-100000, 100000)
#HOFR
e <- ggplot(HOFR_dot, aes(x = GWAS, y = HOFR_dot$`Distance from Gene`))
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", color = "#B93442", fill = "#B93442", method = "histodot", dotsize = 0.3, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
#CH
e <- ggplot(CH_dot, aes(x = GWAS, y = CH_dot$`Distance from Gene`))
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", color = "#3453B9", fill = "#3453B9", method = "histodot", dotsize = 0.3, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
#LM
e <- ggplot(LM_dot, aes(x = GWAS, y = LM_dot$`Distance from Gene`))
e + geom_dotplot(binaxis = "y", stackdir = "centerwhole", color = "#3BAF43", fill = "#3BAF43", method = "histodot", dotsize = 0.3, stackratio = 1, show.legend = FALSE) +
# theme_minimal() +
theme_clean() +
theme(axis.text.y = element_text(face = "italic")) +
labs(y = "Distance from gene", x = "GWAS", title = "SNP Distribution") +
coord_flip() +
ylim(-100000, 100000)
|
# Text analysis of Trump's tweets confirms he writes only the (angrier) Android half
# By David Robinson at http://varianceexplained.org/r/trump-tweets/
# Code: https://github.com/dgrtwo/dgrtwo.github.com/blob/master/_R/2016-08-09-trump-tweets.Rmd
library(dplyr)
library(purrr)
library(twitteR)
library(tidyr)
library(lubridate)
library(scales)
#library(magrittr)
library(stringr)
library(tidytext)
library(broom)
library(ggplot2)
# You'd need to set global options with an authenticated app
#setup_twitter_oauth(getOption("twitter_consumer_key"),
#getOption("twitter_consumer_secret"),
#getOption("twitter_access_token"),
#getOption("twitter_access_token_secret"))
# We can request only 3200 tweets at a time; it will return fewer
# depending on the API
#trump_tweets <- userTimeline("realDonaldTrump", n = 3200)
#trump_tweets_df <- tbl_df(map_df(trump_tweets, as.data.frame))
load(url("http://varianceexplained.org/files/trump_tweets_df.rda"))
tweets <- trump_tweets_df %>%
select(id, statusSource, text, created) %>%
tidyr::extract(statusSource, "source", "Twitter for (.*?)<") %>%
filter(source %in% c("iPhone", "Android"))
# Hour of day
tweets %>%
count(source, hour = hour(with_tz(created, "EST"))) %>%
mutate(percent = n / sum(n)) %>%
ggplot(aes(hour, percent, color = source)) +
geom_line() +
scale_y_continuous(labels = percent_format()) +
labs(x = "Hour of day (EST)",
y = "% of tweets",
color = "")
# tweets start with "
tweets %>%
count(source,
quoted = ifelse(str_detect(text, '^"'), "Quoted", "Not quoted")) %>%
ggplot(aes(source, n, fill = quoted)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "", y = "Number of tweets", fill = "") +
ggtitle('Whether tweets start with a quotation mark (")')
# Picture/link
tweet_picture_counts <- tweets %>%
filter(!str_detect(text, '^"')) %>%
count(source,
picture = ifelse(str_detect(text, "t.co"),
"Picture/link", "No picture/link"))
ggplot(tweet_picture_counts, aes(source, n, fill = picture)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "", y = "Number of tweets", fill = "")
spr <- tweet_picture_counts %>%
spread(source, n) %>%
mutate_each(funs(. / sum(.)), Android, iPhone)
rr <- spr$iPhone[2] / spr$Android[2]
# comparison of words
reg <- "([^A-Za-z\\d#@']|'(?![A-Za-z\\d#@]))"
tweet_words <- tweets %>%
filter(!str_detect(text, '^"')) %>%
mutate(text = str_replace_all(text, "https://t.co/[A-Za-z\\d]+|&", "")) %>%
unnest_tokens(word, text, token = "regex", pattern = reg) %>%
filter(!word %in% stop_words$word,
str_detect(word, "[a-z]"))
tweet_words
tweet_words %>%
count(word, sort = TRUE) %>%
head(20) %>%
mutate(word = reorder(word, n)) %>%
ggplot(aes(word, n)) +
geom_bar(stat = "identity") +
ylab("Occurrences") +
coord_flip()
# phone ratio
android_iphone_ratios <- tweet_words %>%
count(word, source) %>%
filter(sum(n) >= 5) %>%
spread(source, n, fill = 0) %>%
ungroup() %>%
mutate_each(funs((. + 1) / sum(. + 1)), -word) %>%
mutate(logratio = log2(Android / iPhone)) %>%
arrange(desc(logratio))
android_iphone_ratios %>%
group_by(logratio > 0) %>%
top_n(15, abs(logratio)) %>%
ungroup() %>%
mutate(word = reorder(word, logratio)) %>%
ggplot(aes(word, logratio, fill = logratio < 0)) +
geom_bar(stat = "identity") +
coord_flip() +
ylab("Android / iPhone log ratio") +
scale_fill_manual(name = "", labels = c("Android", "iPhone"),
values = c("red", "lightblue"))
# sentiment
nrc <- sentiments %>%
filter(lexicon == "nrc") %>%
dplyr::select(word, sentiment)
nrc
# sentiment by phone
sources <- tweet_words %>%
group_by(source) %>%
mutate(total_words = n()) %>%
ungroup() %>%
distinct(id, source, total_words)
by_source_sentiment <- tweet_words %>%
inner_join(nrc, by = "word") %>%
count(sentiment, id) %>%
ungroup() %>%
complete(sentiment, id, fill = list(n = 0)) %>%
inner_join(sources) %>%
group_by(source, sentiment, total_words) %>%
summarize(words = sum(n)) %>%
ungroup()
head(by_source_sentiment)
# We then want to measure how much more likely the Android account is to use an emotionally-charged term relative to the iPhone account. Since this is count data, we can use a Poisson test to measure the difference:
sentiment_differences <- by_source_sentiment %>%
group_by(sentiment) %>%
do(tidy(poisson.test(.$words, .$total_words)))
sentiment_differences
sentiment_differences %>%
ungroup() %>%
mutate(sentiment = reorder(sentiment, estimate)) %>%
mutate_each(funs(. - 1), estimate, conf.low, conf.high) %>%
ggplot(aes(estimate, sentiment)) +
geom_point() +
geom_errorbarh(aes(xmin = conf.low, xmax = conf.high)) +
scale_x_continuous(labels = percent_format()) +
labs(x = "% increase in Android relative to iPhone",
y = "Sentiment")
# We're especially interested in which words drove this different in sentiment. Let's consider the words with the largest changes within each category:
android_iphone_ratios %>%
inner_join(nrc, by = "word") %>%
filter(!sentiment %in% c("positive", "negative")) %>%
mutate(sentiment = reorder(sentiment, -logratio),
word = reorder(word, -logratio)) %>%
group_by(sentiment) %>%
top_n(10, abs(logratio)) %>%
ungroup() %>%
ggplot(aes(word, logratio, fill = logratio < 0)) +
facet_wrap(~ sentiment, scales = "free", nrow = 2) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(x = "", y = "Android / iPhone log ratio") +
scale_fill_manual(name = "", labels = c("Android", "iPhone"),
values = c("red", "lightblue"))
|
/has-new-digital-research-methods/1-donald-trump-tweet-analysis.r
|
no_license
|
peterdalle/presentations
|
R
| false | false | 5,772 |
r
|
# Text analysis of Trump's tweets confirms he writes only the (angrier) Android half
# By David Robinson at http://varianceexplained.org/r/trump-tweets/
# Code: https://github.com/dgrtwo/dgrtwo.github.com/blob/master/_R/2016-08-09-trump-tweets.Rmd
library(dplyr)
library(purrr)
library(twitteR)
library(tidyr)
library(lubridate)
library(scales)
#library(magrittr)
library(stringr)
library(tidytext)
library(broom)
library(ggplot2)
# You'd need to set global options with an authenticated app
#setup_twitter_oauth(getOption("twitter_consumer_key"),
#getOption("twitter_consumer_secret"),
#getOption("twitter_access_token"),
#getOption("twitter_access_token_secret"))
# We can request only 3200 tweets at a time; it will return fewer
# depending on the API
#trump_tweets <- userTimeline("realDonaldTrump", n = 3200)
#trump_tweets_df <- tbl_df(map_df(trump_tweets, as.data.frame))
load(url("http://varianceexplained.org/files/trump_tweets_df.rda"))
tweets <- trump_tweets_df %>%
select(id, statusSource, text, created) %>%
tidyr::extract(statusSource, "source", "Twitter for (.*?)<") %>%
filter(source %in% c("iPhone", "Android"))
# Hour of day
tweets %>%
count(source, hour = hour(with_tz(created, "EST"))) %>%
mutate(percent = n / sum(n)) %>%
ggplot(aes(hour, percent, color = source)) +
geom_line() +
scale_y_continuous(labels = percent_format()) +
labs(x = "Hour of day (EST)",
y = "% of tweets",
color = "")
# tweets start with "
tweets %>%
count(source,
quoted = ifelse(str_detect(text, '^"'), "Quoted", "Not quoted")) %>%
ggplot(aes(source, n, fill = quoted)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "", y = "Number of tweets", fill = "") +
ggtitle('Whether tweets start with a quotation mark (")')
# Picture/link
tweet_picture_counts <- tweets %>%
filter(!str_detect(text, '^"')) %>%
count(source,
picture = ifelse(str_detect(text, "t.co"),
"Picture/link", "No picture/link"))
ggplot(tweet_picture_counts, aes(source, n, fill = picture)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "", y = "Number of tweets", fill = "")
spr <- tweet_picture_counts %>%
spread(source, n) %>%
mutate_each(funs(. / sum(.)), Android, iPhone)
rr <- spr$iPhone[2] / spr$Android[2]
# comparison of words
reg <- "([^A-Za-z\\d#@']|'(?![A-Za-z\\d#@]))"
tweet_words <- tweets %>%
filter(!str_detect(text, '^"')) %>%
mutate(text = str_replace_all(text, "https://t.co/[A-Za-z\\d]+|&", "")) %>%
unnest_tokens(word, text, token = "regex", pattern = reg) %>%
filter(!word %in% stop_words$word,
str_detect(word, "[a-z]"))
tweet_words
tweet_words %>%
count(word, sort = TRUE) %>%
head(20) %>%
mutate(word = reorder(word, n)) %>%
ggplot(aes(word, n)) +
geom_bar(stat = "identity") +
ylab("Occurrences") +
coord_flip()
# phone ratio
android_iphone_ratios <- tweet_words %>%
count(word, source) %>%
filter(sum(n) >= 5) %>%
spread(source, n, fill = 0) %>%
ungroup() %>%
mutate_each(funs((. + 1) / sum(. + 1)), -word) %>%
mutate(logratio = log2(Android / iPhone)) %>%
arrange(desc(logratio))
android_iphone_ratios %>%
group_by(logratio > 0) %>%
top_n(15, abs(logratio)) %>%
ungroup() %>%
mutate(word = reorder(word, logratio)) %>%
ggplot(aes(word, logratio, fill = logratio < 0)) +
geom_bar(stat = "identity") +
coord_flip() +
ylab("Android / iPhone log ratio") +
scale_fill_manual(name = "", labels = c("Android", "iPhone"),
values = c("red", "lightblue"))
# sentiment
nrc <- sentiments %>%
filter(lexicon == "nrc") %>%
dplyr::select(word, sentiment)
nrc
# sentiment by phone
sources <- tweet_words %>%
group_by(source) %>%
mutate(total_words = n()) %>%
ungroup() %>%
distinct(id, source, total_words)
by_source_sentiment <- tweet_words %>%
inner_join(nrc, by = "word") %>%
count(sentiment, id) %>%
ungroup() %>%
complete(sentiment, id, fill = list(n = 0)) %>%
inner_join(sources) %>%
group_by(source, sentiment, total_words) %>%
summarize(words = sum(n)) %>%
ungroup()
head(by_source_sentiment)
# We then want to measure how much more likely the Android account is to use an emotionally-charged term relative to the iPhone account. Since this is count data, we can use a Poisson test to measure the difference:
sentiment_differences <- by_source_sentiment %>%
group_by(sentiment) %>%
do(tidy(poisson.test(.$words, .$total_words)))
sentiment_differences
sentiment_differences %>%
ungroup() %>%
mutate(sentiment = reorder(sentiment, estimate)) %>%
mutate_each(funs(. - 1), estimate, conf.low, conf.high) %>%
ggplot(aes(estimate, sentiment)) +
geom_point() +
geom_errorbarh(aes(xmin = conf.low, xmax = conf.high)) +
scale_x_continuous(labels = percent_format()) +
labs(x = "% increase in Android relative to iPhone",
y = "Sentiment")
# We're especially interested in which words drove this different in sentiment. Let's consider the words with the largest changes within each category:
android_iphone_ratios %>%
inner_join(nrc, by = "word") %>%
filter(!sentiment %in% c("positive", "negative")) %>%
mutate(sentiment = reorder(sentiment, -logratio),
word = reorder(word, -logratio)) %>%
group_by(sentiment) %>%
top_n(10, abs(logratio)) %>%
ungroup() %>%
ggplot(aes(word, logratio, fill = logratio < 0)) +
facet_wrap(~ sentiment, scales = "free", nrow = 2) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(x = "", y = "Android / iPhone log ratio") +
scale_fill_manual(name = "", labels = c("Android", "iPhone"),
values = c("red", "lightblue"))
|
#' Function to run CHILD from the R interface.
#'
#' The function executes a CHILD model run from the R console and creates a
#' S4-object \code{\link{CHILD}} with all output files. The function requires a
#' compiled version of CHILD and an appropriate input-file.
#'
#' Currently, this function is of preliminary stage. It requires a compiled
#' version of CHILD, present at a specified path or the current working
#' directory. Compiled versions for MS Windows 32 Bit and some Mac OS may be
#' downloaded from CSDMS (http://csdms.colorado.edu/wiki/Model:CHILD, scroll
#' down to download, fill the form fields, choose a recent release version and
#' you will find the compiled versions in ChildExercises/Executables_v10).
#' Existing output files will be overwritten without prompting, so be careful
#' and check before running.
#'
#' @param inputfile (character scalar) Name of the input file, with extention.
#'
#' @param outfiles (logical scalar) Argument to keep (\code{\link{TRUE}}) or
#' delete (\code{\link{FALSE}}) the original output files of the CHILD run,
#' default is \code{\link{FALSE}}.
#'
#' @param path (character scalar) Optional path to the compiled CHILD
#' executable. If not specified, it is assumed that the executable is present
#' in the current working directory.
#'
#' @return A S4-object with all CHILD run output files.
#'
#' @author Michael Dietze
#' @seealso \code{\link{read.CHILD}}, \code{\link{read.IN}},
#' \code{\link{write.IN}}
#' @references CSDMS website. http://csdms.colorado.edu/wiki/Model:CHILD.\cr
#' Tucker, GE. 2010. CHILD Users Guide for version R9.4.1.
#' http://csdms.colorado.edu/mediawiki/images/Child_users_guide.pdf \cr Tucker,
#' GE., Lancaster, ST., Gasparini, NM., Bras, RL. 2001. The Channel-Hillslope
#' Integrated Landscape Development (CHILD) Model. In Harmon, RS., Doe, W.W.
#' III (eds). Landscape Erosion and Evolution Modeling. Kluwer Academic/Plenum
#' Publishers, pp. 349-388.
#' @keywords CHILD
#' @examples
#'
#' # To run example code uncomment it (delete hashes)
#'
#' # You will need a compiled version of CHILD either in
#' # the working directory or under a known path.
#'
#' # hillslope1 <- run.CHILD(dataset = "hillslope1",
#' # inputfile = "hillslope1.in")
#'
#'
#' @export run.CHILD
run.CHILD <- function(
inputfile,
outfiles = FALSE,
path
) {
## read model output name from in-file
infilecontent <- readLines(inputfile)
modelname = as.character(infilecontent[grep("OUTFILENAME:",
infilecontent) + 1])
## set path to child executable
if(missing(path) == TRUE) path <- ""
## run CHILD via system command
system(paste(path,
"child ",
inputfile,
sep = "")) # run child
## read output files to result variable
result <- read.CHILD(modelname)
## optionally, remove CHILD output files from working directory
if(outfiles == FALSE) {
filestoremove <- list.files()[grepl(modelname,
list.files(),
fixed = TRUE)]
filestoremove <- filestoremove[filestoremove != inputfile]
file.remove(c(filestoremove, "run.time"))
}
return(result)
}
|
/R/run.CHILD.R
|
no_license
|
coffeemuggler/RCHILD
|
R
| false | false | 3,208 |
r
|
#' Function to run CHILD from the R interface.
#'
#' The function executes a CHILD model run from the R console and creates a
#' S4-object \code{\link{CHILD}} with all output files. The function requires a
#' compiled version of CHILD and an appropriate input-file.
#'
#' Currently, this function is of preliminary stage. It requires a compiled
#' version of CHILD, present at a specified path or the current working
#' directory. Compiled versions for MS Windows 32 Bit and some Mac OS may be
#' downloaded from CSDMS (http://csdms.colorado.edu/wiki/Model:CHILD, scroll
#' down to download, fill the form fields, choose a recent release version and
#' you will find the compiled versions in ChildExercises/Executables_v10).
#' Existing output files will be overwritten without prompting, so be careful
#' and check before running.
#'
#' @param inputfile (character scalar) Name of the input file, with extention.
#'
#' @param outfiles (logical scalar) Argument to keep (\code{\link{TRUE}}) or
#' delete (\code{\link{FALSE}}) the original output files of the CHILD run,
#' default is \code{\link{FALSE}}.
#'
#' @param path (character scalar) Optional path to the compiled CHILD
#' executable. If not specified, it is assumed that the executable is present
#' in the current working directory.
#'
#' @return A S4-object with all CHILD run output files.
#'
#' @author Michael Dietze
#' @seealso \code{\link{read.CHILD}}, \code{\link{read.IN}},
#' \code{\link{write.IN}}
#' @references CSDMS website. http://csdms.colorado.edu/wiki/Model:CHILD.\cr
#' Tucker, GE. 2010. CHILD Users Guide for version R9.4.1.
#' http://csdms.colorado.edu/mediawiki/images/Child_users_guide.pdf \cr Tucker,
#' GE., Lancaster, ST., Gasparini, NM., Bras, RL. 2001. The Channel-Hillslope
#' Integrated Landscape Development (CHILD) Model. In Harmon, RS., Doe, W.W.
#' III (eds). Landscape Erosion and Evolution Modeling. Kluwer Academic/Plenum
#' Publishers, pp. 349-388.
#' @keywords CHILD
#' @examples
#'
#' # To run example code uncomment it (delete hashes)
#'
#' # You will need a compiled version of CHILD either in
#' # the working directory or under a known path.
#'
#' # hillslope1 <- run.CHILD(dataset = "hillslope1",
#' # inputfile = "hillslope1.in")
#'
#'
#' @export run.CHILD
run.CHILD <- function(
inputfile,
outfiles = FALSE,
path
) {
## read model output name from in-file
infilecontent <- readLines(inputfile)
modelname = as.character(infilecontent[grep("OUTFILENAME:",
infilecontent) + 1])
## set path to child executable
if(missing(path) == TRUE) path <- ""
## run CHILD via system command
system(paste(path,
"child ",
inputfile,
sep = "")) # run child
## read output files to result variable
result <- read.CHILD(modelname)
## optionally, remove CHILD output files from working directory
if(outfiles == FALSE) {
filestoremove <- list.files()[grepl(modelname,
list.files(),
fixed = TRUE)]
filestoremove <- filestoremove[filestoremove != inputfile]
file.remove(c(filestoremove, "run.time"))
}
return(result)
}
|
testlist <- list(metric = 0L, vec = NULL, vec = NULL, w_vec = structure(0, .Dim = c(1L, 1L)), y_vec = structure(c(5.6445088053016e-312, 7.2911220195564e-304, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(7L, 10L)))
result <- do.call(UniIsoRegression:::reg_2d,testlist)
str(result)
|
/UniIsoRegression/inst/testfiles/reg_2d/libFuzzer_reg_2d/reg_2d_valgrind_files/1612737061-test.R
|
no_license
|
akhikolla/updatedatatype-list1
|
R
| false | false | 453 |
r
|
testlist <- list(metric = 0L, vec = NULL, vec = NULL, w_vec = structure(0, .Dim = c(1L, 1L)), y_vec = structure(c(5.6445088053016e-312, 7.2911220195564e-304, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(7L, 10L)))
result <- do.call(UniIsoRegression:::reg_2d,testlist)
str(result)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/MizerParams-class.R
\name{emptyParams}
\alias{emptyParams}
\title{Create empty MizerParams object of the right size}
\usage{
emptyParams(
species_params,
gear_params = data.frame(),
no_w = 100,
min_w = 0.001,
max_w = NA,
min_w_pp = 1e-12
)
}
\arguments{
\item{species_params}{A data frame of species-specific parameter values.}
\item{gear_params}{A data frame with gear-specific parameter values.}
\item{no_w}{The number of size bins in the consumer spectrum.}
\item{min_w}{Sets the size of the eggs of all species for which this is not
given in the \code{w_min} column of the \code{species_params} dataframe.}
\item{max_w}{The largest size of the consumer spectrum. By default this is
set to the largest \code{w_inf} specified in the \code{species_params} data
frame.}
\item{min_w_pp}{The smallest size of the resource spectrum.}
}
\value{
An empty but valid MizerParams object
}
\description{
An internal function.
Sets up a valid \linkS4class{MizerParams} object with all the slots
initialised and given dimension names, but with some slots left empty. This
function is to be used by other functions to set up full parameter objects.
}
\section{Size grid}{
A size grid is created so that
the log-sizes are equally spaced. The spacing is chosen so that there will be
\code{no_w} fish size bins, with the smallest starting at \code{min_w} and the largest
starting at \code{max_w}. For \code{w_full} additional size bins are added below
\code{min_w}, with the same log size. The number of extra bins is such that
\code{min_w_pp} comes to lie within the smallest bin.
}
\section{Changes to species params}{
The \code{species_params} slot of the returned MizerParams object may differ
slightly from the data frame supplied as argument to this function because
default values are set for
\verb{w_min, w_inf, alpha, gear, interaction_resource}.
}
\seealso{
See \code{\link[=newMultispeciesParams]{newMultispeciesParams()}} for a function that fills
the slots left empty by this function.
}
|
/man/emptyParams.Rd
|
no_license
|
patricksykes/mizer
|
R
| false | true | 2,085 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/MizerParams-class.R
\name{emptyParams}
\alias{emptyParams}
\title{Create empty MizerParams object of the right size}
\usage{
emptyParams(
species_params,
gear_params = data.frame(),
no_w = 100,
min_w = 0.001,
max_w = NA,
min_w_pp = 1e-12
)
}
\arguments{
\item{species_params}{A data frame of species-specific parameter values.}
\item{gear_params}{A data frame with gear-specific parameter values.}
\item{no_w}{The number of size bins in the consumer spectrum.}
\item{min_w}{Sets the size of the eggs of all species for which this is not
given in the \code{w_min} column of the \code{species_params} dataframe.}
\item{max_w}{The largest size of the consumer spectrum. By default this is
set to the largest \code{w_inf} specified in the \code{species_params} data
frame.}
\item{min_w_pp}{The smallest size of the resource spectrum.}
}
\value{
An empty but valid MizerParams object
}
\description{
An internal function.
Sets up a valid \linkS4class{MizerParams} object with all the slots
initialised and given dimension names, but with some slots left empty. This
function is to be used by other functions to set up full parameter objects.
}
\section{Size grid}{
A size grid is created so that
the log-sizes are equally spaced. The spacing is chosen so that there will be
\code{no_w} fish size bins, with the smallest starting at \code{min_w} and the largest
starting at \code{max_w}. For \code{w_full} additional size bins are added below
\code{min_w}, with the same log size. The number of extra bins is such that
\code{min_w_pp} comes to lie within the smallest bin.
}
\section{Changes to species params}{
The \code{species_params} slot of the returned MizerParams object may differ
slightly from the data frame supplied as argument to this function because
default values are set for
\verb{w_min, w_inf, alpha, gear, interaction_resource}.
}
\seealso{
See \code{\link[=newMultispeciesParams]{newMultispeciesParams()}} for a function that fills
the slots left empty by this function.
}
|
testlist <- list(G = numeric(0), Rn = numeric(0), atmp = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ra = numeric(0), relh = -1.72131968218895e+83, rs = numeric(0), temp = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 9.66231645734968e+111, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545926e+139, 2.3317908961407e-93, 2.16562581831091e+161))
result <- do.call(meteor:::ET0_PenmanMonteith,testlist)
str(result)
|
/meteor/inst/testfiles/ET0_PenmanMonteith/AFL_ET0_PenmanMonteith/ET0_PenmanMonteith_valgrind_files/1615839057-test.R
|
no_license
|
akhikolla/updatedatatype-list3
|
R
| false | false | 826 |
r
|
testlist <- list(G = numeric(0), Rn = numeric(0), atmp = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ra = numeric(0), relh = -1.72131968218895e+83, rs = numeric(0), temp = c(8.5728629954997e-312, 1.56898424065867e+82, 8.96970809549085e-158, -1.3258495253834e-113, 2.79620616433656e-119, -6.80033518839696e+41, 2.68298522855314e-211, 1444042902784.06, 6.68889884134308e+51, -4.05003163986346e-308, -3.52601820453991e+43, -1.49815227045093e+197, -2.61605817623304e+76, -1.18078903777423e-90, 9.66231645734968e+111, -5.58551357556946e+160, 2.00994342527714e-162, 1.81541609400943e-79, 7.89363005545926e+139, 2.3317908961407e-93, 2.16562581831091e+161))
result <- do.call(meteor:::ET0_PenmanMonteith,testlist)
str(result)
|
# aggregate 연습문제
# aggregate(출력 열 ~ 기준 열, 데이터, 통계함수)
head(Fruits,3)
Fruits
ls(Fruits) # 필드명 출력
# 1. 과일별 판매액의 평균을 구하시오
aggregate(Sales ~ Fruit, Fruits, mean)
# 2. 과일별 비용의 최대값을 구하시오
aggregate(Expenses ~ Fruit, Fruits, max)
# 3. 과일별 수익의 최소값을 구하시오
aggregate(Profit ~ Fruit, Fruits, min)
# 4. 위치별 판매금액의 평균을 구하시오
aggregate(Sales ~ Location, Fruits, mean)
# 5. 과일별 수익의 합계를 구하시오
aggregate(Profit ~ Fruit, Fruits, sum)
# 6. 연도별 판매금액의 합계를 구하시오
aggregate(Sales ~ Year, Fruits, sum)
# 7. 과일별 평균 비용을 구하시오
aggregate(Expenses ~ Fruit, Fruits, mean)
# 8. 지역 + 과일별 수익의 평균을 구하시오
aggregate(Profit ~ Location, Fruits, mean)
# 9. 지역 + 연도별 판매액의 합계를 구하시오
aggregate(Sales ~ Location + Year, Fruits, sum)
# 10. 지역 + 과일별 비용의 합계를 구하시오
aggregate(Expenses ~ Location + Fruit, Fruits, sum)
# 11. 지역 + 연도별 수익의 최대값을 구하시오
aggregate(Profit ~ Location + Year, Fruits, max)
# aggregate() 연습문제2
# 1. 1-4호선승하차승객수.csv 파일을 df_subway로 불러오세요. (stringsAsFactors=F)
df_subway<-read.csv('data\\1-4호선승하차승객수.csv',stringsAsFactors=F)
View(df_subway)
ls(df_subway)
# 2. 노선 번호별 총 승차 인원수를 구하시오
aggregate(승차 ~ 노선번호, df_subway, sum)
# 3. 노선 번호별 총 하차 인원수를 구하시오
aggregate(하차 ~ 노선번호, df_subway, sum)
# 4. 노선 번호별 승차 인원수 평균을 구하시오
aggregate(승차 ~ 노선번호, df_subway, mean)
# 5. 노선 번호별 하차 인원수 최소값을 구하시오
aggregate(하차 ~ 노선번호, df_subway, min)
# 6. 노선 번호별 승차, 하차 각 최대값을 구하시오
aggregate(cbind(승차,하차) ~ 노선번호, df_subway, max)
# 7. 노선 번호별 승차, 하차 각 최소값을 구하시오
aggregate(cbind(승차,하차) ~ 노선번호, df_subway, min)
# 8. 노선 번호별 승하차 총 인원수를 구하시오
aggregate(승차+하차 ~ 노선번호, df_subway, sum)
# apply() 연습문제
# 1. data1.csv 파일을 data1으로 불러오세요
data1<-read.csv("data\\data1.csv", stringsAsFactors = F)
View(data1)
ls(data1)
# 2. 연도별 합계를 모두 구하시오
apply(data1[,-1],2,sum)
# 3. 연령별 합계를 모두 구하시오
apply(data1[,-1],1,sum)
# 4. 2008년부터 2012년까지 연도별 합계를 각각 구하시오
apply(data1[,10:14],2,sum)
apply(data1[,10:(length(data1)-1)],2,sum)
# 5. 2008년부터 2012년까지 연령별 합계를 각각 구하시오
apply(data1[,10:14],1,sum)
# 6. 2000년, 2005년, 2010년의 연도별 합계를 각각 구해 d1에 대입하시오
d1<-apply(data1[,c(2,7,12)],2,sum)
d1
# 7. 2000년, 2005년, 2010년의 연령별 합계를 각각 구해 d2에 대입하시오
d2<-apply(data1[,c(2,7,12)],1,sum)
d2
# sapply() 연습문제
# 1. 연도별 합계를 모두 구하시오
sapply(data1[,-1],sum)
class(sapply(data1[,-1],sum))
# 출력결과 numeric->벡터형태
# 2. 2008년부터 2012년까지 연도별 합계를 각각 구하시오
sapply(data1[,10:14],sum)
lapply(data1[,10:14],sum)
class(lapply(data1[,10:14],sum)) # list 형태
unlist(lapply(data1[,10:14],sum)) # 벡터 형태로
# 3. 2000년, 2005년, 2010년 연도별 합계를 각각 구하시오
sapply(data1[,c(2,7,12)],sum) # 벡터 형태로 출력됨
# apply() / sapply() / tapply() 연습문제
# 1. 1-4호선승하차승객수.csv 파일을 data2로 불러오세요
data2<-read.csv("data\\1-4호선승하차승객수.csv", stringsAsFactors=F)
View(data2)
attach(data2)
# 2. 노선 번호별 총 승차 인원수를 구하시오
tapply(승차,노선번호,sum)
# 3. 노선 번호별 총 하차 인원수를 구하시오
tapply(하차,노선번호,sum)
# 4. 노선 번호에 상관없이 총 승차 인원수 및 총 하차 인원수를 구하시오
apply(data2[,3:4],2,sum)
sapply(data2[,3:4],sum)
sapply(data2[3:4],sum) # sapply가 열 계산을 하기때문에 인덱싱에서 ,를 생략할수있다
# 5. 노선 번호별 총 승차 인원수 및 총 하차 인원수의 평균을 구하시오
tapply(승차,노선번호,mean)
tapply(하차,노선번호,mean)
# tapply(cbind(하차,승차),노선번호,mean) -> 에러 뜸
tapply(승차+하차, 노선번호, mean) # 총 승하차 인원의 노선별 평균
# 6. 노선 번호에 상관없이 승차 및 하차 인원수 최소값을 각각 구하시오
sapply(data2[3:4],min)
sapply(data2[,c(3,4)],min)
# 7. 노선 번호별 인원수의 최소값을 구하시오
tapply(승차+하차,노선번호,min)
# 노선 번호별 하차인원수 최소값
tapply(하차, 노선번호, min)
# 노선 번호별 승차인원수 최소값
tapply(승차, 노선번호, min)
# stringr 패키지 연습문제1
mystr<-'홍길동15강감찬25이순신35김유신45'
# 1. mystr문자열의 길이를 구해 len 변수에 저장하고 변수를 확인하시오
len<-str_length(mystr)
len
# 2. '김유신'의 위치를 파악한다
str_locate(mystr,"김유신")
# 3. mystr의 앞에서 4글자를 추출한다
str_sub(mystr,start=1,end=4)
str_sub(mystr,1,4)
# 4. mystr의 5번째부터 끝까지 추출한다
str_sub(mystr,start=5)
str_sub(mystr,5)
# stringr 패키지 연습문제2
mystr<-'hello world'
# 1. mystr 변수의 모든 글자를 대문자로 변환 후 mystr 변수에 저장하고 변수 내용을 출력하시오
mystr<-str_to_upper(mystr)
mystr
# 2. mystr 변수의 모든 글자를 소문자로 변환 후 mystr변수에 저장하고 변수 내용을 출력하시오
mystr<-str_to_lower(mystr)
mystr
# 3. 문자열 변수 mystr의 값에 대해서 단어의 첫 글자를 대문자로 변환한다
str_to_title(mystr)
# stringr 패키지 연습문제3
mystr='hong1234'
# 1. mystr변수의 값 중 hong을 kang으로 대체하시오
str_replace(mystr,'hong','kang')
# 2. mystr변수의 값 중 1234를 5678로 대체하시오
str_replace(mystr,'1234','5678')
# 3. mystr의 내용과 'choi9876'을 결합하시오
str_c(mystr,"choi9876")
# stringr 패키지 연습문제4
mystr='kim,lee,choi,park'
# 1. mystr 내용을 ,를 기준으로 분리하시오.
str_split(mystr,",")
# 2. human 목록들에 대하여 구분자를 /로 연결하시오.
human<-c("홍길동10","박영희20","김철수30","이몽룡40")
str_c(human,collapse = "/")
paste(human,collapse = "/")
# stringr 패키지 연습문제5
fruits<-c('apple','Apple','banana','Pineapple',"Java",'jungle')
# 1. 대문자P가 있는 단어 찾기
str_detect(fruits,'P')
# 2. 첫 글자가 소문자 b인 단어 찾기
str_detect(fruits,'^b')
# 3. 끝나는 글자가 소문자 e인 단어 찾기
str_detect(fruits,'e$')
# 4. 시작하는 글자가 대문자 J나 소문자 j인 단어 찾기
str_detect(fruits,'^[Jj]')
# 5. 단어에 소문자 l과 대문자 P가 들어있는 단어 찾기
str_detect(fruits,'[lp]')
# stringr 패키지 연습문제6
|
/script/0702연습문제.R
|
no_license
|
valborgs/RStudy
|
R
| false | false | 7,115 |
r
|
# aggregate 연습문제
# aggregate(출력 열 ~ 기준 열, 데이터, 통계함수)
head(Fruits,3)
Fruits
ls(Fruits) # 필드명 출력
# 1. 과일별 판매액의 평균을 구하시오
aggregate(Sales ~ Fruit, Fruits, mean)
# 2. 과일별 비용의 최대값을 구하시오
aggregate(Expenses ~ Fruit, Fruits, max)
# 3. 과일별 수익의 최소값을 구하시오
aggregate(Profit ~ Fruit, Fruits, min)
# 4. 위치별 판매금액의 평균을 구하시오
aggregate(Sales ~ Location, Fruits, mean)
# 5. 과일별 수익의 합계를 구하시오
aggregate(Profit ~ Fruit, Fruits, sum)
# 6. 연도별 판매금액의 합계를 구하시오
aggregate(Sales ~ Year, Fruits, sum)
# 7. 과일별 평균 비용을 구하시오
aggregate(Expenses ~ Fruit, Fruits, mean)
# 8. 지역 + 과일별 수익의 평균을 구하시오
aggregate(Profit ~ Location, Fruits, mean)
# 9. 지역 + 연도별 판매액의 합계를 구하시오
aggregate(Sales ~ Location + Year, Fruits, sum)
# 10. 지역 + 과일별 비용의 합계를 구하시오
aggregate(Expenses ~ Location + Fruit, Fruits, sum)
# 11. 지역 + 연도별 수익의 최대값을 구하시오
aggregate(Profit ~ Location + Year, Fruits, max)
# aggregate() 연습문제2
# 1. 1-4호선승하차승객수.csv 파일을 df_subway로 불러오세요. (stringsAsFactors=F)
df_subway<-read.csv('data\\1-4호선승하차승객수.csv',stringsAsFactors=F)
View(df_subway)
ls(df_subway)
# 2. 노선 번호별 총 승차 인원수를 구하시오
aggregate(승차 ~ 노선번호, df_subway, sum)
# 3. 노선 번호별 총 하차 인원수를 구하시오
aggregate(하차 ~ 노선번호, df_subway, sum)
# 4. 노선 번호별 승차 인원수 평균을 구하시오
aggregate(승차 ~ 노선번호, df_subway, mean)
# 5. 노선 번호별 하차 인원수 최소값을 구하시오
aggregate(하차 ~ 노선번호, df_subway, min)
# 6. 노선 번호별 승차, 하차 각 최대값을 구하시오
aggregate(cbind(승차,하차) ~ 노선번호, df_subway, max)
# 7. 노선 번호별 승차, 하차 각 최소값을 구하시오
aggregate(cbind(승차,하차) ~ 노선번호, df_subway, min)
# 8. 노선 번호별 승하차 총 인원수를 구하시오
aggregate(승차+하차 ~ 노선번호, df_subway, sum)
# apply() 연습문제
# 1. data1.csv 파일을 data1으로 불러오세요
data1<-read.csv("data\\data1.csv", stringsAsFactors = F)
View(data1)
ls(data1)
# 2. 연도별 합계를 모두 구하시오
apply(data1[,-1],2,sum)
# 3. 연령별 합계를 모두 구하시오
apply(data1[,-1],1,sum)
# 4. 2008년부터 2012년까지 연도별 합계를 각각 구하시오
apply(data1[,10:14],2,sum)
apply(data1[,10:(length(data1)-1)],2,sum)
# 5. 2008년부터 2012년까지 연령별 합계를 각각 구하시오
apply(data1[,10:14],1,sum)
# 6. 2000년, 2005년, 2010년의 연도별 합계를 각각 구해 d1에 대입하시오
d1<-apply(data1[,c(2,7,12)],2,sum)
d1
# 7. 2000년, 2005년, 2010년의 연령별 합계를 각각 구해 d2에 대입하시오
d2<-apply(data1[,c(2,7,12)],1,sum)
d2
# sapply() 연습문제
# 1. 연도별 합계를 모두 구하시오
sapply(data1[,-1],sum)
class(sapply(data1[,-1],sum))
# 출력결과 numeric->벡터형태
# 2. 2008년부터 2012년까지 연도별 합계를 각각 구하시오
sapply(data1[,10:14],sum)
lapply(data1[,10:14],sum)
class(lapply(data1[,10:14],sum)) # list 형태
unlist(lapply(data1[,10:14],sum)) # 벡터 형태로
# 3. 2000년, 2005년, 2010년 연도별 합계를 각각 구하시오
sapply(data1[,c(2,7,12)],sum) # 벡터 형태로 출력됨
# apply() / sapply() / tapply() 연습문제
# 1. 1-4호선승하차승객수.csv 파일을 data2로 불러오세요
data2<-read.csv("data\\1-4호선승하차승객수.csv", stringsAsFactors=F)
View(data2)
attach(data2)
# 2. 노선 번호별 총 승차 인원수를 구하시오
tapply(승차,노선번호,sum)
# 3. 노선 번호별 총 하차 인원수를 구하시오
tapply(하차,노선번호,sum)
# 4. 노선 번호에 상관없이 총 승차 인원수 및 총 하차 인원수를 구하시오
apply(data2[,3:4],2,sum)
sapply(data2[,3:4],sum)
sapply(data2[3:4],sum) # sapply가 열 계산을 하기때문에 인덱싱에서 ,를 생략할수있다
# 5. 노선 번호별 총 승차 인원수 및 총 하차 인원수의 평균을 구하시오
tapply(승차,노선번호,mean)
tapply(하차,노선번호,mean)
# tapply(cbind(하차,승차),노선번호,mean) -> 에러 뜸
tapply(승차+하차, 노선번호, mean) # 총 승하차 인원의 노선별 평균
# 6. 노선 번호에 상관없이 승차 및 하차 인원수 최소값을 각각 구하시오
sapply(data2[3:4],min)
sapply(data2[,c(3,4)],min)
# 7. 노선 번호별 인원수의 최소값을 구하시오
tapply(승차+하차,노선번호,min)
# 노선 번호별 하차인원수 최소값
tapply(하차, 노선번호, min)
# 노선 번호별 승차인원수 최소값
tapply(승차, 노선번호, min)
# stringr 패키지 연습문제1
mystr<-'홍길동15강감찬25이순신35김유신45'
# 1. mystr문자열의 길이를 구해 len 변수에 저장하고 변수를 확인하시오
len<-str_length(mystr)
len
# 2. '김유신'의 위치를 파악한다
str_locate(mystr,"김유신")
# 3. mystr의 앞에서 4글자를 추출한다
str_sub(mystr,start=1,end=4)
str_sub(mystr,1,4)
# 4. mystr의 5번째부터 끝까지 추출한다
str_sub(mystr,start=5)
str_sub(mystr,5)
# stringr 패키지 연습문제2
mystr<-'hello world'
# 1. mystr 변수의 모든 글자를 대문자로 변환 후 mystr 변수에 저장하고 변수 내용을 출력하시오
mystr<-str_to_upper(mystr)
mystr
# 2. mystr 변수의 모든 글자를 소문자로 변환 후 mystr변수에 저장하고 변수 내용을 출력하시오
mystr<-str_to_lower(mystr)
mystr
# 3. 문자열 변수 mystr의 값에 대해서 단어의 첫 글자를 대문자로 변환한다
str_to_title(mystr)
# stringr 패키지 연습문제3
mystr='hong1234'
# 1. mystr변수의 값 중 hong을 kang으로 대체하시오
str_replace(mystr,'hong','kang')
# 2. mystr변수의 값 중 1234를 5678로 대체하시오
str_replace(mystr,'1234','5678')
# 3. mystr의 내용과 'choi9876'을 결합하시오
str_c(mystr,"choi9876")
# stringr 패키지 연습문제4
mystr='kim,lee,choi,park'
# 1. mystr 내용을 ,를 기준으로 분리하시오.
str_split(mystr,",")
# 2. human 목록들에 대하여 구분자를 /로 연결하시오.
human<-c("홍길동10","박영희20","김철수30","이몽룡40")
str_c(human,collapse = "/")
paste(human,collapse = "/")
# stringr 패키지 연습문제5
fruits<-c('apple','Apple','banana','Pineapple',"Java",'jungle')
# 1. 대문자P가 있는 단어 찾기
str_detect(fruits,'P')
# 2. 첫 글자가 소문자 b인 단어 찾기
str_detect(fruits,'^b')
# 3. 끝나는 글자가 소문자 e인 단어 찾기
str_detect(fruits,'e$')
# 4. 시작하는 글자가 대문자 J나 소문자 j인 단어 찾기
str_detect(fruits,'^[Jj]')
# 5. 단어에 소문자 l과 대문자 P가 들어있는 단어 찾기
str_detect(fruits,'[lp]')
# stringr 패키지 연습문제6
|
library(fastcluster)
library(gplots)
library("pheatmap")
args=commandArgs(trailingOnly=TRUE)
i=1
name=as.character(args[i]); i=i+1
DEmatrix=NULL
fileEnd=as.character(args[i]); i=i+1
while (i <= length(args))
{
#original code for use with fpkm
x=read.delim(as.character(args[i]), header=F); i=i+1
DEmatrix=cbind(DEmatrix,as.numeric(x[,4]))
}
coords=x[,1:3]
cent=round((coords[,3]+coords[,2])/2)
coords[,2]=cent
coords[,3]=cent+1
myCol <- c(colorRampPalette(c("white", "green4"))(6))
myBreaks <- c(-.2, -.001, .2, .4, .6, .8, 1)
#y=kmeans(DEmatrix,32, iter.max = 50, nstart=100)
#clusters=y$cluster
sums=apply(DEmatrix,1,max)
#DEmatrix=DEmatrix[sums > 20,]
#ordr=hclust(dist(DEmatrix))$order
#ordr=seq(length(DEmatrix[,1]))
#ordr=order(DEmatrix[,2]-DEmatrix[,1], decreasing=T)
ordr=order(DEmatrix[,2], decreasing=T)
#png(paste("heatmap_", name, ".png", sep=""), height = 2500, width = 2500, res=2500)
png(paste("heatmap_", name, ".png", sep=""), height = 3000, width = 3000, res=2500)
#ordr=order(clusters, apply(abs(DEmatrix), 1, max))
#colnames(DEmatrix)=gsub("WTAdultIntestinalEpithelium", "Intestine", gsub(fileEnd, "", args[-c(1,2)]))
colnames(DEmatrix)=c("a", "b")
pheatmap(DEmatrix[ordr,], border_color=NA, color=myCol, breaks=myBreaks, cluster_rows=FALSE, cluster_cols=FALSE, scale="none", fontsize = 12, fontsize_col=20, legend=F)
dev.off()
write.table(cbind(coords[ordr,], seq(length.out = length(ordr))), paste(name, ".bed", sep=""), row.names=F, col.names=F, quote=F, sep="\t")
|
/BSseq_mouseIntestine/getHeatmaps_methylation.R
|
no_license
|
xjyx/Scripts-for-Kremsky-Corces-2020-Genome-Biology-paper
|
R
| false | false | 1,493 |
r
|
library(fastcluster)
library(gplots)
library("pheatmap")
args=commandArgs(trailingOnly=TRUE)
i=1
name=as.character(args[i]); i=i+1
DEmatrix=NULL
fileEnd=as.character(args[i]); i=i+1
while (i <= length(args))
{
#original code for use with fpkm
x=read.delim(as.character(args[i]), header=F); i=i+1
DEmatrix=cbind(DEmatrix,as.numeric(x[,4]))
}
coords=x[,1:3]
cent=round((coords[,3]+coords[,2])/2)
coords[,2]=cent
coords[,3]=cent+1
myCol <- c(colorRampPalette(c("white", "green4"))(6))
myBreaks <- c(-.2, -.001, .2, .4, .6, .8, 1)
#y=kmeans(DEmatrix,32, iter.max = 50, nstart=100)
#clusters=y$cluster
sums=apply(DEmatrix,1,max)
#DEmatrix=DEmatrix[sums > 20,]
#ordr=hclust(dist(DEmatrix))$order
#ordr=seq(length(DEmatrix[,1]))
#ordr=order(DEmatrix[,2]-DEmatrix[,1], decreasing=T)
ordr=order(DEmatrix[,2], decreasing=T)
#png(paste("heatmap_", name, ".png", sep=""), height = 2500, width = 2500, res=2500)
png(paste("heatmap_", name, ".png", sep=""), height = 3000, width = 3000, res=2500)
#ordr=order(clusters, apply(abs(DEmatrix), 1, max))
#colnames(DEmatrix)=gsub("WTAdultIntestinalEpithelium", "Intestine", gsub(fileEnd, "", args[-c(1,2)]))
colnames(DEmatrix)=c("a", "b")
pheatmap(DEmatrix[ordr,], border_color=NA, color=myCol, breaks=myBreaks, cluster_rows=FALSE, cluster_cols=FALSE, scale="none", fontsize = 12, fontsize_col=20, legend=F)
dev.off()
write.table(cbind(coords[ordr,], seq(length.out = length(ordr))), paste(name, ".bed", sep=""), row.names=F, col.names=F, quote=F, sep="\t")
|
# Source depdencies -------------------------------------------
source("global_variable.R")
source("global_dependencies.R")
source("set_curlOptions.R")
# Connections --------------------------------------------------
sdy269 <- CreateConnection("SDY269", verbose = TRUE)
sdy34 <- suppressMessages(CreateConnection("SDY34", verbose = TRUE))
# Helper Functions ---------------------------------------------
try_gei <- function(con){
tryCatch(
con$GeneExpressionInputs(),
warning = function(w) return(w),
error = function(e) return(e)
)
}
# Tests --------------------------------------------------------
context("GeneExpressionInputs")
test_that("returns GE inputs df if study has inputs", {
res <- try_gei(sdy269)
expect_true( (dim(res)[1] > 0) & (dim(res)[2] > 0) )
})
test_that("returns error if study does not have inputs", {
res <- try_gei(sdy34)
expect_true( res$message == "Gene Expression Inputs not found for study.")
})
# cleanup ------------------------------------------------------
if(exists("netrc_file")){
file.remove(netrc_file)
}
|
/tests/testthat/test-GeneExpresssionInputs.R
|
no_license
|
wangdi2014/ImmuneSpaceR
|
R
| false | false | 1,079 |
r
|
# Source depdencies -------------------------------------------
source("global_variable.R")
source("global_dependencies.R")
source("set_curlOptions.R")
# Connections --------------------------------------------------
sdy269 <- CreateConnection("SDY269", verbose = TRUE)
sdy34 <- suppressMessages(CreateConnection("SDY34", verbose = TRUE))
# Helper Functions ---------------------------------------------
try_gei <- function(con){
tryCatch(
con$GeneExpressionInputs(),
warning = function(w) return(w),
error = function(e) return(e)
)
}
# Tests --------------------------------------------------------
context("GeneExpressionInputs")
test_that("returns GE inputs df if study has inputs", {
res <- try_gei(sdy269)
expect_true( (dim(res)[1] > 0) & (dim(res)[2] > 0) )
})
test_that("returns error if study does not have inputs", {
res <- try_gei(sdy34)
expect_true( res$message == "Gene Expression Inputs not found for study.")
})
# cleanup ------------------------------------------------------
if(exists("netrc_file")){
file.remove(netrc_file)
}
|
getCapitalGainMonth <- function(ticker = "GOOG", from = "2013-01-01", to=Sys.time()){
mydata <- yahoodata(ticker, from, to);
names(mydata) <- c("Symbol","Value","Date","Time","Name");
num<-dim(mydata)[1];
gainf<-matrix(ncol=2,nrow=floor((num-1)/20));
for(i in 1:num-1){
if((i/20)==floor(i/20)){
gainf[i/20,1]<- 100*((mydata[i+1,2]-mydata[i,2])/mydata[i+1,2]);
gainf[i/20,2]<-mydata[i+1,3];
}}
gainf<-as.data.frame(gainf);
colnames(gainf)<-c("Value","Date");
return(gainf);
}
|
/R/getCapitalGainMonth.R
|
no_license
|
fcluzeau/stock
|
R
| false | false | 477 |
r
|
getCapitalGainMonth <- function(ticker = "GOOG", from = "2013-01-01", to=Sys.time()){
mydata <- yahoodata(ticker, from, to);
names(mydata) <- c("Symbol","Value","Date","Time","Name");
num<-dim(mydata)[1];
gainf<-matrix(ncol=2,nrow=floor((num-1)/20));
for(i in 1:num-1){
if((i/20)==floor(i/20)){
gainf[i/20,1]<- 100*((mydata[i+1,2]-mydata[i,2])/mydata[i+1,2]);
gainf[i/20,2]<-mydata[i+1,3];
}}
gainf<-as.data.frame(gainf);
colnames(gainf)<-c("Value","Date");
return(gainf);
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/csnapWhisker.R
\name{csnapWhisker}
\alias{csnapWhisker}
\title{csnapWhisker()}
\usage{
csnapWhisker(tre_files_path)
}
\arguments{
\item{tre_files_path}{A path to where your .tre files (assumes you have AIC, Saturated, BIC, Gene, and Uniform). Future edits will make this generalized.}
}
\description{
Create a Compare Shared Node Ages Plot (CSNAP) with whiskers
}
\keyword{ancestry}
|
/man/csnapWhisker.Rd
|
no_license
|
palautatan/csnap
|
R
| false | true | 461 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/csnapWhisker.R
\name{csnapWhisker}
\alias{csnapWhisker}
\title{csnapWhisker()}
\usage{
csnapWhisker(tre_files_path)
}
\arguments{
\item{tre_files_path}{A path to where your .tre files (assumes you have AIC, Saturated, BIC, Gene, and Uniform). Future edits will make this generalized.}
}
\description{
Create a Compare Shared Node Ages Plot (CSNAP) with whiskers
}
\keyword{ancestry}
|
########## SURVEY COMPARISON PROJECT MODEL DATAFRAME CREATION ##########
##########
##########
# This file combines fish observation data from three survey types (SVC,
# transect, and roving) with associated survey metadata, habitat traits, and
# species traits before calculating density and average depth across
# observations and log transforming density for further analyses.
##########
##########
# AUTHOR: Iris M. George
# DATE OF CREATION: 2021-06-07
##########
##########
# Set-Up =======================================================================
# packages
library(plyr)
library(tidyverse)
library(here)
# data
fish_data <- read_csv(here("./dataframes/fish_dataframe.csv"))
SVC <- read_csv(here("./clean_data/SVC_data.csv"))
prey_meta <- read_csv(here("./clean_data/prey_metadata.csv"))
pred_meta <- read_csv(here("./clean_data/pred_metadata.csv"))
traits <- read_csv(here("./clean_data/fish_traits.csv"))
vert_relief <- read_csv(here("./clean_data/vertical_relief.csv"))
# Joining Survey Metadata ======================================================
# The following joins metadata associated with each survey type (SVC, transect
# and roving) to the full fish dataframe.
# Joining SVC Metadata:
# select wanted metadata columns: session, site, date, diver, habitat,
# cylinder_area, max_depth, octocoral, stony coral
SVC_meta <- SVC[,c(1,3,4,12,16,17,33,34)]
# aggregate rows by session
SVC_meta <- SVC_meta %>% group_by(session, site, SVC_date, SVC_habitat) %>%
summarise_each(funs(mean))
# rename area column
SVC_meta <- SVC_meta %>% rename(SVC_area = SVC_cylinder_area)
# join meta data to fish data
SVC_full <- join(fish_data, SVC_meta, by = NULL, type = "left", match = "first")
# Joining Transect Metadata:
# select wanted metadata columns: session, site, date, transect_area, depth
prey_meta <- prey_meta[,c(1,4,5,7,15)]
# rename columns
prey_meta <- prey_meta %>% rename(prey_depth = prey_depth_m)
prey_meta <- prey_meta %>% rename(prey_area = prey_tran_area)
# want to aggregate depth by mean and area by sum: splitting up
# transform depth and area columns from character to numeric
prey_meta <- transform(prey_meta, prey_depth = as.numeric(prey_depth),
prey_area = as.numeric(prey_area))
# remove area column from full transect meta
prey_depth <- prey_meta[,c(1:4)]
# aggregate depth rows by session
prey_depth <- aggregate(.~session+site+prey_date, prey_depth, mean)
# remove depth column from full transect meta
prey_area <- prey_meta[,c(1:3,5)]
# aggregate area rows by session
prey_area <- aggregate(.~session+site+prey_date, prey_area, sum)
# join transect depth and area to make full transect metadata
prey_meta <- join(prey_depth, prey_area, by = NULL, type = "full",
match = "all")
# join transect metadata to fish and SVC dataframe
SVCprey_full <- join(SVC_full, prey_meta, by = NULL, type = "left",
match = "first")
# Joining Roving Metadata:
# select wanted metadata columns: session, site, date, transect_area, depth
pred_meta <- pred_meta[,c(1,4,8,17,21)]
# rename columns
pred_meta <- pred_meta %>% rename(pred_depth = pred_depth_ft)
pred_meta <- pred_meta %>% rename(pred_area = pred_trans_area)
# want to aggregate depth by mean and area by sum: splitting up
# remove area column
pred_depth <- pred_meta[,c(1:4)]
# aggregate depth rows by session
pred_depth <- aggregate(.~session+site+pred_date, pred_depth, mean)
# remove depth column
pred_area <- pred_meta[,c(1:3,5)]
# aggregate area rows by session
pred_area <- aggregate(.~session+site+pred_date, pred_area, sum)
# join roving depth and area to create full roving metadata
pred_meta <- join(pred_depth, pred_area, by = NULL, type = "full",
match = "all")
# join roving metadata to fish, SVC, and transect dataframe
fish_meta <- join(SVCprey_full, pred_meta, by = NULL, type = "left",
match = "first")
# Joining Vertical Relief Data =================================================
# The following section aggregates vertical relief measures to a mean value per
# survey site, then joins these measures to the fish and survey metadata
# dataframe.
# select site and vert relief columns
vert_relief <- vert_relief[,c(1,7)]
# aggregate to site mean
vert_relief <- aggregate(relief_cm~site, vert_relief, mean)
# change KL-P30 to KL-30
vert_relief$site[vert_relief$site == "KL-P30"] <- "KL-30"
# join vertical relief measure to each site
fish_meta <- join(fish_meta, vert_relief, by = NULL, type = "left",
match = "first")
# Joining Species' Trait Data ==================================================
# The following joins adult fish traits used in further analyses to the survey
# metadata and fish dataframe.
# filter for adult lifestage
fish_traits <- filter(traits, lifestage == "adult")
# select relevant columns: latin names, predator presence, nocturnal,
# max_length, position, behaviour, colouration, cryptic_behaviour, shape,
# trophic position
fish_traits <- fish_traits[,c(1:4,7,18,36,38,39,60,61,70,74)]
# rename columns
fish_traits <- fish_traits %>% rename(colouration = colouration_cat3)
fish_traits <- fish_traits %>% rename(species = common_name)
# join fish trait data to meta and fish dataframe
full_dataframe <- join(fish_meta, fish_traits, by = NULL, type = "full",
match = "all")
# remove un-recorded species
sessions <- unique(full_dataframe$session)
length(sessions)
na_values <- which(is.na(full_dataframe), arr.ind=TRUE)
# replace roving NAs with 0s
full_dataframe$pred_date[is.na(full_dataframe$pred_date)] <- "2014-01-01"
full_dataframe$pred_depth[is.na(full_dataframe$pred_depth)] <- 0
full_dataframe$pred_area[is.na(full_dataframe$pred_area)] <- 0
# remove NA values
full_dataframe <- na.omit(full_dataframe)
# Density Calculation ==========================================================
# The following calculates fish densities for each of the three survey types
# (SVC, transect, and roving) for each single observation. It then calculates
# the density differences between each of the survey types for each observation.
# SVC density calculation
full_dataframe$SVC_density <-
full_dataframe$SVC_abundance/full_dataframe$SVC_area
# transect survey density calculation
full_dataframe$prey_density <-
full_dataframe$prey_abundance/full_dataframe$prey_area
# roving survey density calculation
full_dataframe$pred_density <-
full_dataframe$pred_abundance/full_dataframe$pred_area
# SVC - transect density difference calculation
full_dataframe$SVC_prey_difference <-
full_dataframe$SVC_density - full_dataframe$prey_density
# SVC - roving density difference calculation
full_dataframe$SVC_pred_difference <-
full_dataframe$SVC_density - full_dataframe$pred_density
# transect - roving density difference calculation
full_dataframe$prey_pred_difference <-
full_dataframe$prey_density - full_dataframe$pred_density
# Dataframe Edits ==============================================================
# The following provides some additional edits to the full dataframe to produce
# a final version.
# re-order columns
full_dataframe <- full_dataframe[,c(2,1,21:23,3,4,8,10,13,14,21,25:33,9,11,12,
34,15:17,35,18:20,36:39)]
# re-name columns
full_dataframe <- full_dataframe %>% rename(habitat = SVC_habitat)
full_dataframe <- full_dataframe %>% rename(species_order = order)
# SVC vs. Transect Survey Dataframe ============================================
# The following creates a dataframe specific to observations within SVC and
# transect surveys.
# select SVC and transect columns
SVCprey <- full_dataframe[,c(1:29,34)]
# calculate total density for SVC and transect surveys
SVCprey$total_density <- SVCprey$SVC_density+SVCprey$prey_density
# remove rows where total density = 0
SVCprey_data <- SVCprey[SVCprey$total_density !=0,]
# remove trumpetfish (only species in order)
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Syngnathiformes",]
# remove silversides (only species in order)
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Atheriniformes",]
# remove eyed flounder (only depressiform species)
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Pleuronectiformes",]
# remove mackerel scad (only pelagic species)
SVCprey_data <- SVCprey_data[SVCprey_data$species !="mackerel scad",]
# remove eels
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Anguilliformes",]
# remove sessions with un-matched dates between surveys
SVCprey_data <- SVCprey_data[SVCprey_data$session !=178,]
SVCprey_data <- SVCprey_data[SVCprey_data$session !=179,]
SVCprey_data <- SVCprey_data[SVCprey_data$session !=180,]
SVCprey_data <- SVCprey_data[SVCprey_data$session !=268,]
# SVC vs. Roving Survey Dataframe ==============================================
# The following creates a dataframe specific to observations within SVC and
# roving surveys.
# select SVC and roving columns
SVCpred <- full_dataframe[,c(1:25,30:33,35)]
# filter for species recorded on predator surveys
SVCpred <- filter(SVCpred, predator_presence == 1)
# calculate total density for SVC and roving surveys
SVCpred$total_density <- SVCpred$SVC_density+SVCpred$pred_density
# remove rows where total density = 0
SVCpred_data <- SVCpred[SVCpred$total_density !=0,]
# remove trumpetfish (only species in order)
SVCpred_data <- SVCpred_data[SVCpred_data$species_order !="Syngnathiformes",]
# remove gray snapper (inconsistently reported)
SVCpred_data <- SVCpred_data[SVCpred_data$species !="gray snapper",]
# remove amberjack (only schooling species)
SVCpred_data <- SVCpred_data[SVCpred_data$species !="amberjack",]
# remove black margate (only compressiform species)
# SVCpred_data <- SVCpred_data[SVCpred_data$species !="black margate",]
# remove sessions with un-matched dates between surveys
SVCpred_data <- SVCpred_data[SVCpred_data$session !=178,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=179,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=180,]
# remove sessions with no roving data
SVCpred_data <- SVCpred_data[SVCpred_data$session !=264,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=265,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=266,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=267,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=268,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=269,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=270,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=271,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=272,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=273,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=274,]
# remove NA values
SVCpred_data <- na.omit(SVCpred_data)
# Density Log Transformation ===================================================
# Density differences between the survey types did not meet normality
# assumptions required for analyses, so the following conducts a log
# transformation of raw densities before taking the difference to improved
# normality.
# calculate log SVC density in SVC vs. transect dataframe
log_SVCdensity <- log(SVCprey_data$SVC_density + 0.001)
# calculate log transect density
log_preydensity <- log(SVCprey_data$prey_density + 0.001)
# histogram of SVC vs. transect log density differences
hist(log_SVCdensity-log_preydensity)
# calculate SVC vs. transect log density difference
SVCprey_data$log_difference <- log_SVCdensity-log_preydensity
# calculate log SVC density in SVC vs. roving dataframe
log_SVCdensity2 <- log(SVCpred_data$SVC_density + 0.001)
# calculate log roving density
log_preddensity <- log(SVCpred_data$pred_density + 0.001)
# histogram of SVC vs. roving log density differences
hist(log_SVCdensity2-log_preddensity)
# calculate SVC vs. roving log density difference
SVCpred_data$log_difference <- log_SVCdensity2-log_preddensity
# Average Depth Calculation ====================================================
# The following calculates average depth values for each session between the two
# survey types in each dataframe (SVC vs. transect and SVC vs. roving).
# SVC vs. transect dataframe average depth calculation
SVCprey_data$average_depth <- (SVCprey_data$SVC_max_depth +
SVCprey_data$prey_depth)/2
# SVC vs. roving dataframe average depth calculation
SVCpred_data$average_depth <- (SVCpred_data$SVC_max_depth +
SVCpred_data$pred_depth)/2
# export SVC vs. transect survey dataframe
write_csv(SVCprey_data, here("./dataframes/SVCprey_dataframe.csv"))
# export SVC vs. roving survey dataframe
write_csv(SVCpred_data, here("./dataframes/SVCpred_dataframe.csv"))
|
/src/model_dataframes.R
|
no_license
|
iris-george/Reef-Survey-Comparison
|
R
| false | false | 12,839 |
r
|
########## SURVEY COMPARISON PROJECT MODEL DATAFRAME CREATION ##########
##########
##########
# This file combines fish observation data from three survey types (SVC,
# transect, and roving) with associated survey metadata, habitat traits, and
# species traits before calculating density and average depth across
# observations and log transforming density for further analyses.
##########
##########
# AUTHOR: Iris M. George
# DATE OF CREATION: 2021-06-07
##########
##########
# Set-Up =======================================================================
# packages
library(plyr)
library(tidyverse)
library(here)
# data
fish_data <- read_csv(here("./dataframes/fish_dataframe.csv"))
SVC <- read_csv(here("./clean_data/SVC_data.csv"))
prey_meta <- read_csv(here("./clean_data/prey_metadata.csv"))
pred_meta <- read_csv(here("./clean_data/pred_metadata.csv"))
traits <- read_csv(here("./clean_data/fish_traits.csv"))
vert_relief <- read_csv(here("./clean_data/vertical_relief.csv"))
# Joining Survey Metadata ======================================================
# The following joins metadata associated with each survey type (SVC, transect
# and roving) to the full fish dataframe.
# Joining SVC Metadata:
# select wanted metadata columns: session, site, date, diver, habitat,
# cylinder_area, max_depth, octocoral, stony coral
SVC_meta <- SVC[,c(1,3,4,12,16,17,33,34)]
# aggregate rows by session
SVC_meta <- SVC_meta %>% group_by(session, site, SVC_date, SVC_habitat) %>%
summarise_each(funs(mean))
# rename area column
SVC_meta <- SVC_meta %>% rename(SVC_area = SVC_cylinder_area)
# join meta data to fish data
SVC_full <- join(fish_data, SVC_meta, by = NULL, type = "left", match = "first")
# Joining Transect Metadata:
# select wanted metadata columns: session, site, date, transect_area, depth
prey_meta <- prey_meta[,c(1,4,5,7,15)]
# rename columns
prey_meta <- prey_meta %>% rename(prey_depth = prey_depth_m)
prey_meta <- prey_meta %>% rename(prey_area = prey_tran_area)
# want to aggregate depth by mean and area by sum: splitting up
# transform depth and area columns from character to numeric
prey_meta <- transform(prey_meta, prey_depth = as.numeric(prey_depth),
prey_area = as.numeric(prey_area))
# remove area column from full transect meta
prey_depth <- prey_meta[,c(1:4)]
# aggregate depth rows by session
prey_depth <- aggregate(.~session+site+prey_date, prey_depth, mean)
# remove depth column from full transect meta
prey_area <- prey_meta[,c(1:3,5)]
# aggregate area rows by session
prey_area <- aggregate(.~session+site+prey_date, prey_area, sum)
# join transect depth and area to make full transect metadata
prey_meta <- join(prey_depth, prey_area, by = NULL, type = "full",
match = "all")
# join transect metadata to fish and SVC dataframe
SVCprey_full <- join(SVC_full, prey_meta, by = NULL, type = "left",
match = "first")
# Joining Roving Metadata:
# select wanted metadata columns: session, site, date, transect_area, depth
pred_meta <- pred_meta[,c(1,4,8,17,21)]
# rename columns
pred_meta <- pred_meta %>% rename(pred_depth = pred_depth_ft)
pred_meta <- pred_meta %>% rename(pred_area = pred_trans_area)
# want to aggregate depth by mean and area by sum: splitting up
# remove area column
pred_depth <- pred_meta[,c(1:4)]
# aggregate depth rows by session
pred_depth <- aggregate(.~session+site+pred_date, pred_depth, mean)
# remove depth column
pred_area <- pred_meta[,c(1:3,5)]
# aggregate area rows by session
pred_area <- aggregate(.~session+site+pred_date, pred_area, sum)
# join roving depth and area to create full roving metadata
pred_meta <- join(pred_depth, pred_area, by = NULL, type = "full",
match = "all")
# join roving metadata to fish, SVC, and transect dataframe
fish_meta <- join(SVCprey_full, pred_meta, by = NULL, type = "left",
match = "first")
# Joining Vertical Relief Data =================================================
# The following section aggregates vertical relief measures to a mean value per
# survey site, then joins these measures to the fish and survey metadata
# dataframe.
# select site and vert relief columns
vert_relief <- vert_relief[,c(1,7)]
# aggregate to site mean
vert_relief <- aggregate(relief_cm~site, vert_relief, mean)
# change KL-P30 to KL-30
vert_relief$site[vert_relief$site == "KL-P30"] <- "KL-30"
# join vertical relief measure to each site
fish_meta <- join(fish_meta, vert_relief, by = NULL, type = "left",
match = "first")
# Joining Species' Trait Data ==================================================
# The following joins adult fish traits used in further analyses to the survey
# metadata and fish dataframe.
# filter for adult lifestage
fish_traits <- filter(traits, lifestage == "adult")
# select relevant columns: latin names, predator presence, nocturnal,
# max_length, position, behaviour, colouration, cryptic_behaviour, shape,
# trophic position
fish_traits <- fish_traits[,c(1:4,7,18,36,38,39,60,61,70,74)]
# rename columns
fish_traits <- fish_traits %>% rename(colouration = colouration_cat3)
fish_traits <- fish_traits %>% rename(species = common_name)
# join fish trait data to meta and fish dataframe
full_dataframe <- join(fish_meta, fish_traits, by = NULL, type = "full",
match = "all")
# remove un-recorded species
sessions <- unique(full_dataframe$session)
length(sessions)
na_values <- which(is.na(full_dataframe), arr.ind=TRUE)
# replace roving NAs with 0s
full_dataframe$pred_date[is.na(full_dataframe$pred_date)] <- "2014-01-01"
full_dataframe$pred_depth[is.na(full_dataframe$pred_depth)] <- 0
full_dataframe$pred_area[is.na(full_dataframe$pred_area)] <- 0
# remove NA values
full_dataframe <- na.omit(full_dataframe)
# Density Calculation ==========================================================
# The following calculates fish densities for each of the three survey types
# (SVC, transect, and roving) for each single observation. It then calculates
# the density differences between each of the survey types for each observation.
# SVC density calculation
full_dataframe$SVC_density <-
full_dataframe$SVC_abundance/full_dataframe$SVC_area
# transect survey density calculation
full_dataframe$prey_density <-
full_dataframe$prey_abundance/full_dataframe$prey_area
# roving survey density calculation
full_dataframe$pred_density <-
full_dataframe$pred_abundance/full_dataframe$pred_area
# SVC - transect density difference calculation
full_dataframe$SVC_prey_difference <-
full_dataframe$SVC_density - full_dataframe$prey_density
# SVC - roving density difference calculation
full_dataframe$SVC_pred_difference <-
full_dataframe$SVC_density - full_dataframe$pred_density
# transect - roving density difference calculation
full_dataframe$prey_pred_difference <-
full_dataframe$prey_density - full_dataframe$pred_density
# Dataframe Edits ==============================================================
# The following provides some additional edits to the full dataframe to produce
# a final version.
# re-order columns
full_dataframe <- full_dataframe[,c(2,1,21:23,3,4,8,10,13,14,21,25:33,9,11,12,
34,15:17,35,18:20,36:39)]
# re-name columns
full_dataframe <- full_dataframe %>% rename(habitat = SVC_habitat)
full_dataframe <- full_dataframe %>% rename(species_order = order)
# SVC vs. Transect Survey Dataframe ============================================
# The following creates a dataframe specific to observations within SVC and
# transect surveys.
# select SVC and transect columns
SVCprey <- full_dataframe[,c(1:29,34)]
# calculate total density for SVC and transect surveys
SVCprey$total_density <- SVCprey$SVC_density+SVCprey$prey_density
# remove rows where total density = 0
SVCprey_data <- SVCprey[SVCprey$total_density !=0,]
# remove trumpetfish (only species in order)
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Syngnathiformes",]
# remove silversides (only species in order)
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Atheriniformes",]
# remove eyed flounder (only depressiform species)
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Pleuronectiformes",]
# remove mackerel scad (only pelagic species)
SVCprey_data <- SVCprey_data[SVCprey_data$species !="mackerel scad",]
# remove eels
SVCprey_data <- SVCprey_data[SVCprey_data$species_order !="Anguilliformes",]
# remove sessions with un-matched dates between surveys
SVCprey_data <- SVCprey_data[SVCprey_data$session !=178,]
SVCprey_data <- SVCprey_data[SVCprey_data$session !=179,]
SVCprey_data <- SVCprey_data[SVCprey_data$session !=180,]
SVCprey_data <- SVCprey_data[SVCprey_data$session !=268,]
# SVC vs. Roving Survey Dataframe ==============================================
# The following creates a dataframe specific to observations within SVC and
# roving surveys.
# select SVC and roving columns
SVCpred <- full_dataframe[,c(1:25,30:33,35)]
# filter for species recorded on predator surveys
SVCpred <- filter(SVCpred, predator_presence == 1)
# calculate total density for SVC and roving surveys
SVCpred$total_density <- SVCpred$SVC_density+SVCpred$pred_density
# remove rows where total density = 0
SVCpred_data <- SVCpred[SVCpred$total_density !=0,]
# remove trumpetfish (only species in order)
SVCpred_data <- SVCpred_data[SVCpred_data$species_order !="Syngnathiformes",]
# remove gray snapper (inconsistently reported)
SVCpred_data <- SVCpred_data[SVCpred_data$species !="gray snapper",]
# remove amberjack (only schooling species)
SVCpred_data <- SVCpred_data[SVCpred_data$species !="amberjack",]
# remove black margate (only compressiform species)
# SVCpred_data <- SVCpred_data[SVCpred_data$species !="black margate",]
# remove sessions with un-matched dates between surveys
SVCpred_data <- SVCpred_data[SVCpred_data$session !=178,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=179,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=180,]
# remove sessions with no roving data
SVCpred_data <- SVCpred_data[SVCpred_data$session !=264,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=265,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=266,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=267,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=268,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=269,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=270,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=271,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=272,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=273,]
SVCpred_data <- SVCpred_data[SVCpred_data$session !=274,]
# remove NA values
SVCpred_data <- na.omit(SVCpred_data)
# Density Log Transformation ===================================================
# Density differences between the survey types did not meet normality
# assumptions required for analyses, so the following conducts a log
# transformation of raw densities before taking the difference to improved
# normality.
# calculate log SVC density in SVC vs. transect dataframe
log_SVCdensity <- log(SVCprey_data$SVC_density + 0.001)
# calculate log transect density
log_preydensity <- log(SVCprey_data$prey_density + 0.001)
# histogram of SVC vs. transect log density differences
hist(log_SVCdensity-log_preydensity)
# calculate SVC vs. transect log density difference
SVCprey_data$log_difference <- log_SVCdensity-log_preydensity
# calculate log SVC density in SVC vs. roving dataframe
log_SVCdensity2 <- log(SVCpred_data$SVC_density + 0.001)
# calculate log roving density
log_preddensity <- log(SVCpred_data$pred_density + 0.001)
# histogram of SVC vs. roving log density differences
hist(log_SVCdensity2-log_preddensity)
# calculate SVC vs. roving log density difference
SVCpred_data$log_difference <- log_SVCdensity2-log_preddensity
# Average Depth Calculation ====================================================
# The following calculates average depth values for each session between the two
# survey types in each dataframe (SVC vs. transect and SVC vs. roving).
# SVC vs. transect dataframe average depth calculation
SVCprey_data$average_depth <- (SVCprey_data$SVC_max_depth +
SVCprey_data$prey_depth)/2
# SVC vs. roving dataframe average depth calculation
SVCpred_data$average_depth <- (SVCpred_data$SVC_max_depth +
SVCpred_data$pred_depth)/2
# export SVC vs. transect survey dataframe
write_csv(SVCprey_data, here("./dataframes/SVCprey_dataframe.csv"))
# export SVC vs. roving survey dataframe
write_csv(SVCpred_data, here("./dataframes/SVCpred_dataframe.csv"))
|
# Run sudo R, add packages to install
packages <- c("mlr", "devtools", "tableone", "jtools", "ggstance", "kernlab", "randomForest", "reshape2", "GGally", "FactoMineR")
install.packages(packages, lib="/usr/local/lib/R/site-library")
devtools::install_github("vqv/ggbiplot")
devtools::install_github("factoextra")
|
/pkg_install.R
|
no_license
|
mazzottidr/cursoML2018
|
R
| false | false | 316 |
r
|
# Run sudo R, add packages to install
packages <- c("mlr", "devtools", "tableone", "jtools", "ggstance", "kernlab", "randomForest", "reshape2", "GGally", "FactoMineR")
install.packages(packages, lib="/usr/local/lib/R/site-library")
devtools::install_github("vqv/ggbiplot")
devtools::install_github("factoextra")
|
LognormalLikelihood <- function(x, mu, sigma){
z <- (log(x) - mu) / sigma
lnL <- -z^2/2 - log(x) - log(sigma)
sum(lnL)
}
#' @title CalcLognormalLikelihood
#'
#' @param data A vector of sample observations
#' @param mean_range A vector with values of the mean
#' @param CV_range A vector with CV values to be tested
#' @param length.out If the parameter ranges
#'
#' @details
#'
#' The ranges for mean and CV may be of any arbitrary length. If they are a given as a vector of length 2, the function will
#' assume that this represents the bounding range of a sequence of values. In this instance, a sequence of length equal to the
#' length.out parameter will be generated.
#'
#' @include Params.R
#'
#' @examples
#' my_likelihood <- CalcLognormalLikelihood(somedata, mean_range = c(50e3, 150e3), CV_range = c(0.3, 1.8))
#'
#' @export
#'
#' @importFrom purrrlyr by_row
#'
CalcLognormalLikelihood <- function(data, mean_range, CV_range, length.out = 100){
if (!is.numeric(data)) stop("data input must be numeric")
if (any(data <= 0)) stop("data input must be greater than zero")
if (any(mean_range <= 0 )) stop("mean_range must be greater than zero")
if (any(CV_range <= 0 )) stop("CV_range must be greater than zero")
if (length(mean_range) == 2) {
mean_range <- seq(from = mean_range[1], to = mean_range[2], length.out = length.out)
}
if (length(CV_range) == 2) {
CV_range <- seq(from = CV_range[1], to = CV_range[2], length.out = length.out)
}
dfL <- expand.grid(mean_range, CV_range)
rownames(dfL) <- NULL
names(dfL) <- c("Mean", "CV")
dfL <- purrrlyr::by_row(
dfL
, .to = "Likelihood"
, .collate = "rows"
, function(x){
lstParams <- LognormalParams(x$Mean, x$CV)
LognormalLikelihood(data, lstParams$mu, lstParams$sigma)
})
dfL
}
|
/R/Likelihood.R
|
no_license
|
PirateGrunt/momentus
|
R
| false | false | 1,812 |
r
|
LognormalLikelihood <- function(x, mu, sigma){
z <- (log(x) - mu) / sigma
lnL <- -z^2/2 - log(x) - log(sigma)
sum(lnL)
}
#' @title CalcLognormalLikelihood
#'
#' @param data A vector of sample observations
#' @param mean_range A vector with values of the mean
#' @param CV_range A vector with CV values to be tested
#' @param length.out If the parameter ranges
#'
#' @details
#'
#' The ranges for mean and CV may be of any arbitrary length. If they are a given as a vector of length 2, the function will
#' assume that this represents the bounding range of a sequence of values. In this instance, a sequence of length equal to the
#' length.out parameter will be generated.
#'
#' @include Params.R
#'
#' @examples
#' my_likelihood <- CalcLognormalLikelihood(somedata, mean_range = c(50e3, 150e3), CV_range = c(0.3, 1.8))
#'
#' @export
#'
#' @importFrom purrrlyr by_row
#'
CalcLognormalLikelihood <- function(data, mean_range, CV_range, length.out = 100){
if (!is.numeric(data)) stop("data input must be numeric")
if (any(data <= 0)) stop("data input must be greater than zero")
if (any(mean_range <= 0 )) stop("mean_range must be greater than zero")
if (any(CV_range <= 0 )) stop("CV_range must be greater than zero")
if (length(mean_range) == 2) {
mean_range <- seq(from = mean_range[1], to = mean_range[2], length.out = length.out)
}
if (length(CV_range) == 2) {
CV_range <- seq(from = CV_range[1], to = CV_range[2], length.out = length.out)
}
dfL <- expand.grid(mean_range, CV_range)
rownames(dfL) <- NULL
names(dfL) <- c("Mean", "CV")
dfL <- purrrlyr::by_row(
dfL
, .to = "Likelihood"
, .collate = "rows"
, function(x){
lstParams <- LognormalParams(x$Mean, x$CV)
LognormalLikelihood(data, lstParams$mu, lstParams$sigma)
})
dfL
}
|
#' @title Print Loess bootstrap model
#' @description print method for class "loess.boot"
#' @param x Object of class loess.boot
#' @param ... Ignored
#'
#' @method print loess.boot
#' @export
print.loess.boot <- function(x, ...) {
cat("Number of permutations: ", x$nreps, "\n", sep="")
cat("Loess alpha (span) parameter: ", x$span, "\n", sep="")
cat("Polynomial degree: ", x$degree, "\n", sep="")
cat("Data normalized: ", x$normalize, "\n", sep="")
cat("Model distribution: ", x$family, "\n", sep="")
cat("parametric model: ", x$parametric, "\n", sep="")
}
|
/spatialEco/R/print.loess.boot.R
|
no_license
|
albrizre/spatstat.revdep
|
R
| false | false | 574 |
r
|
#' @title Print Loess bootstrap model
#' @description print method for class "loess.boot"
#' @param x Object of class loess.boot
#' @param ... Ignored
#'
#' @method print loess.boot
#' @export
print.loess.boot <- function(x, ...) {
cat("Number of permutations: ", x$nreps, "\n", sep="")
cat("Loess alpha (span) parameter: ", x$span, "\n", sep="")
cat("Polynomial degree: ", x$degree, "\n", sep="")
cat("Data normalized: ", x$normalize, "\n", sep="")
cat("Model distribution: ", x$family, "\n", sep="")
cat("parametric model: ", x$parametric, "\n", sep="")
}
|
testlist <- list(id = NULL, score = NULL, id = NULL, booklet_id = integer(0), item_score = c(NA, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), person_id = integer(0))
result <- do.call(dexterMST:::mutate_booklet_score,testlist)
str(result)
|
/dexterMST/inst/testfiles/mutate_booklet_score/libFuzzer_mutate_booklet_score/mutate_booklet_score_valgrind_files/1612727633-test.R
|
no_license
|
akhikolla/updatedatatype-list1
|
R
| false | false | 540 |
r
|
testlist <- list(id = NULL, score = NULL, id = NULL, booklet_id = integer(0), item_score = c(NA, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), person_id = integer(0))
result <- do.call(dexterMST:::mutate_booklet_score,testlist)
str(result)
|
## Calculate square error projection from sscden objects
project.sscden1 <- function(object,include,...)
{
include <- unique(include)
term <- object$terms
mf <- object$mf
nobs <- dim(mf)[1]
xnames <- object$xnames
ynames <- object$ynames
xx.wt <- object$xx.wt
nx <- length(xx.wt)
xx <- mf[!object$x.dup.ind,xnames,drop=FALSE]
qd.pt <- object$rho$env$qd.pt
qd.wt <- object$rho$env$qd.wt
rho.d <- t(object$rho$fun(xx,qd.pt,object$rho$env,outer=TRUE))
rho.wt <- rho.d*qd.wt
rho.d <- t(t(log(rho.d))-apply(log(rho.d)*rho.wt,2,sum))
nmesh <- length(qd.wt)
ns <- length(object$id.s)
nr <- length(object$id.r)
nbasis <- length(object$id.basis)
s.rho <- ss <- 0
r.rho <- matrix(0,nbasis,nr)
sr <- array(0,c(ns,nbasis,nr))
rr <- array(0,c(nbasis,nbasis,nr,nr))
rho2 <- sum(xx.wt*apply(rho.d^2*rho.wt,2,sum))
for (k in 1:nx) {
id.x <- (1:nobs)[!object$x.dup.ind][k]
qd.s <- NULL
qd.r <- list(NULL)
iq <- 0
for (label in term$labels) {
vlist <- term[[label]]$vlist
x.list <- xnames[xnames%in%vlist]
y.list <- ynames[ynames%in%vlist]
xy.basis <- mf[object$id.basis,vlist]
qd.xy <- data.frame(matrix(0,nmesh,length(vlist)))
names(qd.xy) <- vlist
qd.xy[,y.list] <- qd.pt[,y.list]
if (length(x.list)) xx <- mf[rep(id.x,nmesh),x.list,drop=FALSE]
else xx <- NULL
nphi <- term[[label]]$nphi
nrk <- term[[label]]$nrk
if (nphi) {
phi <- term[[label]]$phi
for (i in 1:nphi) {
if (is.null(xx)) {
qd.s.wk <- phi$fun(qd.xy[,,drop=TRUE],nu=i,env=phi$env)
qd.s <- cbind(qd.s,qd.s.wk)
}
else {
if (length(y.list)>0) {
qd.xy[,x.list] <- xx
qd.s <- cbind(qd.s,phi$fun(qd.xy,i,phi$env))
}
}
}
}
if (nrk) {
rk <- term[[label]]$rk
for (i in 1:nrk) {
if (is.null(xx)) {
qd.r.wk <- rk$fun(qd.xy[,,drop=TRUE],xy.basis,nu=i,env=rk$env,TRUE)
iq <- iq+1
qd.r[[iq]] <- qd.r.wk
}
else {
if (length(y.list)>0) {
qd.xy[,x.list] <- xx
iq <- iq+1
qd.r[[iq]] <- rk$fun(qd.xy,xy.basis,i,rk$env,TRUE)
}
}
}
}
}
if (ns) {
qd.s <- sweep(qd.s,2,apply(qd.s*rho.wt[,k],2,sum))
s.rho <- s.rho + xx.wt[k]*apply(qd.s*rho.d[,k]*rho.wt[,k],2,sum)
ss <- ss + xx.wt[k]*t(rho.wt[,k]*qd.s)%*%qd.s
}
for (i in 1:iq) {
qd.r[[i]] <- sweep(qd.r[[i]],2,apply(qd.r[[i]]*rho.wt[,k],2,sum))
r.rho[,i] <- r.rho[,i] + xx.wt[k]*apply(qd.r[[i]]*rho.d[,k]*rho.wt[,k],2,sum)
if (ns) sr[,,i] <- sr[,,i] + xx.wt[k]*t(rho.wt[,k]*qd.s)%*%qd.r[[i]]
for (j in 1:i) {
rr.wk <- xx.wt[k]*t(rho.wt[,k]*qd.r[[i]])%*%qd.r[[j]]
rr[,,i,j] <- rr[,,i,j] + rr.wk
if (i-j) rr[,,j,i] <- rr[,,j,i] + t(rr.wk)
}
}
}
## evaluate full model
if (ns) d <- object$d[object$id.s]
c <- object$c
theta <- object$theta[object$id.r]
nq <- length(theta)
if (ns) s.eta <- ss%*%d
r.eta <- tmp <- NULL
r.rho.wk <- sr.wk <- rr.wk <- 0
for (i in 1:nq) {
tmp <- c(tmp,10^(2*theta[i])*sum(diag(rr[,,i,i])))
if (ns) {
s.eta <- s.eta + 10^theta[i]*sr[,,i]%*%c
if (length(d)==1) r.eta.wk <- sr[,,i]*d
else r.eta.wk <- t(sr[,,i])%*%d
sr.wk <- sr.wk + 10^theta[i]*sr[,,i]
}
else r.eta.wk <- 0
r.rho.wk <- r.rho.wk + 10^theta[i]*r.rho[,i]
for (j in 1:nq) {
r.eta.wk <- r.eta.wk + 10^theta[j]*rr[,,i,j]%*%c
rr.wk <- rr.wk + 10^(theta[i]+theta[j])*rr[,,i,j]
}
r.eta <- cbind(r.eta,r.eta.wk)
}
rho.eta <- sum(r.rho.wk*c)
if (ns) rho.eta <- rho.eta + sum(r.rho.wk*c)
eta2 <- sum(c*(rr.wk%*%c))
if (ns) eta2 <- eta2 + sum(d*(ss%*%d)) + 2*sum(d*(sr.wk%*%c))
mse <- eta2 + rho2 + 2*rho.eta
## extract terms in subspace
id.s <- id.r <- NULL
for (label in include) {
id.s <- c(id.s,object$id.s.list[[label]])
id.r <- c(id.r,object$id.r.list[[label]])
}
if (is.null(id.s)&is.null(id.r))
stop("gss error in project.sscden1: include some terms")
if (!all(id.s%in%object$id.s)|!all(id.r%in%object$id.r))
stop("gss error in project.sscden1: included terms are not in the model")
## calculate projection
rkl <- function(theta1=NULL) {
theta.wk <- 1:nq0
theta.wk[fix] <- theta[fix]
if (nq0-1) theta.wk[-fix] <- theta1
##
id.s0 <- (1:length(object$id.s))[object$id.s%in%id.s]
id.r0 <- (1:length(object$id.r))[object$id.r%in%id.r]
if (length(id.s0)) ss.wk <- ss[id.s0,id.s0,drop=FALSE]
if (length(id.r0)) {
r.eta.wk <- rr.wk <- 0
sr.wk <- matrix(0,length(id.s),nbasis)
for (i in 1:length(id.r0)) {
r.eta.wk <- r.eta.wk + 10^theta.wk[i]*r.eta[,id.r0[i]]
if (length(id.s0)) sr.wk <- sr.wk + 10^theta.wk[i]*sr[id.s0,,id.r0[i]]
for (j in 1:length(id.r0)) {
rr.wk <- rr.wk + 10^(theta.wk[i]+theta.wk[j])*rr[,,id.r0[i],id.r0[j]]
}
}
if (length(id.s0)) {
v <- cbind(rbind(ss.wk,t(sr.wk)),rbind(sr.wk,rr.wk))
mu <- c(s.eta[id.s0],r.eta.wk)
}
else {
v <- rbind(sr.wk,rr.wk)
mu <- r.eta.wk
}
}
else {
v <- ss.wk
mu <- s.eta[id.s0]
}
nn <- length(mu)
z <- chol(v,pivot=TRUE)
v <- z
rkv <- attr(z,"rank")
m.eps <- .Machine$double.eps
while (v[rkv,rkv]<2*sqrt(m.eps)*v[1,1]) rkv <- rkv - 1
if (rkv<nn) v[(1:nn)>rkv,(1:nn)>rkv] <- diag(v[1,1],nn-rkv)
mu <- backsolve(v,mu[attr(z,"pivot")],transpose=TRUE)
eta2 - sum(mu[1:rkv]^2)
}
cv.wk <- function(theta) cv.scale*rkl(theta)+cv.shift
## initialization
fix <- rev(order(tmp[id.r]))[1]
theta <- object$theta[id.r]
## projection
nq0 <- length(id.r)
if (nq0>1) {
if (object$skip.iter) se <- rkl(theta[-fix])
else {
if (nq0-2) {
## scale and shift cv
tmp <- abs(rkl(theta[-fix]))
cv.scale <- 1
cv.shift <- 0
if (tmp<1&tmp>10^(-4)) {
cv.scale <- 10/tmp
cv.shift <- 0
}
if (tmp<10^(-4)) {
cv.scale <- 10^2
cv.shift <- 10
}
zz <- nlm(cv.wk,theta[-fix],stepmax=.5,ndigit=7)
}
else {
the.wk <- theta[-fix]
repeat {
mn <- the.wk-1
mx <- the.wk+1
zz <- nlm0(rkl,c(mn,mx))
if (min(zz$est-mn,mx-zz$est)>=1e-3) break
else the.wk <- zz$est
}
}
se <- rkl(zz$est)
}
}
else se <- rkl()
list(ratio=se/mse,se=se)
}
|
/R/project.sscden1.R
|
no_license
|
weirichd/gss
|
R
| false | false | 7,797 |
r
|
## Calculate square error projection from sscden objects
project.sscden1 <- function(object,include,...)
{
include <- unique(include)
term <- object$terms
mf <- object$mf
nobs <- dim(mf)[1]
xnames <- object$xnames
ynames <- object$ynames
xx.wt <- object$xx.wt
nx <- length(xx.wt)
xx <- mf[!object$x.dup.ind,xnames,drop=FALSE]
qd.pt <- object$rho$env$qd.pt
qd.wt <- object$rho$env$qd.wt
rho.d <- t(object$rho$fun(xx,qd.pt,object$rho$env,outer=TRUE))
rho.wt <- rho.d*qd.wt
rho.d <- t(t(log(rho.d))-apply(log(rho.d)*rho.wt,2,sum))
nmesh <- length(qd.wt)
ns <- length(object$id.s)
nr <- length(object$id.r)
nbasis <- length(object$id.basis)
s.rho <- ss <- 0
r.rho <- matrix(0,nbasis,nr)
sr <- array(0,c(ns,nbasis,nr))
rr <- array(0,c(nbasis,nbasis,nr,nr))
rho2 <- sum(xx.wt*apply(rho.d^2*rho.wt,2,sum))
for (k in 1:nx) {
id.x <- (1:nobs)[!object$x.dup.ind][k]
qd.s <- NULL
qd.r <- list(NULL)
iq <- 0
for (label in term$labels) {
vlist <- term[[label]]$vlist
x.list <- xnames[xnames%in%vlist]
y.list <- ynames[ynames%in%vlist]
xy.basis <- mf[object$id.basis,vlist]
qd.xy <- data.frame(matrix(0,nmesh,length(vlist)))
names(qd.xy) <- vlist
qd.xy[,y.list] <- qd.pt[,y.list]
if (length(x.list)) xx <- mf[rep(id.x,nmesh),x.list,drop=FALSE]
else xx <- NULL
nphi <- term[[label]]$nphi
nrk <- term[[label]]$nrk
if (nphi) {
phi <- term[[label]]$phi
for (i in 1:nphi) {
if (is.null(xx)) {
qd.s.wk <- phi$fun(qd.xy[,,drop=TRUE],nu=i,env=phi$env)
qd.s <- cbind(qd.s,qd.s.wk)
}
else {
if (length(y.list)>0) {
qd.xy[,x.list] <- xx
qd.s <- cbind(qd.s,phi$fun(qd.xy,i,phi$env))
}
}
}
}
if (nrk) {
rk <- term[[label]]$rk
for (i in 1:nrk) {
if (is.null(xx)) {
qd.r.wk <- rk$fun(qd.xy[,,drop=TRUE],xy.basis,nu=i,env=rk$env,TRUE)
iq <- iq+1
qd.r[[iq]] <- qd.r.wk
}
else {
if (length(y.list)>0) {
qd.xy[,x.list] <- xx
iq <- iq+1
qd.r[[iq]] <- rk$fun(qd.xy,xy.basis,i,rk$env,TRUE)
}
}
}
}
}
if (ns) {
qd.s <- sweep(qd.s,2,apply(qd.s*rho.wt[,k],2,sum))
s.rho <- s.rho + xx.wt[k]*apply(qd.s*rho.d[,k]*rho.wt[,k],2,sum)
ss <- ss + xx.wt[k]*t(rho.wt[,k]*qd.s)%*%qd.s
}
for (i in 1:iq) {
qd.r[[i]] <- sweep(qd.r[[i]],2,apply(qd.r[[i]]*rho.wt[,k],2,sum))
r.rho[,i] <- r.rho[,i] + xx.wt[k]*apply(qd.r[[i]]*rho.d[,k]*rho.wt[,k],2,sum)
if (ns) sr[,,i] <- sr[,,i] + xx.wt[k]*t(rho.wt[,k]*qd.s)%*%qd.r[[i]]
for (j in 1:i) {
rr.wk <- xx.wt[k]*t(rho.wt[,k]*qd.r[[i]])%*%qd.r[[j]]
rr[,,i,j] <- rr[,,i,j] + rr.wk
if (i-j) rr[,,j,i] <- rr[,,j,i] + t(rr.wk)
}
}
}
## evaluate full model
if (ns) d <- object$d[object$id.s]
c <- object$c
theta <- object$theta[object$id.r]
nq <- length(theta)
if (ns) s.eta <- ss%*%d
r.eta <- tmp <- NULL
r.rho.wk <- sr.wk <- rr.wk <- 0
for (i in 1:nq) {
tmp <- c(tmp,10^(2*theta[i])*sum(diag(rr[,,i,i])))
if (ns) {
s.eta <- s.eta + 10^theta[i]*sr[,,i]%*%c
if (length(d)==1) r.eta.wk <- sr[,,i]*d
else r.eta.wk <- t(sr[,,i])%*%d
sr.wk <- sr.wk + 10^theta[i]*sr[,,i]
}
else r.eta.wk <- 0
r.rho.wk <- r.rho.wk + 10^theta[i]*r.rho[,i]
for (j in 1:nq) {
r.eta.wk <- r.eta.wk + 10^theta[j]*rr[,,i,j]%*%c
rr.wk <- rr.wk + 10^(theta[i]+theta[j])*rr[,,i,j]
}
r.eta <- cbind(r.eta,r.eta.wk)
}
rho.eta <- sum(r.rho.wk*c)
if (ns) rho.eta <- rho.eta + sum(r.rho.wk*c)
eta2 <- sum(c*(rr.wk%*%c))
if (ns) eta2 <- eta2 + sum(d*(ss%*%d)) + 2*sum(d*(sr.wk%*%c))
mse <- eta2 + rho2 + 2*rho.eta
## extract terms in subspace
id.s <- id.r <- NULL
for (label in include) {
id.s <- c(id.s,object$id.s.list[[label]])
id.r <- c(id.r,object$id.r.list[[label]])
}
if (is.null(id.s)&is.null(id.r))
stop("gss error in project.sscden1: include some terms")
if (!all(id.s%in%object$id.s)|!all(id.r%in%object$id.r))
stop("gss error in project.sscden1: included terms are not in the model")
## calculate projection
rkl <- function(theta1=NULL) {
theta.wk <- 1:nq0
theta.wk[fix] <- theta[fix]
if (nq0-1) theta.wk[-fix] <- theta1
##
id.s0 <- (1:length(object$id.s))[object$id.s%in%id.s]
id.r0 <- (1:length(object$id.r))[object$id.r%in%id.r]
if (length(id.s0)) ss.wk <- ss[id.s0,id.s0,drop=FALSE]
if (length(id.r0)) {
r.eta.wk <- rr.wk <- 0
sr.wk <- matrix(0,length(id.s),nbasis)
for (i in 1:length(id.r0)) {
r.eta.wk <- r.eta.wk + 10^theta.wk[i]*r.eta[,id.r0[i]]
if (length(id.s0)) sr.wk <- sr.wk + 10^theta.wk[i]*sr[id.s0,,id.r0[i]]
for (j in 1:length(id.r0)) {
rr.wk <- rr.wk + 10^(theta.wk[i]+theta.wk[j])*rr[,,id.r0[i],id.r0[j]]
}
}
if (length(id.s0)) {
v <- cbind(rbind(ss.wk,t(sr.wk)),rbind(sr.wk,rr.wk))
mu <- c(s.eta[id.s0],r.eta.wk)
}
else {
v <- rbind(sr.wk,rr.wk)
mu <- r.eta.wk
}
}
else {
v <- ss.wk
mu <- s.eta[id.s0]
}
nn <- length(mu)
z <- chol(v,pivot=TRUE)
v <- z
rkv <- attr(z,"rank")
m.eps <- .Machine$double.eps
while (v[rkv,rkv]<2*sqrt(m.eps)*v[1,1]) rkv <- rkv - 1
if (rkv<nn) v[(1:nn)>rkv,(1:nn)>rkv] <- diag(v[1,1],nn-rkv)
mu <- backsolve(v,mu[attr(z,"pivot")],transpose=TRUE)
eta2 - sum(mu[1:rkv]^2)
}
cv.wk <- function(theta) cv.scale*rkl(theta)+cv.shift
## initialization
fix <- rev(order(tmp[id.r]))[1]
theta <- object$theta[id.r]
## projection
nq0 <- length(id.r)
if (nq0>1) {
if (object$skip.iter) se <- rkl(theta[-fix])
else {
if (nq0-2) {
## scale and shift cv
tmp <- abs(rkl(theta[-fix]))
cv.scale <- 1
cv.shift <- 0
if (tmp<1&tmp>10^(-4)) {
cv.scale <- 10/tmp
cv.shift <- 0
}
if (tmp<10^(-4)) {
cv.scale <- 10^2
cv.shift <- 10
}
zz <- nlm(cv.wk,theta[-fix],stepmax=.5,ndigit=7)
}
else {
the.wk <- theta[-fix]
repeat {
mn <- the.wk-1
mx <- the.wk+1
zz <- nlm0(rkl,c(mn,mx))
if (min(zz$est-mn,mx-zz$est)>=1e-3) break
else the.wk <- zz$est
}
}
se <- rkl(zz$est)
}
}
else se <- rkl()
list(ratio=se/mse,se=se)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot_functions.R
\name{omicsContrib}
\alias{omicsContrib}
\title{Plot the omics contribution per MFA axis and the overall weighted
contribution}
\usage{
omicsContrib(
padma_obj,
max_dim = min(10, nrow(MFA_results(padma_obj)$eig)),
ggplot = TRUE
)
}
\arguments{
\item{padma_obj}{Output from running the \code{padma} function
(with \code{'full_results = TRUE'})}
\item{max_dim}{Maximum dimension number of the MFA to be plotted}
\item{ggplot}{If \code{TRUE}, use \code{ggplot2} for plotting (and
\code{cowplot} for combining ggplots)}
}
\value{
Barplots of percent variance contribution, optionally of class
\code{ggplot}.
}
\description{
Plot barplots indicating the percent contribution of each omics to each MFA
dimension, as well as the overall weighted (by eigenvalue) percent
contribution to the full analysis.
}
\examples{
LUAD_subset <- padma::LUAD_subset
## Create MultiAssayExperiment object with LUAD data
omics_data <-
list(rnaseq = LUAD_subset$rnaseq,
methyl = LUAD_subset$methyl,
mirna = LUAD_subset$mirna,
cna = LUAD_subset$cna)
pheno_data <-
data.frame(LUAD_subset$clinical,
row.names = LUAD_subset$clinical$bcr_patient_barcode)
mae <-
suppressMessages(
MultiAssayExperiment::MultiAssayExperiment(
experiments = omics_data, colData = pheno_data))
## Run padma
run_padma <-
padma(mae, gene_map = padma::mirtarbase,
pathway_name = "c2_cp_BIOCARTA_D4GDI_PATHWAY", verbose = FALSE)
summary(run_padma)
## padma plots
factorMap(run_padma, dim_x = 1, dim_y = 2)
factorMap(run_padma, dim_x = 1, dim_y = 2,
partial_id = "TCGA-78-7536")
omicsContrib(run_padma, max_dim = 10)
}
|
/man/omicsContrib.Rd
|
no_license
|
lwaldron/padma
|
R
| false | true | 1,750 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot_functions.R
\name{omicsContrib}
\alias{omicsContrib}
\title{Plot the omics contribution per MFA axis and the overall weighted
contribution}
\usage{
omicsContrib(
padma_obj,
max_dim = min(10, nrow(MFA_results(padma_obj)$eig)),
ggplot = TRUE
)
}
\arguments{
\item{padma_obj}{Output from running the \code{padma} function
(with \code{'full_results = TRUE'})}
\item{max_dim}{Maximum dimension number of the MFA to be plotted}
\item{ggplot}{If \code{TRUE}, use \code{ggplot2} for plotting (and
\code{cowplot} for combining ggplots)}
}
\value{
Barplots of percent variance contribution, optionally of class
\code{ggplot}.
}
\description{
Plot barplots indicating the percent contribution of each omics to each MFA
dimension, as well as the overall weighted (by eigenvalue) percent
contribution to the full analysis.
}
\examples{
LUAD_subset <- padma::LUAD_subset
## Create MultiAssayExperiment object with LUAD data
omics_data <-
list(rnaseq = LUAD_subset$rnaseq,
methyl = LUAD_subset$methyl,
mirna = LUAD_subset$mirna,
cna = LUAD_subset$cna)
pheno_data <-
data.frame(LUAD_subset$clinical,
row.names = LUAD_subset$clinical$bcr_patient_barcode)
mae <-
suppressMessages(
MultiAssayExperiment::MultiAssayExperiment(
experiments = omics_data, colData = pheno_data))
## Run padma
run_padma <-
padma(mae, gene_map = padma::mirtarbase,
pathway_name = "c2_cp_BIOCARTA_D4GDI_PATHWAY", verbose = FALSE)
summary(run_padma)
## padma plots
factorMap(run_padma, dim_x = 1, dim_y = 2)
factorMap(run_padma, dim_x = 1, dim_y = 2,
partial_id = "TCGA-78-7536")
omicsContrib(run_padma, max_dim = 10)
}
|
# ----------------------------------------------
# Caitlin O'Brien-Carelli
# Prep incidence and mortality data from WHO/UNAIDS
# Set function arguments to determine which data sources
# ----------------------------------------------
# --------------------
# Set up R
rm(list=ls())
library(data.table)
library(ggplot2)
library(RColorBrewer)
library(stringr)
options(scipen=999)
# --------------------
# detect the user
user = Sys.info()[['user']]
#--------------------------------
# set directories
# detect if operating on windows or on the cluster
j = ifelse(Sys.info()[1]=='Windows', 'J:', '/home/j')
# set the directory for input and output
dir = paste0(j, '/Project/Evaluation/GF/impact_evaluation/synthesis_epidemiology/')
code_dir = paste0('C:/Users/', user, '/local/gf/impact_evaluation/gbd_epidemiology/')
outDir = paste0(j, '/Project/Evaluation/GF/impact_evaluation/synthesis_epidemiology/')
#-----------------------------------------------------------------
# read in who tb
tb = fread(paste0(dir, 'raw_data/who_tb/TB_burden_countries_2020-01-21.csv'))
#---------------------------------
# before subsetting, get a global population estimate
global_pop = tb[ ,.(population = sum(e_pop_num)), by=year]
global_pop[ ,location:='Global'] # use for hiv estimates
#---------------------------------
# calculate global incidence and mortality for tb
# merge in later
# sum everything to the global level, shape long and subset
glob_tb = tb[ ,lapply(.SD, sum, na.rm=T), .SDcols=7:50, by=year]
glob_tb = melt(glob_tb, id.vars='year')
keep_glob = c('year', 'e_pop_num', 'e_inc_num', 'e_inc_num_hi', 'e_inc_num_lo',
'e_mort_num', 'e_mort_num_hi', 'e_mort_num_lo')
glob_tb = glob_tb[variable %in% keep_glob]
# shape wide and calculate
glob_tb = dcast(glob_tb, year~variable)
glob_tb[ ,pop_factor:=e_pop_num/100000]
glob_tb_rates = glob_tb[ ,lapply(.SD, function(x) x = x/pop_factor), .SDcols=3:8, by=.(year, pop_factor)]
glob_tb_rates[ ,pop_factor:=NULL]
glob_tb[ ,c('pop_factor', 'e_pop_num'):=NULL]
# keep mortality and incidence rates and counts
setnames(glob_tb_rates, c("year", "e_inc_num", "e_inc_num_lo",
"e_inc_num_hi", "e_mort_num", "e_mort_num_lo", "e_mort_num_hi"),
c('year', 'e_inc_100k', 'e_inc_100k_lo', 'e_inc_100k_hi',
'e_mort_100k', 'e_mort_100k_lo', 'e_mort_100k_hi'))
glob_tb = merge(glob_tb, glob_tb_rates)
glob_tb = melt(glob_tb, id.vars = 'year')
glob_tb[ ,location:='Global']
#--------------------------------
# subset and rename variables
countries = c("Cambodia", "Democratic Republic of the Congo",
"Guatemala", "Mozambique", "Myanmar", "Senegal", "Sudan", "Uganda", "Global")
# subset to relevant countries, does not include global estimates
tb = tb[country %in% countries]
# --------------------------------------
# extract population data and use later to calculate hiv mortality rates
pop = tb[ ,.(population = e_pop_num), by = .(country, year)]
setnames(pop, 'country', 'location')
pop = rbind(pop, global_pop)
# --------------------------------------
# PREP TB DATA
# drop unecessary variables and shape long
tb[ ,c('iso2', 'iso3', 'iso_numeric', 'g_whoregion'):=NULL]
tb = melt(tb, id.vars = c('country', 'year')) # some are numerics and some integers
# keep mortality and incidence rates and counts
keep = c('country', 'year', 'e_inc_100k', 'e_inc_100k_hi', 'e_inc_100k_lo',
'e_mort_100k', 'e_mort_100k_hi', 'e_mort_100k_lo',
'e_inc_num', 'e_inc_num_hi', 'e_inc_num_lo',
'e_mort_num', 'e_mort_num_hi', 'e_mort_num_lo')
tb = tb[variable %in% keep]
setnames(tb, 'country', 'location')
# add in global data
tb = rbind(tb, glob_tb)
# format to match
tb[grepl('hi', variable), bound:='upper']
tb[grepl('lo', variable), bound:='lower']
tb[!grepl('lo', variable) & !grepl('hi', variable), bound:='val']
# designate mortality and incidence, rates and counts
tb[grepl('mort', variable), measure:='Deaths']
tb[grepl('inc', variable), measure:='Incidence']
tb[grepl('100k', variable), metric:='Rate']
tb[!grepl('100k', variable), metric:='Number']
# add age
tb[metric=='Number', age:='All Ages']
tb[metric=='Rate', age:='Age-standardized']
# add variables not included in the data
tb[ ,sex:='Both']
tb[ ,cause:='Tuberculosis']
tb[ ,variable:=NULL]
tb = dcast(tb, measure+location+sex+age+cause+metric+year~bound)
#---------------------
# output prepped tb data
saveRDS(tb, paste0(outDir, 'prepped_data/who_tb_2000_2018_prepped.rds'))
#---------------------
#-------------------------------------------------------
# PREP HIV DATA
#------------------------
# upload and prep unaids data
hiv = fread(paste0(dir, 'raw_data/unaids/New HIV infections_HIV incidence per 1000 population_Population_ All ages.csv'))
hiv2 = fread(paste0(dir, 'raw_data/unaids/AIDS-related deaths_Number of AIDS-related deaths_Population_ All ages.csv'))
hiv3 = fread(paste0(dir, 'raw_data/unaids/new_hiv_infections_counts.csv'))
#----------------
# write a function to format the unaids data
format = function(x) {
# rename the columns and drop the first row as it imports weird
name_list = as.character(x[1])
setnames(x, name_list)
x = x[-1]
# subset and shape long
x = x[Country %in% countries]
setnames(x, 'Country', 'location')
x = melt(x, id.vars='location')
return(x)}
#----------------
#------------------------
# format the data and bind them together
hiv = format(hiv)
hiv2 = format(hiv2)
hiv3 = format(hiv3)
hiv[ ,measure:='Incidence']
hiv[ , metric:='Rate']
hiv2[ , measure:='Deaths']
hiv2[ , metric:='Number']
#--------------------------
hiv = rbind(hiv, hiv2)
hiv[metric=='Number', age:='All Ages']
hiv[metric=='Rate', age:='Age-standardized']# check if age standardized
# shape wide
hiv[grepl('upper', variable), bound:='upper']
hiv[grepl('lower', variable), bound:='lower']
hiv[!grepl('lower', variable) & !grepl('upper', variable), bound:='val']
# split and add year
hiv$year = unlist(lapply(str_split(hiv$variable, '_'), '[', 1))
hiv[ ,variable:=NULL]
hiv = dcast(hiv, location+measure+metric+age+year~bound)
#------------------------
# new infection counts need special wrangling
# reset names and develop bounds
setnames(hiv3, 'variable', 'year')
hiv3$val = trimws(unlist(lapply(str_split(hiv3$value, '\\['), '[', 1)))
hiv3$lower = trimws(unlist(lapply(str_split(hiv3$value, '\\['), '[', 2)))
hiv3$lower = trimws(unlist(lapply(str_split(hiv3$lower, '\\-'), '[', 1))) #split twice for lower bound
hiv3$upper = trimws(unlist(lapply(str_split(hiv3$value, '\\['), '[', 2)))
hiv3$upper = trimws(unlist(lapply(str_split(hiv3$upper, '\\-'), '[', 2)))
hiv3[ ,upper:=gsub('\\]', '', upper)]
hiv3[ ,value:=NULL]
# add in identifiers
hiv3[ ,age:='All Ages']
hiv3[ ,measure:='Incidence']
hiv3[ , metric:='Number']
hiv = rbind(hiv, hiv3)
#--------------------------------------------------
# final formatting of numbers for the merge
# if the estimate is listed as "less than," delete from the data
hiv[grep('<', val)][order(location, year)]
hiv = hiv[!grepl('<', val)]
# only one estimate for cambodia has a less than, in 1990
hiv = hiv[!grepl('<', upper)]
# if the lower bound is listed as less than 1,000, estimate as 0
hiv[grepl('<', lower), lower:=0]
# trim the spaces from the values
hiv[ ,val:=as.numeric(gsub(' ', '', val))]
hiv[ ,lower:=as.numeric(gsub(' ', '', lower))]
hiv[ ,upper:=as.numeric(gsub(' ', '', upper))]
# add the cause
hiv[ ,cause:='HIV/AIDS']
hiv[ ,sex:='Both']
# confirm year is a numeric
hiv[, year:=as.numeric(as.character(year))]
#--------------------------
# hiv rates are per 1,000 - convert to rate per 100k
hiv[metric == 'Rate' , val:=100*val]
hiv[metric == 'Rate' , lower:=100*lower]
hiv[metric == 'Rate' , upper:=100*upper]
#--------------------------------------------------
# calculate mortality rates
death_rates = hiv[measure=='Deaths' & 2000 <= year]
death_rates = merge(death_rates, pop, by=c('location','year'))
# create rates
death_rates[ ,population:=(population/100000)]
death_rates[ ,val:=val/population]
death_rates[ ,lower:=lower/population]
death_rates[ ,upper:=upper/population]
death_rates[ ,metric:='Rate']
death_rates[ ,age:='Age-standardized']
death_rates[ ,population:=NULL]
# bind death rates into the data
hiv = rbind(hiv, death_rates)
#--------------------------------------------------
# save the data set and bind tb and hiv together
# output prepped hiv data
saveRDS(hiv, paste0(outDir, 'prepped_data/unaids_hiv_2000_2018_prepped.rds'))
# bind the data sets together
tb_hiv = rbind(tb, hiv)
#-------------------------------------------------------
# prep malaria data
mal = readRDS(paste0(dir, 'raw_data/who_malaria/estimated_malaria_cases_and_deaths_2010_2018.rds'))
mal = mal[country!='South Sudan']
# format the data and shape long
setnames(mal, 'country', 'location')
mal[ ,sex:='Both']
mal[ ,population_at_risk:=NULL]
mal = melt(mal, id.vars=c('location', 'year', 'sex'))
# format to match
mal[grepl('upper', variable), bound:='upper']
mal[grepl('lower', variable), bound:='lower']
mal[grepl('point', variable), bound:='val']
# designate mortality and incidence, rates and counts
mal[grepl('deaths', variable) | grepl('mortality', variable) , measure:='Deaths']
mal[grepl('inc', variable) | grepl('cases', variable), measure:='Incidence']
mal[grepl('inc', variable) | grepl('mortality', variable), metric:='Rate']
mal[grepl('deaths', variable) | grepl('cases', variable), metric:='Number']
# add age
mal[metric=='Number', age:='All Ages']
mal[metric=='Rate', age:='Age-standardized']
# add variables not included in the data
mal[ ,sex:='Both']
mal[ ,cause:='Malaria']
mal[ ,variable:=NULL]
# shape wide
mal = dcast(mal, measure+location+sex+age+cause+metric+year~bound)
# match locations in other data
mal[location=='DRC', location:='Democratic Republic of the Congo']
#--------------------------------------------------
# save the data set and bind tb and hiv together
# output prepped hiv data
saveRDS(mal, paste0(outDir, 'prepped_data/who_malaria_2010_2018_prepped.rds'))
# bind the data sets together
dt = rbind(tb_hiv, mal)
# ensure year is not a factor
dt[ ,year:=as.numeric(as.character(year))]
#------------------------------------------------
# save the final product
saveRDS(dt, paste0(outDir, 'prepped_data/who_unaids_prepped.rds'))
#------------------------------------------------
|
/impact_evaluation/synthesis/1_prep_who_unaids_data.R
|
no_license
|
ihmeuw/gf
|
R
| false | false | 10,343 |
r
|
# ----------------------------------------------
# Caitlin O'Brien-Carelli
# Prep incidence and mortality data from WHO/UNAIDS
# Set function arguments to determine which data sources
# ----------------------------------------------
# --------------------
# Set up R
rm(list=ls())
library(data.table)
library(ggplot2)
library(RColorBrewer)
library(stringr)
options(scipen=999)
# --------------------
# detect the user
user = Sys.info()[['user']]
#--------------------------------
# set directories
# detect if operating on windows or on the cluster
j = ifelse(Sys.info()[1]=='Windows', 'J:', '/home/j')
# set the directory for input and output
dir = paste0(j, '/Project/Evaluation/GF/impact_evaluation/synthesis_epidemiology/')
code_dir = paste0('C:/Users/', user, '/local/gf/impact_evaluation/gbd_epidemiology/')
outDir = paste0(j, '/Project/Evaluation/GF/impact_evaluation/synthesis_epidemiology/')
#-----------------------------------------------------------------
# read in who tb
tb = fread(paste0(dir, 'raw_data/who_tb/TB_burden_countries_2020-01-21.csv'))
#---------------------------------
# before subsetting, get a global population estimate
global_pop = tb[ ,.(population = sum(e_pop_num)), by=year]
global_pop[ ,location:='Global'] # use for hiv estimates
#---------------------------------
# calculate global incidence and mortality for tb
# merge in later
# sum everything to the global level, shape long and subset
glob_tb = tb[ ,lapply(.SD, sum, na.rm=T), .SDcols=7:50, by=year]
glob_tb = melt(glob_tb, id.vars='year')
keep_glob = c('year', 'e_pop_num', 'e_inc_num', 'e_inc_num_hi', 'e_inc_num_lo',
'e_mort_num', 'e_mort_num_hi', 'e_mort_num_lo')
glob_tb = glob_tb[variable %in% keep_glob]
# shape wide and calculate
glob_tb = dcast(glob_tb, year~variable)
glob_tb[ ,pop_factor:=e_pop_num/100000]
glob_tb_rates = glob_tb[ ,lapply(.SD, function(x) x = x/pop_factor), .SDcols=3:8, by=.(year, pop_factor)]
glob_tb_rates[ ,pop_factor:=NULL]
glob_tb[ ,c('pop_factor', 'e_pop_num'):=NULL]
# keep mortality and incidence rates and counts
setnames(glob_tb_rates, c("year", "e_inc_num", "e_inc_num_lo",
"e_inc_num_hi", "e_mort_num", "e_mort_num_lo", "e_mort_num_hi"),
c('year', 'e_inc_100k', 'e_inc_100k_lo', 'e_inc_100k_hi',
'e_mort_100k', 'e_mort_100k_lo', 'e_mort_100k_hi'))
glob_tb = merge(glob_tb, glob_tb_rates)
glob_tb = melt(glob_tb, id.vars = 'year')
glob_tb[ ,location:='Global']
#--------------------------------
# subset and rename variables
countries = c("Cambodia", "Democratic Republic of the Congo",
"Guatemala", "Mozambique", "Myanmar", "Senegal", "Sudan", "Uganda", "Global")
# subset to relevant countries, does not include global estimates
tb = tb[country %in% countries]
# --------------------------------------
# extract population data and use later to calculate hiv mortality rates
pop = tb[ ,.(population = e_pop_num), by = .(country, year)]
setnames(pop, 'country', 'location')
pop = rbind(pop, global_pop)
# --------------------------------------
# PREP TB DATA
# drop unecessary variables and shape long
tb[ ,c('iso2', 'iso3', 'iso_numeric', 'g_whoregion'):=NULL]
tb = melt(tb, id.vars = c('country', 'year')) # some are numerics and some integers
# keep mortality and incidence rates and counts
keep = c('country', 'year', 'e_inc_100k', 'e_inc_100k_hi', 'e_inc_100k_lo',
'e_mort_100k', 'e_mort_100k_hi', 'e_mort_100k_lo',
'e_inc_num', 'e_inc_num_hi', 'e_inc_num_lo',
'e_mort_num', 'e_mort_num_hi', 'e_mort_num_lo')
tb = tb[variable %in% keep]
setnames(tb, 'country', 'location')
# add in global data
tb = rbind(tb, glob_tb)
# format to match
tb[grepl('hi', variable), bound:='upper']
tb[grepl('lo', variable), bound:='lower']
tb[!grepl('lo', variable) & !grepl('hi', variable), bound:='val']
# designate mortality and incidence, rates and counts
tb[grepl('mort', variable), measure:='Deaths']
tb[grepl('inc', variable), measure:='Incidence']
tb[grepl('100k', variable), metric:='Rate']
tb[!grepl('100k', variable), metric:='Number']
# add age
tb[metric=='Number', age:='All Ages']
tb[metric=='Rate', age:='Age-standardized']
# add variables not included in the data
tb[ ,sex:='Both']
tb[ ,cause:='Tuberculosis']
tb[ ,variable:=NULL]
tb = dcast(tb, measure+location+sex+age+cause+metric+year~bound)
#---------------------
# output prepped tb data
saveRDS(tb, paste0(outDir, 'prepped_data/who_tb_2000_2018_prepped.rds'))
#---------------------
#-------------------------------------------------------
# PREP HIV DATA
#------------------------
# upload and prep unaids data
hiv = fread(paste0(dir, 'raw_data/unaids/New HIV infections_HIV incidence per 1000 population_Population_ All ages.csv'))
hiv2 = fread(paste0(dir, 'raw_data/unaids/AIDS-related deaths_Number of AIDS-related deaths_Population_ All ages.csv'))
hiv3 = fread(paste0(dir, 'raw_data/unaids/new_hiv_infections_counts.csv'))
#----------------
# write a function to format the unaids data
format = function(x) {
# rename the columns and drop the first row as it imports weird
name_list = as.character(x[1])
setnames(x, name_list)
x = x[-1]
# subset and shape long
x = x[Country %in% countries]
setnames(x, 'Country', 'location')
x = melt(x, id.vars='location')
return(x)}
#----------------
#------------------------
# format the data and bind them together
hiv = format(hiv)
hiv2 = format(hiv2)
hiv3 = format(hiv3)
hiv[ ,measure:='Incidence']
hiv[ , metric:='Rate']
hiv2[ , measure:='Deaths']
hiv2[ , metric:='Number']
#--------------------------
hiv = rbind(hiv, hiv2)
hiv[metric=='Number', age:='All Ages']
hiv[metric=='Rate', age:='Age-standardized']# check if age standardized
# shape wide
hiv[grepl('upper', variable), bound:='upper']
hiv[grepl('lower', variable), bound:='lower']
hiv[!grepl('lower', variable) & !grepl('upper', variable), bound:='val']
# split and add year
hiv$year = unlist(lapply(str_split(hiv$variable, '_'), '[', 1))
hiv[ ,variable:=NULL]
hiv = dcast(hiv, location+measure+metric+age+year~bound)
#------------------------
# new infection counts need special wrangling
# reset names and develop bounds
setnames(hiv3, 'variable', 'year')
hiv3$val = trimws(unlist(lapply(str_split(hiv3$value, '\\['), '[', 1)))
hiv3$lower = trimws(unlist(lapply(str_split(hiv3$value, '\\['), '[', 2)))
hiv3$lower = trimws(unlist(lapply(str_split(hiv3$lower, '\\-'), '[', 1))) #split twice for lower bound
hiv3$upper = trimws(unlist(lapply(str_split(hiv3$value, '\\['), '[', 2)))
hiv3$upper = trimws(unlist(lapply(str_split(hiv3$upper, '\\-'), '[', 2)))
hiv3[ ,upper:=gsub('\\]', '', upper)]
hiv3[ ,value:=NULL]
# add in identifiers
hiv3[ ,age:='All Ages']
hiv3[ ,measure:='Incidence']
hiv3[ , metric:='Number']
hiv = rbind(hiv, hiv3)
#--------------------------------------------------
# final formatting of numbers for the merge
# if the estimate is listed as "less than," delete from the data
hiv[grep('<', val)][order(location, year)]
hiv = hiv[!grepl('<', val)]
# only one estimate for cambodia has a less than, in 1990
hiv = hiv[!grepl('<', upper)]
# if the lower bound is listed as less than 1,000, estimate as 0
hiv[grepl('<', lower), lower:=0]
# trim the spaces from the values
hiv[ ,val:=as.numeric(gsub(' ', '', val))]
hiv[ ,lower:=as.numeric(gsub(' ', '', lower))]
hiv[ ,upper:=as.numeric(gsub(' ', '', upper))]
# add the cause
hiv[ ,cause:='HIV/AIDS']
hiv[ ,sex:='Both']
# confirm year is a numeric
hiv[, year:=as.numeric(as.character(year))]
#--------------------------
# hiv rates are per 1,000 - convert to rate per 100k
hiv[metric == 'Rate' , val:=100*val]
hiv[metric == 'Rate' , lower:=100*lower]
hiv[metric == 'Rate' , upper:=100*upper]
#--------------------------------------------------
# calculate mortality rates
death_rates = hiv[measure=='Deaths' & 2000 <= year]
death_rates = merge(death_rates, pop, by=c('location','year'))
# create rates
death_rates[ ,population:=(population/100000)]
death_rates[ ,val:=val/population]
death_rates[ ,lower:=lower/population]
death_rates[ ,upper:=upper/population]
death_rates[ ,metric:='Rate']
death_rates[ ,age:='Age-standardized']
death_rates[ ,population:=NULL]
# bind death rates into the data
hiv = rbind(hiv, death_rates)
#--------------------------------------------------
# save the data set and bind tb and hiv together
# output prepped hiv data
saveRDS(hiv, paste0(outDir, 'prepped_data/unaids_hiv_2000_2018_prepped.rds'))
# bind the data sets together
tb_hiv = rbind(tb, hiv)
#-------------------------------------------------------
# prep malaria data
mal = readRDS(paste0(dir, 'raw_data/who_malaria/estimated_malaria_cases_and_deaths_2010_2018.rds'))
mal = mal[country!='South Sudan']
# format the data and shape long
setnames(mal, 'country', 'location')
mal[ ,sex:='Both']
mal[ ,population_at_risk:=NULL]
mal = melt(mal, id.vars=c('location', 'year', 'sex'))
# format to match
mal[grepl('upper', variable), bound:='upper']
mal[grepl('lower', variable), bound:='lower']
mal[grepl('point', variable), bound:='val']
# designate mortality and incidence, rates and counts
mal[grepl('deaths', variable) | grepl('mortality', variable) , measure:='Deaths']
mal[grepl('inc', variable) | grepl('cases', variable), measure:='Incidence']
mal[grepl('inc', variable) | grepl('mortality', variable), metric:='Rate']
mal[grepl('deaths', variable) | grepl('cases', variable), metric:='Number']
# add age
mal[metric=='Number', age:='All Ages']
mal[metric=='Rate', age:='Age-standardized']
# add variables not included in the data
mal[ ,sex:='Both']
mal[ ,cause:='Malaria']
mal[ ,variable:=NULL]
# shape wide
mal = dcast(mal, measure+location+sex+age+cause+metric+year~bound)
# match locations in other data
mal[location=='DRC', location:='Democratic Republic of the Congo']
#--------------------------------------------------
# save the data set and bind tb and hiv together
# output prepped hiv data
saveRDS(mal, paste0(outDir, 'prepped_data/who_malaria_2010_2018_prepped.rds'))
# bind the data sets together
dt = rbind(tb_hiv, mal)
# ensure year is not a factor
dt[ ,year:=as.numeric(as.character(year))]
#------------------------------------------------
# save the final product
saveRDS(dt, paste0(outDir, 'prepped_data/who_unaids_prepped.rds'))
#------------------------------------------------
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/convert_MMU_Block.R
\name{convert_MMU_Block}
\alias{convert_MMU_Block}
\title{Convert Measurement, methods and units block}
\usage{
convert_MMU_Block(methodColStrs = NULL, unitName = NULL, org.df,
unit.df = NULL, verbose = FALSE)
}
\arguments{
\item{methodColStrs}{an array of strings idenfiying the methods}
\item{verbose}{}
}
\description{
This function will convert a long format with columns declared as methods, measurements, or units.
}
|
/man/convert_MMU_Block.Rd
|
permissive
|
Em17y/soilDataR
|
R
| false | true | 524 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/convert_MMU_Block.R
\name{convert_MMU_Block}
\alias{convert_MMU_Block}
\title{Convert Measurement, methods and units block}
\usage{
convert_MMU_Block(methodColStrs = NULL, unitName = NULL, org.df,
unit.df = NULL, verbose = FALSE)
}
\arguments{
\item{methodColStrs}{an array of strings idenfiying the methods}
\item{verbose}{}
}
\description{
This function will convert a long format with columns declared as methods, measurements, or units.
}
|
\name{mosaic.generateMetricTablePlot}
\alias{mosaic.generateMetricTablePlot}
\title{
generateMetricTablePlot
}
\description{
Generate missing-ratio table for metric data (data, num of columns, column index, varname)
}
\usage{
mosaic.generateMetricTablePlot(data, num_of_columns, index, varname)
}
\arguments{
\item{data}{
preprocessed data frame including 'valid value markers'
}
\item{num_of_columns}{
absolute number of to be processed data columns
}
\item{index}{
current column to be processed
}
\item{varname}{
current name of variable to be used in table heading
}
}
\author{
The MOSAIC Project, Martin Bialke
}
\note{
Function call type: internal
}
|
/man/mosaic.generateMetricTablePlot.Rd
|
no_license
|
cran/MOQA
|
R
| false | false | 705 |
rd
|
\name{mosaic.generateMetricTablePlot}
\alias{mosaic.generateMetricTablePlot}
\title{
generateMetricTablePlot
}
\description{
Generate missing-ratio table for metric data (data, num of columns, column index, varname)
}
\usage{
mosaic.generateMetricTablePlot(data, num_of_columns, index, varname)
}
\arguments{
\item{data}{
preprocessed data frame including 'valid value markers'
}
\item{num_of_columns}{
absolute number of to be processed data columns
}
\item{index}{
current column to be processed
}
\item{varname}{
current name of variable to be used in table heading
}
}
\author{
The MOSAIC Project, Martin Bialke
}
\note{
Function call type: internal
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/exportFromSCE.R
\name{exportFromSCE}
\alias{exportFromSCE}
\title{Export SingleCellExperiment (SCE) object to Cerebro.}
\usage{
exportFromSCE(
object,
assay = "logcounts",
file,
experiment_name,
organism,
groups,
cell_cycle = NULL,
nUMI = "nUMI",
nGene = "nGene",
add_all_meta_data = TRUE,
use_delayed_array = FALSE,
verbose = FALSE
)
}
\arguments{
\item{object}{\code{SingleCellExperiment} (\code{SCE}) object.}
\item{assay}{Assay to pull expression values from; defaults to
\code{logcounts}. It is recommended to use sparse data (such as
log-transformed or raw counts) instead of dense data (such as the 'scaled'
slot) to avoid performance bottlenecks in the Cerebro interface.}
\item{file}{Where to save the output.}
\item{experiment_name}{Experiment name.}
\item{organism}{Organism, e.g. \code{hg} (human), \code{mm} (mouse), etc.}
\item{groups}{Names of grouping variables in meta data
(\code{colData(object)}), e.g. \code{c("sample","cluster")}; at least one
must be provided; defaults to \code{NULL}.}
\item{cell_cycle}{Names of columns in meta data (\code{colData(object)}) that#
contain cell cycle information, e.g. \code{c("Phase")}; defaults to
\code{NULL}.}
\item{nUMI}{Column in \code{colData(object)} that contains information about
number of transcripts per cell; defaults to \code{nUMI}.}
\item{nGene}{Column in \code{colData(object)} that contains information about
number of expressed genes per cell; defaults to \code{nGene}.}
\item{add_all_meta_data}{If set to \code{TRUE}, all further meta data columns
will be extracted as well.}
\item{use_delayed_array}{When set to \code{TRUE}, the expression matrix will
be stored as an \code{RleMatrix} (see \code{DelayedArray} package). This can
be useful for very large data sets, as the matrix won't be loaded into memory
and instead values will be read from the disk directly, at the cost of
performance. Note that it is necessary to install the \code{DelayedArray}
package. If set to \code{FALSE} (default), the expression matrix will be
copied from the input object as is. It is recommended to use a sparse format,
such as \code{dgCMatrix} from the \code{Matrix} package.}
\item{verbose}{Set this to \code{TRUE} if you want additional log messages;
defaults to \code{FALSE}.}
}
\value{
No data returned.
}
\description{
This function allows to export a \code{SingleCellExperiment} (\code{SCE})
object to visualize in Cerebro.
}
\examples{
pbmc <- readRDS(system.file("extdata/v1.3/pbmc_SCE.rds",
package = "cerebroApp"))
exportFromSCE(
object = pbmc,
file = 'pbmc_SCE.crb',
experiment_name = 'PBMC',
organism = 'hg',
groups = c('sample','cluster'),
nUMI = 'nUMI',
nGene = 'nGene',
use_delayed_array = FALSE,
verbose = TRUE
)
}
|
/man/exportFromSCE.Rd
|
permissive
|
romanhaa/cerebroApp
|
R
| false | true | 2,826 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/exportFromSCE.R
\name{exportFromSCE}
\alias{exportFromSCE}
\title{Export SingleCellExperiment (SCE) object to Cerebro.}
\usage{
exportFromSCE(
object,
assay = "logcounts",
file,
experiment_name,
organism,
groups,
cell_cycle = NULL,
nUMI = "nUMI",
nGene = "nGene",
add_all_meta_data = TRUE,
use_delayed_array = FALSE,
verbose = FALSE
)
}
\arguments{
\item{object}{\code{SingleCellExperiment} (\code{SCE}) object.}
\item{assay}{Assay to pull expression values from; defaults to
\code{logcounts}. It is recommended to use sparse data (such as
log-transformed or raw counts) instead of dense data (such as the 'scaled'
slot) to avoid performance bottlenecks in the Cerebro interface.}
\item{file}{Where to save the output.}
\item{experiment_name}{Experiment name.}
\item{organism}{Organism, e.g. \code{hg} (human), \code{mm} (mouse), etc.}
\item{groups}{Names of grouping variables in meta data
(\code{colData(object)}), e.g. \code{c("sample","cluster")}; at least one
must be provided; defaults to \code{NULL}.}
\item{cell_cycle}{Names of columns in meta data (\code{colData(object)}) that#
contain cell cycle information, e.g. \code{c("Phase")}; defaults to
\code{NULL}.}
\item{nUMI}{Column in \code{colData(object)} that contains information about
number of transcripts per cell; defaults to \code{nUMI}.}
\item{nGene}{Column in \code{colData(object)} that contains information about
number of expressed genes per cell; defaults to \code{nGene}.}
\item{add_all_meta_data}{If set to \code{TRUE}, all further meta data columns
will be extracted as well.}
\item{use_delayed_array}{When set to \code{TRUE}, the expression matrix will
be stored as an \code{RleMatrix} (see \code{DelayedArray} package). This can
be useful for very large data sets, as the matrix won't be loaded into memory
and instead values will be read from the disk directly, at the cost of
performance. Note that it is necessary to install the \code{DelayedArray}
package. If set to \code{FALSE} (default), the expression matrix will be
copied from the input object as is. It is recommended to use a sparse format,
such as \code{dgCMatrix} from the \code{Matrix} package.}
\item{verbose}{Set this to \code{TRUE} if you want additional log messages;
defaults to \code{FALSE}.}
}
\value{
No data returned.
}
\description{
This function allows to export a \code{SingleCellExperiment} (\code{SCE})
object to visualize in Cerebro.
}
\examples{
pbmc <- readRDS(system.file("extdata/v1.3/pbmc_SCE.rds",
package = "cerebroApp"))
exportFromSCE(
object = pbmc,
file = 'pbmc_SCE.crb',
experiment_name = 'PBMC',
organism = 'hg',
groups = c('sample','cluster'),
nUMI = 'nUMI',
nGene = 'nGene',
use_delayed_array = FALSE,
verbose = TRUE
)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/themes.R
\name{theme_scientific}
\alias{theme_scientific}
\title{Theme 'scientific'}
\usage{
theme_scientific()
}
\value{
theme
}
\description{
A theme that was strongly based on http://minimaxir.com/2015/02/ggplot-tutorial/
}
|
/man/theme_scientific.Rd
|
no_license
|
DPCscience/artyfarty
|
R
| false | true | 306 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/themes.R
\name{theme_scientific}
\alias{theme_scientific}
\title{Theme 'scientific'}
\usage{
theme_scientific()
}
\value{
theme
}
\description{
A theme that was strongly based on http://minimaxir.com/2015/02/ggplot-tutorial/
}
|
install.packages("openxlsx")
library(openxlsx)
input<- EastWestAirlines
normal<-scale(input[,2:12])
dis<-dist(normal,method ="euclidean")
fit<-hclust(dis,method = "ward.D2")
plot(fit)
plot(fit,hang=-1)
group<-cutree(fit,k=6)
rect.hclust(fit,k=6,border="red")
matrix<-as.matrix(group,EastWestAirlines)
matrix
final<-data.frame(EastWestAirlines,group)
last<-final[,c(ncol(final),1:(ncol(final)-1))]
write.csv(last,file="dendgoram")
##k mean
input<- EastWestAirlines
normal<-scale(input[,2:12])
plot(normal)
plot(normal,type = "n")
text(normal,rownames(normal))
km<-kmeans(normal,6)
str(km)
km$cluster
install.packages("animation")
library(animation)
km1<-kmeans.ani(normal,6)
wss = (nrow(normal)-1)*sum(apply(normal,2,var))
for(i in 2:12) wss[i] = sum(kmeans(normal,centers=i)$withinss)
plot(1:12,wss,type="b",xlab = "Number of clusters",ylab="within groups sum of squares")
title(sub="k-means clustering screen-plot")
fit<-kmeans(normal,6)
str(fit$cluster)
final2<-data.frame(input,fit$cluster)
final2
final3<-final2[,c(ncol(final2),1:(ncol(final2)-1))]
aggregate(input[,2:12],by=list(fit$cluster),FUN=mean)
write.csv(final3,file="kmean")
getwd()
|
/cluster k means.R
|
no_license
|
vageesha1994/cluster
|
R
| false | false | 1,186 |
r
|
install.packages("openxlsx")
library(openxlsx)
input<- EastWestAirlines
normal<-scale(input[,2:12])
dis<-dist(normal,method ="euclidean")
fit<-hclust(dis,method = "ward.D2")
plot(fit)
plot(fit,hang=-1)
group<-cutree(fit,k=6)
rect.hclust(fit,k=6,border="red")
matrix<-as.matrix(group,EastWestAirlines)
matrix
final<-data.frame(EastWestAirlines,group)
last<-final[,c(ncol(final),1:(ncol(final)-1))]
write.csv(last,file="dendgoram")
##k mean
input<- EastWestAirlines
normal<-scale(input[,2:12])
plot(normal)
plot(normal,type = "n")
text(normal,rownames(normal))
km<-kmeans(normal,6)
str(km)
km$cluster
install.packages("animation")
library(animation)
km1<-kmeans.ani(normal,6)
wss = (nrow(normal)-1)*sum(apply(normal,2,var))
for(i in 2:12) wss[i] = sum(kmeans(normal,centers=i)$withinss)
plot(1:12,wss,type="b",xlab = "Number of clusters",ylab="within groups sum of squares")
title(sub="k-means clustering screen-plot")
fit<-kmeans(normal,6)
str(fit$cluster)
final2<-data.frame(input,fit$cluster)
final2
final3<-final2[,c(ncol(final2),1:(ncol(final2)-1))]
aggregate(input[,2:12],by=list(fit$cluster),FUN=mean)
write.csv(final3,file="kmean")
getwd()
|
library(glmnet)
mydata = read.table("./TrainingSet/RF/cervix.csv",head=T,sep=",")
x = as.matrix(mydata[,4:ncol(mydata)])
y = as.matrix(mydata[,1])
set.seed(123)
glm = cv.glmnet(x,y,nfolds=10,type.measure="mse",alpha=0.01,family="gaussian",standardize=FALSE)
sink('./Model/EN/Classifier/cervix/cervix_006.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
|
/Model/EN/Classifier/cervix/cervix_006.R
|
no_license
|
leon1003/QSMART
|
R
| false | false | 351 |
r
|
library(glmnet)
mydata = read.table("./TrainingSet/RF/cervix.csv",head=T,sep=",")
x = as.matrix(mydata[,4:ncol(mydata)])
y = as.matrix(mydata[,1])
set.seed(123)
glm = cv.glmnet(x,y,nfolds=10,type.measure="mse",alpha=0.01,family="gaussian",standardize=FALSE)
sink('./Model/EN/Classifier/cervix/cervix_006.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
|
# 2-level bootstrapping example function
#' Multi-level Bootstrapping
#'
#' Bootstrapping for 2-level multi-level data
#' @usage bootmlm2(id, group1, data)
#' @param id character of level 1 grouping variable/identifier
#' @param group1 character of level 2 grouping variable (ex: classrooms)
#' @param data dataset from which to bootstrap
#' @examples bootmlm2(id = "ID", group1 = "schoolid", data = dat)
bootmlm2 <- function(id, group1, data){
# Find the unique groups
num.groups <- unique(data[,group1])
# Find the unique IDs
num.ids <- unique(data[,id])
# Initiate bootstrap sample storage
boot.samp <- NULL
# Get column call ready since can't pass as before
group1 <- data[,group1]
# Resample within each group
for(i in num.groups){
# Get observations that are in current group
in.group <- data[group1==i,]
# sample from within that group
group.samp <- in.group[sample(1:nrow(in.group), nrow(in.group), replace = T),]
# Save into a data frame
boot.samp <- rbind(boot.samp,group.samp)
}
return(boot.samp)
}
|
/R/bootmlm_example_2levelonly.R
|
no_license
|
CClingain/powermlm
|
R
| false | false | 1,062 |
r
|
# 2-level bootstrapping example function
#' Multi-level Bootstrapping
#'
#' Bootstrapping for 2-level multi-level data
#' @usage bootmlm2(id, group1, data)
#' @param id character of level 1 grouping variable/identifier
#' @param group1 character of level 2 grouping variable (ex: classrooms)
#' @param data dataset from which to bootstrap
#' @examples bootmlm2(id = "ID", group1 = "schoolid", data = dat)
bootmlm2 <- function(id, group1, data){
# Find the unique groups
num.groups <- unique(data[,group1])
# Find the unique IDs
num.ids <- unique(data[,id])
# Initiate bootstrap sample storage
boot.samp <- NULL
# Get column call ready since can't pass as before
group1 <- data[,group1]
# Resample within each group
for(i in num.groups){
# Get observations that are in current group
in.group <- data[group1==i,]
# sample from within that group
group.samp <- in.group[sample(1:nrow(in.group), nrow(in.group), replace = T),]
# Save into a data frame
boot.samp <- rbind(boot.samp,group.samp)
}
return(boot.samp)
}
|
\name{utf8_width}
\title{Measure the Character String Width}
\alias{utf8_width}
\description{
Compute the display widths of the elements of a character object.
}
\usage{
utf8_width(x, encode = TRUE, quote = FALSE, utf8 = NULL)
}
\arguments{
\item{x}{character object.}
\item{encode}{whether to encode the object before measuring its
width.}
\item{quote}{whether to quote the object before measuring its
width.}
\item{utf8}{logical scalar indicating whether to determine widths
assuming a UTF-8 capable display (ASCII-only otherwise), or
\code{NULL} to format for output capabilities as determined
by \code{output_utf8()}.}
}
\details{
\code{utf8_width} returns the printed widths of the elements of
a character object on a UTF-8 device (or on an ASCII device
when \code{output_utf8()} is \code{FALSE}), when printed with
\code{utf8_print}. If the string is not printable on the device,
for example if it contains a control code like \code{"\n"}, then
the result is \code{NA}. If \code{encode = TRUE}, the default,
then the function returns the widths of the encoded elements
via \code{utf8_encode}); otherwise, the function returns the
widths of the original elements.
}
\value{
An integer object, with the same \code{names}, \code{dim}, and
\code{dimnames} as \code{x}.
}
\seealso{
\code{\link{utf8_print}}.
}
\examples{
# the second element is encoded in latin-1, but declared as UTF-8
x <- c("fa\u00E7ile", "fa\xE7ile", "fa\xC3\xA7ile")
Encoding(x) <- c("UTF-8", "UTF-8", "bytes")
# get widths
utf8_width(x)
utf8_width(x, encode = FALSE)
utf8_width('"')
utf8_width('"', quote = TRUE)
}
|
/man/utf8_width.Rd
|
permissive
|
bedatadriven/r-utf8
|
R
| false | false | 1,698 |
rd
|
\name{utf8_width}
\title{Measure the Character String Width}
\alias{utf8_width}
\description{
Compute the display widths of the elements of a character object.
}
\usage{
utf8_width(x, encode = TRUE, quote = FALSE, utf8 = NULL)
}
\arguments{
\item{x}{character object.}
\item{encode}{whether to encode the object before measuring its
width.}
\item{quote}{whether to quote the object before measuring its
width.}
\item{utf8}{logical scalar indicating whether to determine widths
assuming a UTF-8 capable display (ASCII-only otherwise), or
\code{NULL} to format for output capabilities as determined
by \code{output_utf8()}.}
}
\details{
\code{utf8_width} returns the printed widths of the elements of
a character object on a UTF-8 device (or on an ASCII device
when \code{output_utf8()} is \code{FALSE}), when printed with
\code{utf8_print}. If the string is not printable on the device,
for example if it contains a control code like \code{"\n"}, then
the result is \code{NA}. If \code{encode = TRUE}, the default,
then the function returns the widths of the encoded elements
via \code{utf8_encode}); otherwise, the function returns the
widths of the original elements.
}
\value{
An integer object, with the same \code{names}, \code{dim}, and
\code{dimnames} as \code{x}.
}
\seealso{
\code{\link{utf8_print}}.
}
\examples{
# the second element is encoded in latin-1, but declared as UTF-8
x <- c("fa\u00E7ile", "fa\xE7ile", "fa\xC3\xA7ile")
Encoding(x) <- c("UTF-8", "UTF-8", "bytes")
# get widths
utf8_width(x)
utf8_width(x, encode = FALSE)
utf8_width('"')
utf8_width('"', quote = TRUE)
}
|
# use quadratic exponential scheme from Andersen (2008) to discretize the CIR process
QE = function(v0, kappa, theta, sigma, T, n, M){
Delta = T / n
U = matrix(runif(M * n), M, n)
psic = 1.5
emkt = exp(- kappa * Delta)
c1 = sigma * sigma * emkt * (1 - emkt) / kappa
c2 = theta * sigma * sigma * ((1 - emkt)^2) / (2 * kappa)
v = matrix(, M, n + 1)
v[, 1]= v0
for(i in 1:n){
s2 = v[, i] * c1 + c2
m = v[, i] * emkt + theta * (1 - emkt)
psi = s2 / (m * m)
v[,i + 1] =
ifelse(
psi <= psic,
# a * (b + Z_v)^2, where a = m / (1 + b^2)
m / (1 + 2 * psi^-1 - 1 + sqrt(2 * psi^-1) * sqrt(2 * psi^-1 - 1)) * (sqrt(2 * psi^-1 - 1 + sqrt(2 * psi^-1) * sqrt(2 * psi^-1 - 1)) + qnorm(U[, i]))^2,
# p = (psi - 1) / (psi + 1)
ifelse(U[, i] < (psi - 1) / (psi + 1), 0, ((1 - (psi - 1) / (psi + 1)) / m)^-1 * log( (1 - (psi - 1) / (psi + 1)) / (1 - U[,i]) ))
)
}
# Old, not vectorized code:
# if(psi < psic){
#
# psii = 1 / psi
# b2 = 2 * psii - 1 + sqrt(2 * psii * (2 * psii - 1))
# a = m / (1 + b2)
# v[i] = a * (sqrt(b2) + qnorm(U[i - 1]))^2
#
# }else{
#
# p = (psi - 1) / (psi + 1)
# beta = (1 - p) / m
#
# if(U[i - 1] < p){
#
# v[i] = 0
#
# }else{
#
# v[i] = (1 / beta) * log( (1 - p) / (1 - U[i - 1]) )
#
# }
# }
# }
return(v)
}
# test = QE(0.04, 0.5, 0.04, 1, 1, 1, 1000000)
# > MomentsCIR(p = 1:4, kappa = 0.5, theta = 0.04, sigma = 1, v0 = 0.04, t = 1)
# Evt^1|v0 Evt^2|v0 Evt^3|v0 Evt^4|v0
# 0.04000000 0.02688482 0.03050794 0.04777093
|
/R/CIR/QE.r
|
no_license
|
mrockinger/CIR-Heston-Simulation
|
R
| false | false | 1,995 |
r
|
# use quadratic exponential scheme from Andersen (2008) to discretize the CIR process
QE = function(v0, kappa, theta, sigma, T, n, M){
Delta = T / n
U = matrix(runif(M * n), M, n)
psic = 1.5
emkt = exp(- kappa * Delta)
c1 = sigma * sigma * emkt * (1 - emkt) / kappa
c2 = theta * sigma * sigma * ((1 - emkt)^2) / (2 * kappa)
v = matrix(, M, n + 1)
v[, 1]= v0
for(i in 1:n){
s2 = v[, i] * c1 + c2
m = v[, i] * emkt + theta * (1 - emkt)
psi = s2 / (m * m)
v[,i + 1] =
ifelse(
psi <= psic,
# a * (b + Z_v)^2, where a = m / (1 + b^2)
m / (1 + 2 * psi^-1 - 1 + sqrt(2 * psi^-1) * sqrt(2 * psi^-1 - 1)) * (sqrt(2 * psi^-1 - 1 + sqrt(2 * psi^-1) * sqrt(2 * psi^-1 - 1)) + qnorm(U[, i]))^2,
# p = (psi - 1) / (psi + 1)
ifelse(U[, i] < (psi - 1) / (psi + 1), 0, ((1 - (psi - 1) / (psi + 1)) / m)^-1 * log( (1 - (psi - 1) / (psi + 1)) / (1 - U[,i]) ))
)
}
# Old, not vectorized code:
# if(psi < psic){
#
# psii = 1 / psi
# b2 = 2 * psii - 1 + sqrt(2 * psii * (2 * psii - 1))
# a = m / (1 + b2)
# v[i] = a * (sqrt(b2) + qnorm(U[i - 1]))^2
#
# }else{
#
# p = (psi - 1) / (psi + 1)
# beta = (1 - p) / m
#
# if(U[i - 1] < p){
#
# v[i] = 0
#
# }else{
#
# v[i] = (1 / beta) * log( (1 - p) / (1 - U[i - 1]) )
#
# }
# }
# }
return(v)
}
# test = QE(0.04, 0.5, 0.04, 1, 1, 1, 1000000)
# > MomentsCIR(p = 1:4, kappa = 0.5, theta = 0.04, sigma = 1, v0 = 0.04, t = 1)
# Evt^1|v0 Evt^2|v0 Evt^3|v0 Evt^4|v0
# 0.04000000 0.02688482 0.03050794 0.04777093
|
#########################################
# ER_all
#########################################
# summary Plots
Focusing on this
```{r}
summary(g.er.BEST1$gam)
```
## Predictions
```{r}
pdf(file.path(here::here("03_Plots"), "02a_ERpredictionXdoy.pdf"), height = 4, width = 8)
ggplot() +
geom_point(data = met, aes(y = lER, x = doy, color = treatment)) +
geom_line(data = met, aes(y = ERgamPred, x = doy, color = treatment)) +
geom_ribbon(data = met, aes(ymin = ERgamPred - ERgamPred.se,
ymax = ERgamPred + ERgamPred.se, x = doy, fill = treatment), alpha = 0.5) +
facet_grid(stream ~ treatment)
dev.off()
```
Use model to predict log ER, with Qres, doy and stream set to "centered" values
```{r}
gamPred2 <- predict_gam(g.er.BEST1$gam, exclude_terms = c(
"s(Qres):streamst11U",
"s(Qres):streamst18",
"s(Qres):streamst6",
"s(Qres):streamst9",
"s(doy):streamst11U",
"s(doy):streamst18",
"s(doy):streamst6",
"s(doy):streamst9"),
values = list(
Qres = 0,
doy = 200,
stream = "st6"))
# make the temperature axes sensical
gamPred3 <- gamPred2 %>%
mutate(Tanom.iktCsFlip = -1 * Tanom.iktCs,
invKT.C.StMeanFlip = -1 *invKT.C.StMean)
```
**NOTE: TEMPERATURE AXIS ARE FLIPPED SO LARGE #'S ARE WARM**
During amb year, ER increases with daily temp and with annual temp across streams. Duing the N and P years, this switches. We see ER increasing with annual temp again, but decreasing with daily temp. Cool
```{r}
ErPredSur <- ggplot() +
geom_raster(data = gamPred2, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, fill = fit)) +
facet_wrap(vars(treatment)) +
scale_fill_distiller(palette = "Spectral") +
geom_point(data = met, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, size = lER),
position = position_jitter(width = 0.05, height = 0.025), shape = 21, fill = "transparent", alpha= 0.5) +
scale_size_binned(n.breaks = 4, nice.breaks = TRUE) +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)")
```
```{r}
gamPred2w <- gamPred2 %>%
pivot_wider(id_cols = Tanom.iktCs:doy, names_from = treatment, values_from = c(fit,se.fit)) %>%
mutate(N_amb = exp(fit_nitrogen)/exp(fit_ambient),
P_amb = exp(fit_phosphorus)/exp(fit_ambient))
gamPred2w2 <- gamPred2w %>%
select(Tanom.iktCs:doy, fit_ambient:P_amb) %>%
pivot_longer(cols = N_amb:P_amb, names_to = "treatment", values_to = "effectSize") %>%
mutate(treatment = fct_recode(treatment, Nitrogen = "N_amb", Phosphorus = "P_amb"))
```
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERpredictionSurfaces.pdf"), height = 4, width = 8)
ErPredSur
dev.off()
```
```{r}
pdf(file.path(here::here("03_Plots"), "02c_ERdifferencePlots2.pdf"), height = 5, width = 4)
ggplot(gamPred2w2, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, fill = effectSize)) +
geom_raster() +
scale_fill_distiller(palette = "Spectral") +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)") +
facet_wrap(vars(treatment), nrow = 2, ncol = 1)
dev.off()
```
#########################################
# ER_N
#########################################
# summary Plots
Focusing on this
```{r}
summary(g.er.BEST1$gam)
```
## Predictions
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERpredXdoy_Nonly.pdf"), height = 4, width = 8)
ggplot() +
geom_point(data = met, aes(y = lER, x = doy, color = treatment)) +
geom_line(data = met, aes(y = ERgamPredNonly, x = doy, color = treatment)) +
geom_ribbon(data = met, aes(ymin = ERgamPredNonly - ERgamPredNonly.se,
ymax = ERgamPredNonly + ERgamPredNonly.se, x = doy, fill = treatment), alpha = 0.5) +
facet_grid(stream ~ treatment)
dev.off()
```
Use model to predict log ER, with Qres, doy and stream set to "centered" values
```{r}
gamPred2 <- predict_gam(g.er.BEST1$gam, exclude_terms = c(
"s(Qres):streamst11U",
"s(Qres):streamst18",
"s(Qres):streamst6",
"s(Qres):streamst9",
"s(DOYres)"),
values = list(
Qres = 0,
DOYres = 8.1, # this is the median
stream = "st6"))
```
**NOTE: TEMPERATURE AXIS ARE FLIPPED SO LARGE #'S ARE WARM**
During amb year, ER increases with daily temp and with annual temp across streams. Duing the N and P years, this switches. We see ER increasing with annual temp again, but decreasing with daily temp. Cool
```{r}
#note inversing temp axis here
ErPredSur <- ggplot() +
geom_raster(data = gamPred2, aes(y = invKT.C.StMean, x = Tanom.iktCs, fill = fit)) +
facet_wrap(vars(treatment)) +
scale_fill_distiller(palette = "Spectral") +
geom_point(data = met, aes(y = invKT.C.StMean, x = Tanom.iktCs, size = lER),
position = position_jitter(width = 0.05, height = 0.025), shape = 21, fill = "transparent", alpha= 0.5) +
scale_size_binned(n.breaks = 4, nice.breaks = TRUE) +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)")
```
```{r}
gamPred2w <- gamPred2 %>%
pivot_wider(id_cols = invKT.C.StMean:stream, names_from = treatment, values_from = c(fit,se.fit)) %>%
mutate(N_amb = exp(fit_nitrogen)/exp(fit_ambient))
gamPred2w2 <- gamPred2w %>%
# select(Tanom.iktCs:doy, fit_ambient:P_amb) %>%
pivot_longer(cols = N_amb, names_to = "treatment", values_to = "effectSize") %>%
mutate(treatment = fct_recode(treatment, Nitrogen = "N_amb"))
```
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERpredSurNonly.pdf"), height = 4, width = 8)
ErPredSur
dev.off()
```
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERdifPlotsNonly.pdf"), height = 5, width = 4)
ggplot() +
geom_raster(data = gamPred2w2, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, fill = effectSize)) +
geom_point(data = met, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, size = lER), alpha = 30/100)+
scale_fill_distiller(palette = "Spectral") +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)")
dev.off()
```
#########################################
# ER_P
#########################################
# summary Plots
Focusing on this
```{r}
summary(g.er.BEST1$gam)
```
## Predictions
```{r}
pdf(file.path(here::here("03_Plots"), "02c_Ponly_ERpredXdoyPonly.pdf"), height = 4, width = 8)
ggplot() +
geom_point(data = met, aes(y = lER, x = doy, color = treatment)) +
geom_line(data = met, aes(y = ERgamPred, x = doy, color = treatment)) +
geom_ribbon(data = met, aes(ymin = ERgamPred - ERgamPred.se,
ymax = ERgamPred + ERgamPred.se, x = doy, fill = treatment), alpha = 0.5) +
facet_grid(stream ~ treatment)
dev.off()
```
Use model to predict log ER, with Qres, doy and stream set to "centered" values
```{r}
gamPred2 <- predict_gam(g.er.BEST1$gam,exclude_terms = c(
"s(Qres):streamst11U",
"s(Qres):streamst18",
"s(Qres):streamst6",
"s(Qres):streamst9",
"s(DOYres):streamst11U",
"s(DOYres):streamst18",
"s(DOYres):streamst6",
"s(DOYres):streamst9"),
values = list(
Qres = 0,
DOYres = 6.1)) # median in this dataset
```
```{r}
gamPred2w <- gamPred2 %>%
pivot_wider(id_cols = c(stream:Tanom.iktCs,Qres:DOYres), names_from = treatment, values_from = c(fit,se.fit)) %>%
mutate(P_amb = exp(fit_phosphorus)/exp(fit_ambient))
# gamPred2w2 <- gamPred2w %>%
# select(Tanom.iktCs:doy, fit_ambient:P_amb) %>%
# pivot_longer(cols = N_amb:P_amb, names_to = "treatment", values_to = "effectSize") %>%
# mutate(treatment = fct_recode(treatment, Nitrogen = "N_amb", Phosphorus = "P_amb"))
```
**NOTE: TEMPERATURE AXIS ARE FLIPPED SO LARGE #'S ARE WARM**
During amb year, ER increases with daily temp and with annual temp across streams. Duing the N and P years, this switches. We see ER increasing with annual temp again, but decreasing with daily temp. Cool
```{r}
ErPredSur <- ggplot() +
geom_raster(data = gamPred2, aes(y = stream, x = -Tanom.iktCs, fill = fit)) +
scale_fill_distiller(palette = "Spectral") +
geom_point(data = met, aes(y = stream, x = -Tanom.iktCs, size = lER),
position = position_jitter(width = 0, height = 0.075), shape = 21, fill = "transparent", alpha= 0.5) +
scale_size_binned(n.breaks = 4, nice.breaks = TRUE) +
facet_wrap(vars(treatment)) +
ylab("stream") +
xlab("Mean daily temp (-1 * centered 1/kT)")
```
```{r}
pdf(file.path(here::here("03_Plots"), "02c_ERpredSur_Ponly.pdf"), height = 4, width = 8)
ErPredSur
dev.off()
```
```{r}
pdf(file.path(here::here("03_Plots"), "02c_ERdifPlotsPonly.pdf"), height = 5, width = 4)
ggplot() +
geom_raster(data = gamPred2w, aes(y = stream, x = -Tanom.iktCs, fill = P_amb)) +
geom_point(data = met, aes(y = stream, x = -Tanom.iktCs, size = lER),
position = position_jitter(width = 0, height = 0.075), shape = 21, fill = "transparent", alpha= 0.5) +
scale_fill_distiller(palette = "Spectral") +
xlab("Mean daily temp (-1 * centered 1/kT)") +
ylab("stream")
dev.off()
```
#########################################
# GPP_All
#########################################
# These aren't too useful for interactions
```{r echo=FALSE}
GPPquickPlot1 <- plot(g.gpp.BEST1.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot1, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot2 <- plot(g.gpp.BEST2.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot2, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot3 <- plot(g.gpp.BEST3.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot3, pages = 1)
```
Predict for future ploting
```{r echo= FALSE}
met$GPPgamPred <- predict.gam(g.gppBEST3$gam, met, type = "response")
met$GPPgamPred.se <- predict.gam(g.gppBEST3$gam, met, type = "response", se.fit = TRUE)$se.fit
```
#########################################
# GPP_N
#########################################
# These aren't too useful for interactions
```{r echo=FALSE}
GPPquickPlot1 <- plot(g.gpp.BEST1.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot1, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot2 <- plot(g.gpp.BEST2.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot2, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot3 <- plot(g.gpp.BEST3.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot3, pages = 1)
```
|
/zz_code for figs.R
|
no_license
|
hood211/IceMetab2
|
R
| false | false | 11,181 |
r
|
#########################################
# ER_all
#########################################
# summary Plots
Focusing on this
```{r}
summary(g.er.BEST1$gam)
```
## Predictions
```{r}
pdf(file.path(here::here("03_Plots"), "02a_ERpredictionXdoy.pdf"), height = 4, width = 8)
ggplot() +
geom_point(data = met, aes(y = lER, x = doy, color = treatment)) +
geom_line(data = met, aes(y = ERgamPred, x = doy, color = treatment)) +
geom_ribbon(data = met, aes(ymin = ERgamPred - ERgamPred.se,
ymax = ERgamPred + ERgamPred.se, x = doy, fill = treatment), alpha = 0.5) +
facet_grid(stream ~ treatment)
dev.off()
```
Use model to predict log ER, with Qres, doy and stream set to "centered" values
```{r}
gamPred2 <- predict_gam(g.er.BEST1$gam, exclude_terms = c(
"s(Qres):streamst11U",
"s(Qres):streamst18",
"s(Qres):streamst6",
"s(Qres):streamst9",
"s(doy):streamst11U",
"s(doy):streamst18",
"s(doy):streamst6",
"s(doy):streamst9"),
values = list(
Qres = 0,
doy = 200,
stream = "st6"))
# make the temperature axes sensical
gamPred3 <- gamPred2 %>%
mutate(Tanom.iktCsFlip = -1 * Tanom.iktCs,
invKT.C.StMeanFlip = -1 *invKT.C.StMean)
```
**NOTE: TEMPERATURE AXIS ARE FLIPPED SO LARGE #'S ARE WARM**
During amb year, ER increases with daily temp and with annual temp across streams. Duing the N and P years, this switches. We see ER increasing with annual temp again, but decreasing with daily temp. Cool
```{r}
ErPredSur <- ggplot() +
geom_raster(data = gamPred2, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, fill = fit)) +
facet_wrap(vars(treatment)) +
scale_fill_distiller(palette = "Spectral") +
geom_point(data = met, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, size = lER),
position = position_jitter(width = 0.05, height = 0.025), shape = 21, fill = "transparent", alpha= 0.5) +
scale_size_binned(n.breaks = 4, nice.breaks = TRUE) +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)")
```
```{r}
gamPred2w <- gamPred2 %>%
pivot_wider(id_cols = Tanom.iktCs:doy, names_from = treatment, values_from = c(fit,se.fit)) %>%
mutate(N_amb = exp(fit_nitrogen)/exp(fit_ambient),
P_amb = exp(fit_phosphorus)/exp(fit_ambient))
gamPred2w2 <- gamPred2w %>%
select(Tanom.iktCs:doy, fit_ambient:P_amb) %>%
pivot_longer(cols = N_amb:P_amb, names_to = "treatment", values_to = "effectSize") %>%
mutate(treatment = fct_recode(treatment, Nitrogen = "N_amb", Phosphorus = "P_amb"))
```
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERpredictionSurfaces.pdf"), height = 4, width = 8)
ErPredSur
dev.off()
```
```{r}
pdf(file.path(here::here("03_Plots"), "02c_ERdifferencePlots2.pdf"), height = 5, width = 4)
ggplot(gamPred2w2, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, fill = effectSize)) +
geom_raster() +
scale_fill_distiller(palette = "Spectral") +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)") +
facet_wrap(vars(treatment), nrow = 2, ncol = 1)
dev.off()
```
#########################################
# ER_N
#########################################
# summary Plots
Focusing on this
```{r}
summary(g.er.BEST1$gam)
```
## Predictions
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERpredXdoy_Nonly.pdf"), height = 4, width = 8)
ggplot() +
geom_point(data = met, aes(y = lER, x = doy, color = treatment)) +
geom_line(data = met, aes(y = ERgamPredNonly, x = doy, color = treatment)) +
geom_ribbon(data = met, aes(ymin = ERgamPredNonly - ERgamPredNonly.se,
ymax = ERgamPredNonly + ERgamPredNonly.se, x = doy, fill = treatment), alpha = 0.5) +
facet_grid(stream ~ treatment)
dev.off()
```
Use model to predict log ER, with Qres, doy and stream set to "centered" values
```{r}
gamPred2 <- predict_gam(g.er.BEST1$gam, exclude_terms = c(
"s(Qres):streamst11U",
"s(Qres):streamst18",
"s(Qres):streamst6",
"s(Qres):streamst9",
"s(DOYres)"),
values = list(
Qres = 0,
DOYres = 8.1, # this is the median
stream = "st6"))
```
**NOTE: TEMPERATURE AXIS ARE FLIPPED SO LARGE #'S ARE WARM**
During amb year, ER increases with daily temp and with annual temp across streams. Duing the N and P years, this switches. We see ER increasing with annual temp again, but decreasing with daily temp. Cool
```{r}
#note inversing temp axis here
ErPredSur <- ggplot() +
geom_raster(data = gamPred2, aes(y = invKT.C.StMean, x = Tanom.iktCs, fill = fit)) +
facet_wrap(vars(treatment)) +
scale_fill_distiller(palette = "Spectral") +
geom_point(data = met, aes(y = invKT.C.StMean, x = Tanom.iktCs, size = lER),
position = position_jitter(width = 0.05, height = 0.025), shape = 21, fill = "transparent", alpha= 0.5) +
scale_size_binned(n.breaks = 4, nice.breaks = TRUE) +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)")
```
```{r}
gamPred2w <- gamPred2 %>%
pivot_wider(id_cols = invKT.C.StMean:stream, names_from = treatment, values_from = c(fit,se.fit)) %>%
mutate(N_amb = exp(fit_nitrogen)/exp(fit_ambient))
gamPred2w2 <- gamPred2w %>%
# select(Tanom.iktCs:doy, fit_ambient:P_amb) %>%
pivot_longer(cols = N_amb, names_to = "treatment", values_to = "effectSize") %>%
mutate(treatment = fct_recode(treatment, Nitrogen = "N_amb"))
```
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERpredSurNonly.pdf"), height = 4, width = 8)
ErPredSur
dev.off()
```
```{r}
pdf(file.path(here::here("03_Plots"), "02b_ERdifPlotsNonly.pdf"), height = 5, width = 4)
ggplot() +
geom_raster(data = gamPred2w2, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, fill = effectSize)) +
geom_point(data = met, aes(y = -invKT.C.StMean, x = -Tanom.iktCs, size = lER), alpha = 30/100)+
scale_fill_distiller(palette = "Spectral") +
ylab("Mean summer temp (-1 * centered 1/kT)") +
xlab("Mean daily temp (-1 * centered 1/kT)")
dev.off()
```
#########################################
# ER_P
#########################################
# summary Plots
Focusing on this
```{r}
summary(g.er.BEST1$gam)
```
## Predictions
```{r}
pdf(file.path(here::here("03_Plots"), "02c_Ponly_ERpredXdoyPonly.pdf"), height = 4, width = 8)
ggplot() +
geom_point(data = met, aes(y = lER, x = doy, color = treatment)) +
geom_line(data = met, aes(y = ERgamPred, x = doy, color = treatment)) +
geom_ribbon(data = met, aes(ymin = ERgamPred - ERgamPred.se,
ymax = ERgamPred + ERgamPred.se, x = doy, fill = treatment), alpha = 0.5) +
facet_grid(stream ~ treatment)
dev.off()
```
Use model to predict log ER, with Qres, doy and stream set to "centered" values
```{r}
gamPred2 <- predict_gam(g.er.BEST1$gam,exclude_terms = c(
"s(Qres):streamst11U",
"s(Qres):streamst18",
"s(Qres):streamst6",
"s(Qres):streamst9",
"s(DOYres):streamst11U",
"s(DOYres):streamst18",
"s(DOYres):streamst6",
"s(DOYres):streamst9"),
values = list(
Qres = 0,
DOYres = 6.1)) # median in this dataset
```
```{r}
gamPred2w <- gamPred2 %>%
pivot_wider(id_cols = c(stream:Tanom.iktCs,Qres:DOYres), names_from = treatment, values_from = c(fit,se.fit)) %>%
mutate(P_amb = exp(fit_phosphorus)/exp(fit_ambient))
# gamPred2w2 <- gamPred2w %>%
# select(Tanom.iktCs:doy, fit_ambient:P_amb) %>%
# pivot_longer(cols = N_amb:P_amb, names_to = "treatment", values_to = "effectSize") %>%
# mutate(treatment = fct_recode(treatment, Nitrogen = "N_amb", Phosphorus = "P_amb"))
```
**NOTE: TEMPERATURE AXIS ARE FLIPPED SO LARGE #'S ARE WARM**
During amb year, ER increases with daily temp and with annual temp across streams. Duing the N and P years, this switches. We see ER increasing with annual temp again, but decreasing with daily temp. Cool
```{r}
ErPredSur <- ggplot() +
geom_raster(data = gamPred2, aes(y = stream, x = -Tanom.iktCs, fill = fit)) +
scale_fill_distiller(palette = "Spectral") +
geom_point(data = met, aes(y = stream, x = -Tanom.iktCs, size = lER),
position = position_jitter(width = 0, height = 0.075), shape = 21, fill = "transparent", alpha= 0.5) +
scale_size_binned(n.breaks = 4, nice.breaks = TRUE) +
facet_wrap(vars(treatment)) +
ylab("stream") +
xlab("Mean daily temp (-1 * centered 1/kT)")
```
```{r}
pdf(file.path(here::here("03_Plots"), "02c_ERpredSur_Ponly.pdf"), height = 4, width = 8)
ErPredSur
dev.off()
```
```{r}
pdf(file.path(here::here("03_Plots"), "02c_ERdifPlotsPonly.pdf"), height = 5, width = 4)
ggplot() +
geom_raster(data = gamPred2w, aes(y = stream, x = -Tanom.iktCs, fill = P_amb)) +
geom_point(data = met, aes(y = stream, x = -Tanom.iktCs, size = lER),
position = position_jitter(width = 0, height = 0.075), shape = 21, fill = "transparent", alpha= 0.5) +
scale_fill_distiller(palette = "Spectral") +
xlab("Mean daily temp (-1 * centered 1/kT)") +
ylab("stream")
dev.off()
```
#########################################
# GPP_All
#########################################
# These aren't too useful for interactions
```{r echo=FALSE}
GPPquickPlot1 <- plot(g.gpp.BEST1.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot1, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot2 <- plot(g.gpp.BEST2.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot2, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot3 <- plot(g.gpp.BEST3.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot3, pages = 1)
```
Predict for future ploting
```{r echo= FALSE}
met$GPPgamPred <- predict.gam(g.gppBEST3$gam, met, type = "response")
met$GPPgamPred.se <- predict.gam(g.gppBEST3$gam, met, type = "response", se.fit = TRUE)$se.fit
```
#########################################
# GPP_N
#########################################
# These aren't too useful for interactions
```{r echo=FALSE}
GPPquickPlot1 <- plot(g.gpp.BEST1.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot1, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot2 <- plot(g.gpp.BEST2.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot2, pages = 1)
```
```{r echo=FALSE}
GPPquickPlot3 <- plot(g.gpp.BEST3.gv, allTerms = 1) +
l_points(color = "pink") + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
print(GPPquickPlot3, pages = 1)
```
|
context("test-tbl_stack")
testthat::skip_on_cran()
library(survival)
t1 <-
glm(response ~ trt, trial, family = binomial) %>%
tbl_regression(
exponentiate = TRUE,
label = list("trt" ~ "Treatment (unadjusted)")
)
t2 <-
glm(response ~ trt + grade + stage + marker, trial, family = binomial) %>%
tbl_regression(
include = "trt",
exponentiate = TRUE,
label = list("trt" ~ "Treatment (adjusted)")
)
t3 <-
coxph(Surv(ttdeath, death) ~ trt, trial) %>%
tbl_regression(
exponentiate = TRUE,
label = list("trt" ~ "Treatment (unadjusted)")
)
t4 <-
coxph(Surv(ttdeath, death) ~ trt + grade + stage + marker, trial) %>%
tbl_regression(
include = "trt",
exponentiate = TRUE,
label = list("trt" ~ "Treatment (adjusted)")
)
row1 <- tbl_merge(list(t1, t3), tab_spanner = c("Tumor Response", "Death"))
row2 <- tbl_merge(list(t2, t4))
test_that("Stacking tbl_regression objects", {
expect_error(
tbl_stack(list(t1, t2), group_header = c("Group 1", "Group 2")),
NA
)
# must pass items as list
expect_error(
tbl_stack(t1, t2),
NULL
)
# must pass acceptable objects
expect_error(
tbl_stack(list(mtcars)),
NULL
)
})
test_that("Stacking tbl_merge objects", {
expect_error(
tbl_stack(list(row1, row2)),
NA
)
})
test_that("Stacking tbl_summary objects", {
yy <- tbl_summary(trial, by = response) %>%
add_p() %>%
add_q()
tt <- tbl_summary(trial, by = trt) %>%
add_p() %>%
add_q()
expect_error(
zz <- tbl_stack(list(yy, tt)),
NA
)
# no error if the list is named
lst_summary <- list(yy, tt) %>% set_names("one", "two")
expect_error(
tbl_stack(lst_summary, group_header = c("Group 1", "Group 2")),
NA
)
})
|
/tests/testthat/test-tbl_stack.R
|
permissive
|
shijianasdf/gtsummary
|
R
| false | false | 1,752 |
r
|
context("test-tbl_stack")
testthat::skip_on_cran()
library(survival)
t1 <-
glm(response ~ trt, trial, family = binomial) %>%
tbl_regression(
exponentiate = TRUE,
label = list("trt" ~ "Treatment (unadjusted)")
)
t2 <-
glm(response ~ trt + grade + stage + marker, trial, family = binomial) %>%
tbl_regression(
include = "trt",
exponentiate = TRUE,
label = list("trt" ~ "Treatment (adjusted)")
)
t3 <-
coxph(Surv(ttdeath, death) ~ trt, trial) %>%
tbl_regression(
exponentiate = TRUE,
label = list("trt" ~ "Treatment (unadjusted)")
)
t4 <-
coxph(Surv(ttdeath, death) ~ trt + grade + stage + marker, trial) %>%
tbl_regression(
include = "trt",
exponentiate = TRUE,
label = list("trt" ~ "Treatment (adjusted)")
)
row1 <- tbl_merge(list(t1, t3), tab_spanner = c("Tumor Response", "Death"))
row2 <- tbl_merge(list(t2, t4))
test_that("Stacking tbl_regression objects", {
expect_error(
tbl_stack(list(t1, t2), group_header = c("Group 1", "Group 2")),
NA
)
# must pass items as list
expect_error(
tbl_stack(t1, t2),
NULL
)
# must pass acceptable objects
expect_error(
tbl_stack(list(mtcars)),
NULL
)
})
test_that("Stacking tbl_merge objects", {
expect_error(
tbl_stack(list(row1, row2)),
NA
)
})
test_that("Stacking tbl_summary objects", {
yy <- tbl_summary(trial, by = response) %>%
add_p() %>%
add_q()
tt <- tbl_summary(trial, by = trt) %>%
add_p() %>%
add_q()
expect_error(
zz <- tbl_stack(list(yy, tt)),
NA
)
# no error if the list is named
lst_summary <- list(yy, tt) %>% set_names("one", "two")
expect_error(
tbl_stack(lst_summary, group_header = c("Group 1", "Group 2")),
NA
)
})
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cloudresourcemanager_objects.R
\name{Project.labels}
\alias{Project.labels}
\title{Project.labels Object}
\usage{
Project.labels()
}
\value{
Project.labels object
}
\description{
Project.labels Object
}
\details{
Autogenerated via \code{\link[googleAuthR]{gar_create_api_objects}}
The labels associated with this Project.Label keys must be between 1 and 63 characters long and must conformto the following regular expression: \[a-z\](\[-a-z0-9\]*\[a-z0-9\])?.Label values must be between 0 and 63 characters long and must conformto the regular expression (\[a-z\](\[-a-z0-9\]*\[a-z0-9\])?)?.No more than 256 labels can be associated with a given resource.Clients should store labels in a representation such as JSON that does notdepend on specific characters being disallowed.Example: <code>'environment' : 'dev'</code>Read-write.
}
\seealso{
Other Project functions: \code{\link{Project}},
\code{\link{projects.create}},
\code{\link{projects.update}}
}
|
/googlecloudresourcemanagerv1beta1.auto/man/Project.labels.Rd
|
permissive
|
GVersteeg/autoGoogleAPI
|
R
| false | true | 1,036 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cloudresourcemanager_objects.R
\name{Project.labels}
\alias{Project.labels}
\title{Project.labels Object}
\usage{
Project.labels()
}
\value{
Project.labels object
}
\description{
Project.labels Object
}
\details{
Autogenerated via \code{\link[googleAuthR]{gar_create_api_objects}}
The labels associated with this Project.Label keys must be between 1 and 63 characters long and must conformto the following regular expression: \[a-z\](\[-a-z0-9\]*\[a-z0-9\])?.Label values must be between 0 and 63 characters long and must conformto the regular expression (\[a-z\](\[-a-z0-9\]*\[a-z0-9\])?)?.No more than 256 labels can be associated with a given resource.Clients should store labels in a representation such as JSON that does notdepend on specific characters being disallowed.Example: <code>'environment' : 'dev'</code>Read-write.
}
\seealso{
Other Project functions: \code{\link{Project}},
\code{\link{projects.create}},
\code{\link{projects.update}}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/groupZscores.R
\name{groupZscores}
\alias{groupZscores}
\title{Calculate z-scores for each peak}
\usage{
groupZscores(zscore)
}
\arguments{
\item{zscore}{A vector of numeric.
It is the z-scores of ratios for each window.}
}
\value{
A data.frame with column names as "zscore", "group", "grp.zscore",
and "pvalue".
}
\description{
Detect peaks and calculate z-scores for each peak
}
\examples{
x <- seq_len(500)
a <- 2 * 2*pi/length(x)
y <- 20 * sin(x*a)
noise1 <- 20 * 1/10 * sin(x*a*10)
zscore <- y+noise1
groupZscores(zscore)
}
|
/man/groupZscores.Rd
|
no_license
|
LihuaJulieZhu/NADfinder
|
R
| false | true | 609 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/groupZscores.R
\name{groupZscores}
\alias{groupZscores}
\title{Calculate z-scores for each peak}
\usage{
groupZscores(zscore)
}
\arguments{
\item{zscore}{A vector of numeric.
It is the z-scores of ratios for each window.}
}
\value{
A data.frame with column names as "zscore", "group", "grp.zscore",
and "pvalue".
}
\description{
Detect peaks and calculate z-scores for each peak
}
\examples{
x <- seq_len(500)
a <- 2 * 2*pi/length(x)
y <- 20 * sin(x*a)
noise1 <- 20 * 1/10 * sin(x*a*10)
zscore <- y+noise1
groupZscores(zscore)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.