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/checkFit.R
\name{checkFit}
\alias{checkFit}
\title{checkFit function}
\usage{
checkFit(pop)
}
\arguments{
\item{pop}{[value]}
}
\value{
[value]
}
\description{
function to (do something)
}
\details{
[fill in details here]
}
\examples{
none
}
|
/man/checkFit.Rd
|
no_license
|
skayondo/breedingProgramR
|
R
| false
| true
| 320
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/checkFit.R
\name{checkFit}
\alias{checkFit}
\title{checkFit function}
\usage{
checkFit(pop)
}
\arguments{
\item{pop}{[value]}
}
\value{
[value]
}
\description{
function to (do something)
}
\details{
[fill in details here]
}
\examples{
none
}
|
db$run( '{"createIndexes":"metadb","indexes":[{"key":{"name":1},"name":"typename","unique":"true"}] }' )
|
/CreateScripts/uniqueindex.R
|
no_license
|
ceparman/ShinyLIMS
|
R
| false
| false
| 108
|
r
|
db$run( '{"createIndexes":"metadb","indexes":[{"key":{"name":1},"name":"typename","unique":"true"}] }' )
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/param.R
\name{check.rpath.params}
\alias{check.rpath.params}
\title{Check Rpath parameter files}
\usage{
check.rpath.params(Rpath.params)
}
\arguments{
\item{filename}{Name of the parameter file. Can be the path to a .csv or an R
object.}
\item{parameter}{The type of parameter file you are checking. Choices include}
}
\value{
Checks Rpath parameter files for consistency. An error message will be produced if one of
the logical checks fails. Checks include:
(NOTE: This does not ensure data is correct just that it is in the right places).
}
\description{
Logical check that the parameter files are filled out correctly, i.e. data is entered where it is
expected.
}
\seealso{
Other Rpath.functions: \code{\link{adjust.fishing}},
\code{\link{adjust.scenario}},
\code{\link{create.rpath.params}},
\code{\link{frate.table}},
\code{\link{read.rpath.params}},
\code{\link{rpath.stanzas}}, \code{\link{rpath}},
\code{\link{rsim.params}}, \code{\link{rsim.plot}},
\code{\link{rsim.scenario}}, \code{\link{stanzaplot}},
\code{\link{webplot}}, \code{\link{write.Rpath}},
\code{\link{write.Rsim}},
\code{\link{write.rpath.params}}
}
|
/Rpath/man/check.rpath.params.Rd
|
no_license
|
kakearney/RpathDev
|
R
| false
| true
| 1,232
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/param.R
\name{check.rpath.params}
\alias{check.rpath.params}
\title{Check Rpath parameter files}
\usage{
check.rpath.params(Rpath.params)
}
\arguments{
\item{filename}{Name of the parameter file. Can be the path to a .csv or an R
object.}
\item{parameter}{The type of parameter file you are checking. Choices include}
}
\value{
Checks Rpath parameter files for consistency. An error message will be produced if one of
the logical checks fails. Checks include:
(NOTE: This does not ensure data is correct just that it is in the right places).
}
\description{
Logical check that the parameter files are filled out correctly, i.e. data is entered where it is
expected.
}
\seealso{
Other Rpath.functions: \code{\link{adjust.fishing}},
\code{\link{adjust.scenario}},
\code{\link{create.rpath.params}},
\code{\link{frate.table}},
\code{\link{read.rpath.params}},
\code{\link{rpath.stanzas}}, \code{\link{rpath}},
\code{\link{rsim.params}}, \code{\link{rsim.plot}},
\code{\link{rsim.scenario}}, \code{\link{stanzaplot}},
\code{\link{webplot}}, \code{\link{write.Rpath}},
\code{\link{write.Rsim}},
\code{\link{write.rpath.params}}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/quick.helpers.R
\name{quick.SAS.labels}
\alias{quick.SAS.labels}
\title{Quick SAS Factor Labels}
\usage{
quick.SAS.labels(my.df)
}
\arguments{
\item{my.df}{Data frame to get the new information}
}
\value{
Dataframe with label information
}
\description{
Why should you have to type them? A dialog will come up to ask you for the file.
}
|
/man/quick.SAS.labels.Rd
|
no_license
|
ckraner/quick.tasks
|
R
| false
| true
| 415
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/quick.helpers.R
\name{quick.SAS.labels}
\alias{quick.SAS.labels}
\title{Quick SAS Factor Labels}
\usage{
quick.SAS.labels(my.df)
}
\arguments{
\item{my.df}{Data frame to get the new information}
}
\value{
Dataframe with label information
}
\description{
Why should you have to type them? A dialog will come up to ask you for the file.
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/rand_dist.R
\name{rand_dist}
\alias{rand_dist}
\title{Randomization Test Distribution}
\usage{
rand_dist(x, show.all = TRUE)
}
\arguments{
\item{x}{double}
\item{show.all}{boolean}
}
\value{
output
}
\description{
Display the distribution of the test statistic for a single-sample
randomization test.
}
\examples{
scores <- (5, 3, -7)
rand_dist(scores)
}
|
/man/rand_dist.Rd
|
permissive
|
fourthz/nplearn
|
R
| false
| true
| 434
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/rand_dist.R
\name{rand_dist}
\alias{rand_dist}
\title{Randomization Test Distribution}
\usage{
rand_dist(x, show.all = TRUE)
}
\arguments{
\item{x}{double}
\item{show.all}{boolean}
}
\value{
output
}
\description{
Display the distribution of the test statistic for a single-sample
randomization test.
}
\examples{
scores <- (5, 3, -7)
rand_dist(scores)
}
|
library(dplyr)
# reading test data, including activity and subject
test <- read.table("./X_test.txt")
test_activ <- read.table("./y_test.txt", colClasses = "factor", col.names = "activity")
test_subject <- read.table("./subject_test.txt", colClasses = "factor", col.names = "subject")
# reading train data, including activity and subject
train <- read.table("./X_train.txt")
train_activ <- read.table("./y_train.txt",
colClasses = "factor", col.names = "activity")
train_subject <- read.table("./subject_train.txt",
colClasses = "factor", col.names = "subject")
# Merging activity test and train data, same for subject
activity_set <- rbind(test_activ, train_activ)
subject_set <- rbind(test_subject, train_subject)
# Mergind test and train data
dim(test)
dim(train)
data <- rbind(test, train)
# Extract the measurements on the mean and standard deviation
# (only match if end with mean() or std()).
feat <- read.table("features.txt")
feat2 <- grep("mean\\()$|std\\()$", feat[,2])
data <- data[,feat2]
# Save the feature labels for measurements names
feat_labels <- feat[feat2,][,2]
colnames(data) <- feat_labels
# Naming the activities in the data set
data$activity <- activity_set$activity
data$subject <- subject_set$subject
data$activity <- factor(data$activity, levels = c(1,2,3,4,5,6),
labels = c("walking","walking up","walking down",
"sitting","standing","laying"))
# Summarizing and creating tidy data set
data <- tbl_df(data)
# From the data set created, group by activity and subject to get the average
# of each variable for each activity and each subject
group_data <- (data
%>% group_by(activity, subject)
%>% summarise_if(is.numeric, mean, na.rm = TRUE)
%>% print)
# write the tidy data set created above
write.table(group_data, file = "dataset.txt", row.names = FALSE)
|
/run_analysis.R
|
no_license
|
juanjord/cleaningdata_project
|
R
| false
| false
| 1,960
|
r
|
library(dplyr)
# reading test data, including activity and subject
test <- read.table("./X_test.txt")
test_activ <- read.table("./y_test.txt", colClasses = "factor", col.names = "activity")
test_subject <- read.table("./subject_test.txt", colClasses = "factor", col.names = "subject")
# reading train data, including activity and subject
train <- read.table("./X_train.txt")
train_activ <- read.table("./y_train.txt",
colClasses = "factor", col.names = "activity")
train_subject <- read.table("./subject_train.txt",
colClasses = "factor", col.names = "subject")
# Merging activity test and train data, same for subject
activity_set <- rbind(test_activ, train_activ)
subject_set <- rbind(test_subject, train_subject)
# Mergind test and train data
dim(test)
dim(train)
data <- rbind(test, train)
# Extract the measurements on the mean and standard deviation
# (only match if end with mean() or std()).
feat <- read.table("features.txt")
feat2 <- grep("mean\\()$|std\\()$", feat[,2])
data <- data[,feat2]
# Save the feature labels for measurements names
feat_labels <- feat[feat2,][,2]
colnames(data) <- feat_labels
# Naming the activities in the data set
data$activity <- activity_set$activity
data$subject <- subject_set$subject
data$activity <- factor(data$activity, levels = c(1,2,3,4,5,6),
labels = c("walking","walking up","walking down",
"sitting","standing","laying"))
# Summarizing and creating tidy data set
data <- tbl_df(data)
# From the data set created, group by activity and subject to get the average
# of each variable for each activity and each subject
group_data <- (data
%>% group_by(activity, subject)
%>% summarise_if(is.numeric, mean, na.rm = TRUE)
%>% print)
# write the tidy data set created above
write.table(group_data, file = "dataset.txt", row.names = FALSE)
|
library(tidyverse)
load("rdas/murders.rda")
head(murders)
murders%>% mutate(abb=reorder(abb,rate))%>%
ggplot(aes(abb,rate))+
geom_bar(width=0.5,stat = "identity", color="black")+coord_flip()
ggsave("figs/barplot.png")
|
/analysis.R
|
no_license
|
Binmana/murders
|
R
| false
| false
| 222
|
r
|
library(tidyverse)
load("rdas/murders.rda")
head(murders)
murders%>% mutate(abb=reorder(abb,rate))%>%
ggplot(aes(abb,rate))+
geom_bar(width=0.5,stat = "identity", color="black")+coord_flip()
ggsave("figs/barplot.png")
|
## input a matrix to compute its inverse, if there is already an existing matrix
## it checks if it is the same with the old one
## if it is, the cacheSolve will return the old matrix
## Assignment number 3.
## i understand a little how the code works, but i cant grasp the idea fully
## would really appreciate if you have any recommended articles, readings, or videos
## i want to understand R more as it is interesting
## but my current level of understanding does not make it more fun
## make CacheMatrix will cache a matrix's inverse
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinverse <- function(inverse) m <<- inverse
getinverse <- function() m
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## cacheSolve retrieves the inversed matrix from the cached value that is stored in makeCacheMatrix()'s environment
cacheSolve <- function(x, ...) {
m <- x$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <-x$get()
m <- solve(data,...)
x$setinverse(m)
m
}
|
/cachematrix.R
|
no_license
|
lemuellozada/ProgrammingAssignment2
|
R
| false
| false
| 1,386
|
r
|
## input a matrix to compute its inverse, if there is already an existing matrix
## it checks if it is the same with the old one
## if it is, the cacheSolve will return the old matrix
## Assignment number 3.
## i understand a little how the code works, but i cant grasp the idea fully
## would really appreciate if you have any recommended articles, readings, or videos
## i want to understand R more as it is interesting
## but my current level of understanding does not make it more fun
## make CacheMatrix will cache a matrix's inverse
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinverse <- function(inverse) m <<- inverse
getinverse <- function() m
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## cacheSolve retrieves the inversed matrix from the cached value that is stored in makeCacheMatrix()'s environment
cacheSolve <- function(x, ...) {
m <- x$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <-x$get()
m <- solve(data,...)
x$setinverse(m)
m
}
|
\name{graze}
\alias{graze}
\docType{data}
\title{ Site information and grazed vegetation data. }
\description{
This data frame contains site location, landscape context and dominant plant species abundances for 25 of the plant species found in 50 grazed pastures in the northeastern United States. Elements are the mean values for canopy cover for ten 0.5 x 2 m quadrats.
}
\usage{data(graze)}
\format{
A data frame with 50 observations on the following 25 variables.
\describe{
\item{\code{sitelocation}}{Site location along a geographic gradient.}
\item{\code{forestpct}}{Percentage forest cover within a 1-km radius.}
\item{\code{ACMI2}}{Percentage canopy cover.}
\item{\code{ANOD}}{Percentage canopy cover.}
\item{\code{ASSY}}{Percentage canopy cover.}
\item{\code{BRIN2}}{Percentage canopy cover.}
\item{\code{CIAR4}}{Percentage canopy cover.}
\item{\code{CIIN}}{Percentage canopy cover.}
\item{\code{CIVU}}{Percentage canopy cover.}
\item{\code{DAGL}}{Percentage canopy cover.}
\item{\code{ELRE4}}{Percentage canopy cover.}
\item{\code{GAMO}}{Percentage canopy cover.}
\item{\code{LOAR10}}{Percentage canopy cover.}
\item{\code{LOCO6}}{Percentage canopy cover.}
\item{\code{LOPE}}{Percentage canopy cover.}
\item{\code{OXST}}{Percentage canopy cover.}
\item{\code{PLMA2}}{Percentage canopy cover.}
\item{\code{POPR}}{Percentage canopy cover.}
\item{\code{PRVU}}{Percentage canopy cover.}
\item{\code{RAAC3}}{Percentage canopy cover.}
\item{\code{RUCR}}{Percentage canopy cover.}
\item{\code{SORU2}}{Percentage canopy cover.}
\item{\code{STGR}}{Percentage canopy cover.}
\item{\code{TAOF}}{Percentage canopy cover.}
\item{\code{TRPR2}}{Percentage canopy cover.}
\item{\code{TRRE3}}{Percentage canopy cover.}
\item{\code{VEOF2}}{Percentage canopy cover.}
}
}
\details{
Site locations fall along a southwest-northeast transect through the northeastern United States. This is a synthetic gradient calculated from latitude and longitude.
Forest landcover is taken from the USGS 1992 National Land Cover Dataset. All forest classes were combined, and the percentage within 1 km of the sample sites was calculated using a GIS.
}
\source{
Details of these data are available in Tracy and Sanderson (2000) and Goslee and Sanderson (2010).
The 1992 NLCD data can be obtained from http://www.mrlc.gov/.
Species codes are from http://plants.usda.gov (2010).
}
\references{
Tracy, B.F. and M.A. Sanderson. 2000. Patterns of plant species richness in pasture lands of the northeast United States. Plant Ecology 149:169-180.
Goslee, S.C., Sanderson, M.A. 2010. Landscape Context and Plant Community Composition in Grazed Agricultural Systems. Landscape Ecology 25:1029-1039.
}
\author{ Sarah Goslee }
\examples{
data(graze)
}
\keyword{datasets}
|
/man/graze.Rd
|
no_license
|
cran/ecodist
|
R
| false
| false
| 2,876
|
rd
|
\name{graze}
\alias{graze}
\docType{data}
\title{ Site information and grazed vegetation data. }
\description{
This data frame contains site location, landscape context and dominant plant species abundances for 25 of the plant species found in 50 grazed pastures in the northeastern United States. Elements are the mean values for canopy cover for ten 0.5 x 2 m quadrats.
}
\usage{data(graze)}
\format{
A data frame with 50 observations on the following 25 variables.
\describe{
\item{\code{sitelocation}}{Site location along a geographic gradient.}
\item{\code{forestpct}}{Percentage forest cover within a 1-km radius.}
\item{\code{ACMI2}}{Percentage canopy cover.}
\item{\code{ANOD}}{Percentage canopy cover.}
\item{\code{ASSY}}{Percentage canopy cover.}
\item{\code{BRIN2}}{Percentage canopy cover.}
\item{\code{CIAR4}}{Percentage canopy cover.}
\item{\code{CIIN}}{Percentage canopy cover.}
\item{\code{CIVU}}{Percentage canopy cover.}
\item{\code{DAGL}}{Percentage canopy cover.}
\item{\code{ELRE4}}{Percentage canopy cover.}
\item{\code{GAMO}}{Percentage canopy cover.}
\item{\code{LOAR10}}{Percentage canopy cover.}
\item{\code{LOCO6}}{Percentage canopy cover.}
\item{\code{LOPE}}{Percentage canopy cover.}
\item{\code{OXST}}{Percentage canopy cover.}
\item{\code{PLMA2}}{Percentage canopy cover.}
\item{\code{POPR}}{Percentage canopy cover.}
\item{\code{PRVU}}{Percentage canopy cover.}
\item{\code{RAAC3}}{Percentage canopy cover.}
\item{\code{RUCR}}{Percentage canopy cover.}
\item{\code{SORU2}}{Percentage canopy cover.}
\item{\code{STGR}}{Percentage canopy cover.}
\item{\code{TAOF}}{Percentage canopy cover.}
\item{\code{TRPR2}}{Percentage canopy cover.}
\item{\code{TRRE3}}{Percentage canopy cover.}
\item{\code{VEOF2}}{Percentage canopy cover.}
}
}
\details{
Site locations fall along a southwest-northeast transect through the northeastern United States. This is a synthetic gradient calculated from latitude and longitude.
Forest landcover is taken from the USGS 1992 National Land Cover Dataset. All forest classes were combined, and the percentage within 1 km of the sample sites was calculated using a GIS.
}
\source{
Details of these data are available in Tracy and Sanderson (2000) and Goslee and Sanderson (2010).
The 1992 NLCD data can be obtained from http://www.mrlc.gov/.
Species codes are from http://plants.usda.gov (2010).
}
\references{
Tracy, B.F. and M.A. Sanderson. 2000. Patterns of plant species richness in pasture lands of the northeast United States. Plant Ecology 149:169-180.
Goslee, S.C., Sanderson, M.A. 2010. Landscape Context and Plant Community Composition in Grazed Agricultural Systems. Landscape Ecology 25:1029-1039.
}
\author{ Sarah Goslee }
\examples{
data(graze)
}
\keyword{datasets}
|
library(tidyverse)
library(ggplot2)
library(rstan)
library(shinystan)
setwd("~/basketball")
df = read_csv('data/rw_nba.csv')# %>% sample_n(1000)
sdata = list(N = nrow(df),
K = 80,
x = df$x,
y = df$result)
fit = stan('models/rff_bernoulli.stan', data = sdata, chains = 4, cores = 4, iter = 2000)
a = as_tibble(extract(fit, "f")$f)
colnames(a) = 1:ncol(a)
b = as_tibble(list(idx = 1:nrow(df), time = df$elapsed))
out = inner_join(a %>% gather(idx, f) %>% mutate(idx = as.integer(idx)), b, by = "idx")
summary = out %>% group_by(time) %>%
summarize(mean = mean(f),
q1 = quantile(f, 0.025),
q2 = quantile(f, 0.167),
q3 = quantile(f, 0.833),
q4 = quantile(f, 0.975)) %>%
ungroup()
#write_csv(summary, "westbrook_rff2.csv")
summary %>% ggplot(aes(time, mean)) +
geom_ribbon(aes(ymin = q1, ymax = q2), alpha = 0.75, fill = "dodgerblue2") +
geom_ribbon(aes(ymin = q2, ymax = q3), alpha = 0.75, fill = "orangered1") +
geom_ribbon(aes(ymin = q3, ymax = q4), alpha = 0.75, fill = "dodgerblue2") +
geom_line() +
geom_line(aes(time, q1), alpha = 1.0, size = 0.125) +
geom_line(aes(time, q2), alpha = 1.0, size = 0.125) +
geom_line(aes(time, q3), alpha = 1.0, size = 0.125) +
geom_line(aes(time, q4), alpha = 1.0, size = 0.125) +
xlab("Game time") +
ylab("Shooting percentage") +
ggtitle("Russell Westbrook's shooting percentage (w/ est. 95% conf. intervals)")
|
/westbrook_rff.R
|
no_license
|
bbbales2/basketball
|
R
| false
| false
| 1,468
|
r
|
library(tidyverse)
library(ggplot2)
library(rstan)
library(shinystan)
setwd("~/basketball")
df = read_csv('data/rw_nba.csv')# %>% sample_n(1000)
sdata = list(N = nrow(df),
K = 80,
x = df$x,
y = df$result)
fit = stan('models/rff_bernoulli.stan', data = sdata, chains = 4, cores = 4, iter = 2000)
a = as_tibble(extract(fit, "f")$f)
colnames(a) = 1:ncol(a)
b = as_tibble(list(idx = 1:nrow(df), time = df$elapsed))
out = inner_join(a %>% gather(idx, f) %>% mutate(idx = as.integer(idx)), b, by = "idx")
summary = out %>% group_by(time) %>%
summarize(mean = mean(f),
q1 = quantile(f, 0.025),
q2 = quantile(f, 0.167),
q3 = quantile(f, 0.833),
q4 = quantile(f, 0.975)) %>%
ungroup()
#write_csv(summary, "westbrook_rff2.csv")
summary %>% ggplot(aes(time, mean)) +
geom_ribbon(aes(ymin = q1, ymax = q2), alpha = 0.75, fill = "dodgerblue2") +
geom_ribbon(aes(ymin = q2, ymax = q3), alpha = 0.75, fill = "orangered1") +
geom_ribbon(aes(ymin = q3, ymax = q4), alpha = 0.75, fill = "dodgerblue2") +
geom_line() +
geom_line(aes(time, q1), alpha = 1.0, size = 0.125) +
geom_line(aes(time, q2), alpha = 1.0, size = 0.125) +
geom_line(aes(time, q3), alpha = 1.0, size = 0.125) +
geom_line(aes(time, q4), alpha = 1.0, size = 0.125) +
xlab("Game time") +
ylab("Shooting percentage") +
ggtitle("Russell Westbrook's shooting percentage (w/ est. 95% conf. intervals)")
|
# Setup
library(googlesheets)
library(dplyr)
library(lubridate)
library(zoo)
library(randomForest)
library(timeDate)
library(rvest)
library(tidyr)
library(jsonlite)
library(shiny)
library(ggplot2)
library(data.table)
# Helper Functions
get_monthly_weather <- function(airport="PDX", date=as.Date("2016-12-19")) {
url <- paste0('https://www.wunderground.com/history/airport/',airport,'/',
year(date),'/',
month(date),'/',
day(date),'/',
'MonthlyHistory.html')
page <- read_html(url)
closeAllConnections()
weather_data <- page %>%
html_nodes("table") %>%
.[[4]] %>%
html_table() %>%
as.data.table()
setnames(weather_data, c("day","temp_max","temp_avg","temp_min",
"dew_high","dew_avg","dew_low",
"humidity_high","humidity","humidity_low",
"pressure_high","pressure_avg","pressure_low",
"visibility_high","visibility_avg","visibility_low",
"wind_high","wind","wind_dir",
"precipitation","conditions"))
weather_data = weather_data[-1]
weather_data[,month:=month(date)]
weather_data[,year:=year(date)]
weather_data[,date:=ymd(paste(year,month,day,sep="-"))]
# convert columns to numeric
names = colnames(weather_data)
ignore = c("conditions","date","precipitation")
names = names[!names %in% ignore]
dtnew <- weather_data[,(names):=lapply(.SD, as.numeric), .SDcols = names]
}
get_weather_forecast <- function(airport="PDX")
{
base_url <- paste0('http://api.wunderground.com/api/',wu.apikey,'/')
final_url <- paste0(base_url, 'forecast10day/q/',airport, '.json')
# reading in as raw lines from the web service
conn <- url(final_url)
raw_data <- readLines(conn, n=-1L, ok=TRUE)
# Convert to a JSON
weather_data <- fromJSON(paste(raw_data, collapse=""))
close(conn)
return(weather_data)
}
get_season = function(dates) {
WS = as.Date("2012-12-15", format = "%Y-%m-%d") # Winter Solstice
SE = as.Date("2012-3-15", format = "%Y-%m-%d") # Spring Equinox
SS = as.Date("2012-6-15", format = "%Y-%m-%d") # Summer Solstice
FE = as.Date("2012-9-15", format = "%Y-%m-%d") # Fall Equinox
# Convert dates from any year to 2012 dates
d = as.Date(strftime(dates, format="2012-%m-%d"))
ifelse (d >= WS | d < SE, "Winter",
ifelse (d >= SE & d < SS, "Spring",
ifelse (d >= SS & d < FE, "Summer", "Fall")))
}
get_holiday = function(holidays=listHolidays("US"),dates) {
years = year(dates)
years_levels = levels(as.factor(years))
holiday_date = data.table()
for (h in holidays) {
for (y in years_levels) {
y = as.list(as.numeric(y))
holiday_date = rbind(holiday_date,do.call(h,y))
}
}
holiday_date = as.Date(holiday_date$`GMT:x`)
holiday = ifelse(dates %in% holiday_date,1,0)
}
get_weather_condition = function(conditions1,conditions2,conditions3) {
if (!is.na(conditions2) & !is.na(conditions3)) {
c = sample(c(conditions1,conditions2,conditions3),1)
} else if (!is.na(conditions2)) {
c = sample(c(conditions1,conditions2),1)
} else {
c = conditions1
}
return(c)
}
##############################
# Pyro Pizza Data ############
##############################
pyrodata = setDT(read.csv(file="pyrodata.csv"))
pyrodata[,date:=as.Date(date)]
# # (my_sheets <- gs_ls())
# # fin2016 = gs_title("2016 Springwater Ledger")
pyro = gs_key("18eViJiRTmdNkYtZrwOpHqy-39RrhamL8EfemAvuhPXM")
# # gs_ws_ls(fin2016)
inventory = pyro %>% gs_read_csv(ws = "INVENTORY", skip=0) %>% as.data.table
# fixing the dates in the 2016 data
setnames(inventory,colnames(inventory),c("date","day","initial_inventory","par","prep_rec","prep_actual","waste","final_inventory","short_long","scale","use_expected","use_actual","temp","precip","clouds","sun","wind","humidity","holiday","event"))
inventory = inventory[-1]
inventory[,c("event","temp","precip","clouds","sun","wind","humidity","holiday"):=NULL]
inventory[,date:=mdy(date)]
inventory[,use_actual:=as.double(use_actual)]
inventory[,initial_inventory:=as.double(initial_inventory)]
inventory[,par:=as.double(par)]
inventory[,prep_rec:=as.double(prep_rec)]
inventory[,prep_actual:=as.double(prep_actual)]
inventory[,waste:=as.double(waste)]
inventory[,final_inventory:=as.double(final_inventory)]
inventory[,short_long:=as.double(short_long)]
# inventory = inventory[use_actual!=0]
# inventory = inventory[!is.na(use_actual)]
##############################
# Forecast Data ############
##############################
wu.apikey = readLines("config.io",warn=F)
rwunderground::set_api_key(wu.apikey)
weather_data <- get_weather_forecast('PDX')
weather_data = setDT(weather_data$forecast$simpleforecast$forecastday)
forecast = data.table(date=seq(Sys.Date(),Sys.Date()+9,by='day'),
temp_max=weather_data$high[[1]],
temp_min=weather_data$low[[1]],
conditions=weather_data$conditions,
rain=weather_data$qpf_allday[[1]],
snow=weather_data$snow_allday[[1]],
humidity=weather_data$avehumidity,
wind=weather_data$avewind[[1]])
forecast[,date:=as.Date(date)]
forecast[,temp_max:=as.numeric(temp_max)]
forecast[,temp_min:=as.numeric(temp_min)]
# getting rid of "Chance of a "
forecast$conditions = gsub("Chance of a ","",forecast$conditions)
forecast$conditions = gsub("Chance of ","",forecast$conditions)
table(forecast$conditions)
# changing conditions to match conditions from the training data
forecast[conditions=="Clear",conditions:="Scattered Clouds"]
forecast[conditions=="Hail",conditions:="Thunderstorm"]
##############################
# Preparing Features #########
##############################
# merging inventory and forecast
dt <- merge(inventory,forecast,by="date",all=TRUE)
# combining pyrodata and current inventory with forecast
names <- colnames(dt)
pyrodata <- pyrodata[,names,with=FALSE]
dt = rbind(pyrodata[date<Sys.Date()],dt[date>=Sys.Date()])
# adding seasons
dt[,season:=get_season(date)]
# adding holidays
dt[,holiday:=get_holiday(listHolidays("US"),date)]
# adding day of the week
dt[,day:=weekdays(date)]
# adding day
dt[,day:=weekdays(date)]
# adding day
dt[,month:=month(date)]
# creating average use compared to previous 7 days, 3 days, 1 day
dt[,':=' (use7=rollapply(use_actual, width=list(-(7:1)), FUN=mean, fill="extend", na.rm=T),
use3=rollapply(use_actual, width=list(-(3:1)), FUN=mean, fill="extend", na.rm=T),
use1=rollapply(use_actual, width=list(-(1:1)), FUN=mean, fill="extend", na.rm=T))]
# creating use 3, use 1, and use 7 for forecast data
dt[,use3:=ifelse(is.na(use3),.SD[match(date - 7,.SD[,date]),use3],use3)]
dt[,use1:=ifelse(is.na(use1),.SD[match(date - 7,.SD[,date]),use1],use1)]
dt[,use7:=ifelse(is.na(use7),.SD[match(date - 7,.SD[,date]),use7],use7)]
# adding average use for day of week by month
dt[,':=' (avgUse=mean(use_actual, na.rm=T),
medUse=median(use_actual, na.rm=T),
quart1Use=quantile(use_actual, na.rm=T)[2],
quart3Use=quantile(use_actual, na.rm=T)[4],
maxUse=max(use_actual, na.rm=T)),
by=.(day,season)]
# center and scale all numerical features
dt[, ':=' (temp_maxz=scale(temp_max),
temp_minz=scale(temp_min),
humidityz=scale(humidity),
windz=scale(wind),
snowz=scale(snow),
rainz=scale(rain),
use7z=scale(use7),
use3z=scale(use3),
use1z=scale(use1),
avgUsez=scale(avgUse),
medUsez=scale(medUse),
quart1Usez=scale(quart1Use),
quart3Usez=scale(quart3Use),
maxUsez=scale(maxUse))]
# making the categorical variables factors
dt$day = as.factor(dt$day)
dt$season = as.factor(dt$season)
dt$conditions = as.character(dt$conditions)
dt$conditions = as.factor(dt$conditions)
dt$month = as.factor(dt$month)
dt$holiday = as.factor(dt$holiday)
##############################
# Predictor ############
##############################
# load(file="rfuse.RData")
rfuse = randomForest(use_actual ~ day + holiday + conditions + season + month +
temp_maxz + temp_minz + humidityz + windz + rainz +
use7z + use3z + use1z + avgUsez + medUsez + quart1Usez + quart3Usez + maxUsez,
data = dt[!is.na(use_actual) & use_actual!=0])
dt[,use_predicted:=round(predict(rfuse,dt,type="response"))]
dt[order(-date)]
write.csv(dt,file="pyrodata.csv")
# imp = importance(rfuse)
# MAE = mean(abs(dt$use_actual-dt$use_predicted),na.rm=T)
# MAE_baseline = mean(abs(dt$use_actual-dt$use_expected), na.rm=T)
#
# R2 <- 1 - (sum((ntest$use_actual-ntest$use_predicted)^2)/sum((ntest$use_actual-mean(ntest$use_actual))^2))
# R2_baseline <- 1 - (sum((ntest$use_actual-ntest$use_expected)^2)/sum((ntest$use_actual-mean(ntest$use_actual))^2))
dt[,par:=ifelse(date==Sys.Date(),rollapply(use_predicted,
width=4,
align="right",
FUN=sum,
# fill="extend",
na.rm=T),par)]
# importance(rfuse)
# MAE = mean(abs(dt$use_actual-dt$use_predicted))
# MAE_baseline = mean(abs(dt$use_actual-dt$use_expected))
#
# R2 <- 1 - (sum((dt$use_actual-dt$use_predicted)^2)/sum((dt$use_actual-mean(dt$use_actual))^2))
# R2_baseline <- 1 - (sum((dt$use_actual-dt$use_expected)^2)/sum((dt$use_actual-mean(dt$use_actual))^2))
# dt[date==Sys.Date(),short_long:=final_inventory - par]
|
/global.R
|
no_license
|
ntbryant/PyroPizzaPredictor
|
R
| false
| false
| 9,718
|
r
|
# Setup
library(googlesheets)
library(dplyr)
library(lubridate)
library(zoo)
library(randomForest)
library(timeDate)
library(rvest)
library(tidyr)
library(jsonlite)
library(shiny)
library(ggplot2)
library(data.table)
# Helper Functions
get_monthly_weather <- function(airport="PDX", date=as.Date("2016-12-19")) {
url <- paste0('https://www.wunderground.com/history/airport/',airport,'/',
year(date),'/',
month(date),'/',
day(date),'/',
'MonthlyHistory.html')
page <- read_html(url)
closeAllConnections()
weather_data <- page %>%
html_nodes("table") %>%
.[[4]] %>%
html_table() %>%
as.data.table()
setnames(weather_data, c("day","temp_max","temp_avg","temp_min",
"dew_high","dew_avg","dew_low",
"humidity_high","humidity","humidity_low",
"pressure_high","pressure_avg","pressure_low",
"visibility_high","visibility_avg","visibility_low",
"wind_high","wind","wind_dir",
"precipitation","conditions"))
weather_data = weather_data[-1]
weather_data[,month:=month(date)]
weather_data[,year:=year(date)]
weather_data[,date:=ymd(paste(year,month,day,sep="-"))]
# convert columns to numeric
names = colnames(weather_data)
ignore = c("conditions","date","precipitation")
names = names[!names %in% ignore]
dtnew <- weather_data[,(names):=lapply(.SD, as.numeric), .SDcols = names]
}
get_weather_forecast <- function(airport="PDX")
{
base_url <- paste0('http://api.wunderground.com/api/',wu.apikey,'/')
final_url <- paste0(base_url, 'forecast10day/q/',airport, '.json')
# reading in as raw lines from the web service
conn <- url(final_url)
raw_data <- readLines(conn, n=-1L, ok=TRUE)
# Convert to a JSON
weather_data <- fromJSON(paste(raw_data, collapse=""))
close(conn)
return(weather_data)
}
get_season = function(dates) {
WS = as.Date("2012-12-15", format = "%Y-%m-%d") # Winter Solstice
SE = as.Date("2012-3-15", format = "%Y-%m-%d") # Spring Equinox
SS = as.Date("2012-6-15", format = "%Y-%m-%d") # Summer Solstice
FE = as.Date("2012-9-15", format = "%Y-%m-%d") # Fall Equinox
# Convert dates from any year to 2012 dates
d = as.Date(strftime(dates, format="2012-%m-%d"))
ifelse (d >= WS | d < SE, "Winter",
ifelse (d >= SE & d < SS, "Spring",
ifelse (d >= SS & d < FE, "Summer", "Fall")))
}
get_holiday = function(holidays=listHolidays("US"),dates) {
years = year(dates)
years_levels = levels(as.factor(years))
holiday_date = data.table()
for (h in holidays) {
for (y in years_levels) {
y = as.list(as.numeric(y))
holiday_date = rbind(holiday_date,do.call(h,y))
}
}
holiday_date = as.Date(holiday_date$`GMT:x`)
holiday = ifelse(dates %in% holiday_date,1,0)
}
get_weather_condition = function(conditions1,conditions2,conditions3) {
if (!is.na(conditions2) & !is.na(conditions3)) {
c = sample(c(conditions1,conditions2,conditions3),1)
} else if (!is.na(conditions2)) {
c = sample(c(conditions1,conditions2),1)
} else {
c = conditions1
}
return(c)
}
##############################
# Pyro Pizza Data ############
##############################
pyrodata = setDT(read.csv(file="pyrodata.csv"))
pyrodata[,date:=as.Date(date)]
# # (my_sheets <- gs_ls())
# # fin2016 = gs_title("2016 Springwater Ledger")
pyro = gs_key("18eViJiRTmdNkYtZrwOpHqy-39RrhamL8EfemAvuhPXM")
# # gs_ws_ls(fin2016)
inventory = pyro %>% gs_read_csv(ws = "INVENTORY", skip=0) %>% as.data.table
# fixing the dates in the 2016 data
setnames(inventory,colnames(inventory),c("date","day","initial_inventory","par","prep_rec","prep_actual","waste","final_inventory","short_long","scale","use_expected","use_actual","temp","precip","clouds","sun","wind","humidity","holiday","event"))
inventory = inventory[-1]
inventory[,c("event","temp","precip","clouds","sun","wind","humidity","holiday"):=NULL]
inventory[,date:=mdy(date)]
inventory[,use_actual:=as.double(use_actual)]
inventory[,initial_inventory:=as.double(initial_inventory)]
inventory[,par:=as.double(par)]
inventory[,prep_rec:=as.double(prep_rec)]
inventory[,prep_actual:=as.double(prep_actual)]
inventory[,waste:=as.double(waste)]
inventory[,final_inventory:=as.double(final_inventory)]
inventory[,short_long:=as.double(short_long)]
# inventory = inventory[use_actual!=0]
# inventory = inventory[!is.na(use_actual)]
##############################
# Forecast Data ############
##############################
wu.apikey = readLines("config.io",warn=F)
rwunderground::set_api_key(wu.apikey)
weather_data <- get_weather_forecast('PDX')
weather_data = setDT(weather_data$forecast$simpleforecast$forecastday)
forecast = data.table(date=seq(Sys.Date(),Sys.Date()+9,by='day'),
temp_max=weather_data$high[[1]],
temp_min=weather_data$low[[1]],
conditions=weather_data$conditions,
rain=weather_data$qpf_allday[[1]],
snow=weather_data$snow_allday[[1]],
humidity=weather_data$avehumidity,
wind=weather_data$avewind[[1]])
forecast[,date:=as.Date(date)]
forecast[,temp_max:=as.numeric(temp_max)]
forecast[,temp_min:=as.numeric(temp_min)]
# getting rid of "Chance of a "
forecast$conditions = gsub("Chance of a ","",forecast$conditions)
forecast$conditions = gsub("Chance of ","",forecast$conditions)
table(forecast$conditions)
# changing conditions to match conditions from the training data
forecast[conditions=="Clear",conditions:="Scattered Clouds"]
forecast[conditions=="Hail",conditions:="Thunderstorm"]
##############################
# Preparing Features #########
##############################
# merging inventory and forecast
dt <- merge(inventory,forecast,by="date",all=TRUE)
# combining pyrodata and current inventory with forecast
names <- colnames(dt)
pyrodata <- pyrodata[,names,with=FALSE]
dt = rbind(pyrodata[date<Sys.Date()],dt[date>=Sys.Date()])
# adding seasons
dt[,season:=get_season(date)]
# adding holidays
dt[,holiday:=get_holiday(listHolidays("US"),date)]
# adding day of the week
dt[,day:=weekdays(date)]
# adding day
dt[,day:=weekdays(date)]
# adding day
dt[,month:=month(date)]
# creating average use compared to previous 7 days, 3 days, 1 day
dt[,':=' (use7=rollapply(use_actual, width=list(-(7:1)), FUN=mean, fill="extend", na.rm=T),
use3=rollapply(use_actual, width=list(-(3:1)), FUN=mean, fill="extend", na.rm=T),
use1=rollapply(use_actual, width=list(-(1:1)), FUN=mean, fill="extend", na.rm=T))]
# creating use 3, use 1, and use 7 for forecast data
dt[,use3:=ifelse(is.na(use3),.SD[match(date - 7,.SD[,date]),use3],use3)]
dt[,use1:=ifelse(is.na(use1),.SD[match(date - 7,.SD[,date]),use1],use1)]
dt[,use7:=ifelse(is.na(use7),.SD[match(date - 7,.SD[,date]),use7],use7)]
# adding average use for day of week by month
dt[,':=' (avgUse=mean(use_actual, na.rm=T),
medUse=median(use_actual, na.rm=T),
quart1Use=quantile(use_actual, na.rm=T)[2],
quart3Use=quantile(use_actual, na.rm=T)[4],
maxUse=max(use_actual, na.rm=T)),
by=.(day,season)]
# center and scale all numerical features
dt[, ':=' (temp_maxz=scale(temp_max),
temp_minz=scale(temp_min),
humidityz=scale(humidity),
windz=scale(wind),
snowz=scale(snow),
rainz=scale(rain),
use7z=scale(use7),
use3z=scale(use3),
use1z=scale(use1),
avgUsez=scale(avgUse),
medUsez=scale(medUse),
quart1Usez=scale(quart1Use),
quart3Usez=scale(quart3Use),
maxUsez=scale(maxUse))]
# making the categorical variables factors
dt$day = as.factor(dt$day)
dt$season = as.factor(dt$season)
dt$conditions = as.character(dt$conditions)
dt$conditions = as.factor(dt$conditions)
dt$month = as.factor(dt$month)
dt$holiday = as.factor(dt$holiday)
##############################
# Predictor ############
##############################
# load(file="rfuse.RData")
rfuse = randomForest(use_actual ~ day + holiday + conditions + season + month +
temp_maxz + temp_minz + humidityz + windz + rainz +
use7z + use3z + use1z + avgUsez + medUsez + quart1Usez + quart3Usez + maxUsez,
data = dt[!is.na(use_actual) & use_actual!=0])
dt[,use_predicted:=round(predict(rfuse,dt,type="response"))]
dt[order(-date)]
write.csv(dt,file="pyrodata.csv")
# imp = importance(rfuse)
# MAE = mean(abs(dt$use_actual-dt$use_predicted),na.rm=T)
# MAE_baseline = mean(abs(dt$use_actual-dt$use_expected), na.rm=T)
#
# R2 <- 1 - (sum((ntest$use_actual-ntest$use_predicted)^2)/sum((ntest$use_actual-mean(ntest$use_actual))^2))
# R2_baseline <- 1 - (sum((ntest$use_actual-ntest$use_expected)^2)/sum((ntest$use_actual-mean(ntest$use_actual))^2))
dt[,par:=ifelse(date==Sys.Date(),rollapply(use_predicted,
width=4,
align="right",
FUN=sum,
# fill="extend",
na.rm=T),par)]
# importance(rfuse)
# MAE = mean(abs(dt$use_actual-dt$use_predicted))
# MAE_baseline = mean(abs(dt$use_actual-dt$use_expected))
#
# R2 <- 1 - (sum((dt$use_actual-dt$use_predicted)^2)/sum((dt$use_actual-mean(dt$use_actual))^2))
# R2_baseline <- 1 - (sum((dt$use_actual-dt$use_expected)^2)/sum((dt$use_actual-mean(dt$use_actual))^2))
# dt[date==Sys.Date(),short_long:=final_inventory - par]
|
library(tidyverse)
library(toolbox)
# reference ---------------------------------------------------------------
met.thresh.df <-
data.table::fread(
"H:/Projects/Chessie_BIBI/report/FINAL_May25_2017/2017_Data/Metric_Thresholds/metric_thresholds.csv"
) %>%
toolbox::prep_df() %>%
filter(
taxonomic_resolution == "family",!spatial_resolution %in% c("basin", "inland", "coast")
) %>%
arrange(taxonomic_resolution, metric)
metrics <- sort(unique(met.thresh.df$metric))
# calc metrics ------------------------------------------------------------
bio_fam_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
aspt_mod = taxa_tol_index(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
tol.col = aspt_mod
),
pct_gastro_oligo = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = class,
taxon = c("gastropoda", "oligochatea")
),
pct_diptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "diptera"
),
gold = 1 - (pct_gastro_oligo + pct_diptera),
hbi = taxa_tol_index(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
tol.col = tol_value
),
pct_arthropoda = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = phylum,
taxon = "arthropda"
),
pct_burrow = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "burrow"
),
pct_chironomidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "chironomidae"
),
pct_cling = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "cling"
),
pct_burrow = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "burrow"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
pct_cote = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("coleoptera",
"odonata",
"trichoptera",
"ephemeroptera")
),
pct_ephemeroptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "ephemeroptera"
),
pct_baetidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "baetidae"
),
pct_ephemeroptera_no_baetid = pct_ephemeroptera - pct_baetidae,
pct_ept = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera",
"plecoptera",
"trichoptera")
),
pct_hydropsychidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "hydropsychidae"
),
pct_ept_no_hydro = pct_ept - pct_hydropsychidae,
pct_euholognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "euholognatha"
),
pct_filter = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "filter"
),
pct_heptageniidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "heptageniidae"
),
pct_hexapoda = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = subphylum,
taxon = "hexapoda"
),
pct_hydro_ept = ifelse(pct_ept == 0,
0,
(pct_hydropsychidae / pct_ept) * 100),
pct_intol_0_3 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 0:3
),
pct_intol_0_4 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 0:4
),
pct_amph_iso = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("amphipoda", "isopoda")
),
pct_ephemerellidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "ephemerellidae"
),
pct_limestone = pct_amph_iso + pct_ephemerellidae,
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_trichoptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "trichoptera"
),
pct_non_hydrop_trichoptera = pct_trichoptera - pct_hydropsychidae,
pct_odonata = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "odonata"
),
pct_pisciforma = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "pisciforma"
),
pct_predator = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "predator"
),
pct_pterygota = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = subclass,
taxon = "pterygota"
),
pct_retreat_caddisfly = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "annulipalpia"
),
pct_scrape = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "scrape"
),
pct_sprawl = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "sprawl"
),
pct_systellognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "systellognatha"
),
pct_tolerant_7_10 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 7:10
),
pct_urban_intol = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = c(
"aeshnidae",
"ameletidae",
"asellidae",
"athericidae",
"baetidae",
"brachycentridae",
"caenidae",
"calamoceratidae",
"cambaridae",
"capniidae",
"ceratopogonidae",
"chironomidae",
"chloroperlidae",
"cordulegastridae",
"corduliidae",
"corydalidae",
"crangonyctidae",
"elmidae",
"ephemerellidae",
"ephemeridae",
"glossosomatidae",
"gomphidae",
"heptageniidae",
"hydropsychidae",
"hydroptilidae",
"isonychiidae",
"lepidostomatidae",
"leptophlebiidae",
"leuctridae",
"libellulidae",
"metretopodidae",
"nemouridae",
"odontoceridae",
"peltoperlidae",
"perlidae",
"perlodidae",
"philopotamidae",
"phryganeidae",
"polycentropodidae",
"polymitarcyidae",
"potamanthidae",
"psephenidae",
"pteronarcyidae",
"rhyacophilidae",
"sericostomatidae",
"sialidae",
"simuliidae",
"stratiomyidae",
"tabanidae",
"taeniopterygidae",
"tipulidae",
"uenoidae",
"viviparidae"
)
),
# Richness/Diversity metrics require rarefied data.
margalefs = taxa_div(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
low.taxa.col = NULL,
high.taxa.col = family,
job = "margalef"
),
pct_ept_rich = taxa_pct_rich(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera", "plecoptera", "trichotpera"),
high.res.taxa.col = family,
exclusion.col = NULL,
exclusion.vec = NULL
),
pct_ept_rich_no_tol = taxa_pct_rich(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera", "plecoptera", "trichotpera"),
high.res.taxa.col = family,
exclusion.col = tol_val,
exclusion.vec = 7:10
),
pielou = taxa_div(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
low.taxa.col = NULL,
high.taxa.col = family,
job = "pielou"
),
rich_burrow = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "burrow"
),
rich_climb = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "climb"
),
rich_cling = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "cling"
),
rich_collect = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = c("filter", "gather")
),
rich_ephemeroptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "ephemeroptera"
),
rich_ept = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = c("ephemeroptera",
"plecoptera",
"trichoptera")
),
rich_filter = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "filter"
),
rich_gather = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "gather"
),
rich_intol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 0:3
),
rich_modtol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 4:6
),
rich_plecoptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "plecoptera"
),
rich_predator = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "predator"
),
rich_shred = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "shred"
),
rich_sprawl = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "sprawl"
),
rich_tol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 7:10
),
rich_trichoptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "trichoptera"
)
)
}
# blue --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "blue", "metric"]
blue_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
pct_systellognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "systellognatha"
),
pct_scrape = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "scrape"
),
pct_burrow = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "burrow"
),
rich_ephemeroptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "ephemeroptera"
)#,
# pct_ept_rich_no_tol =
)
}
# ca --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "ca", "metric"]
ca_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
# pct_ept_rich =
pct_euholognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "euholognatha"
),
pct_heptageniidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "heptageniidae"
),
pct_hydropsychidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "hydropsychidae"
),
pct_ept = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera",
"plecoptera",
"trichoptera")
),
pct_hydro_ept = pct_ept - pct_hydropsychidae,
############################ CORRECT?
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_trichoptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "trichoptera"
),
pct_non_hydrop_trichoptera = pct_trichoptera - pct_hydropsychidae,
pct_pisciforma = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "pisciforma"
),
pct_systellognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "systellognatha"
),
rich_burrow = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "burrow"
),
rich_collect = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = c("filter", "gather")
),
rich_filter = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "filter"
),
rich_plecoptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "plecoptera"
),
rich_predator = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "predator"
)
) %>%
select(-pct_hydropsychidae,-pct_ept,-pct_trichoptera)
}
# lnp --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "lnp", "metric"]
lnp_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
#aspt_mod = ################################################################## build
pct_cling = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "cling"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
#pct_ept_rich = ########################################################### build
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_predator = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "predator"
),
pct_pterygota = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = subclass,
taxon = "pterygota"
),
rich_cling = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "cling"
),
rich_ephemeroptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "ephemeroptera"
)
)
}
# mac --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "mac", "metric"]
mac_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
#aspt_mod = ################################################################## build
pct_gastro_oligo = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = class,
taxon = c("gastropoda", "oligochatea")
),
pct_diptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "diptera"
),
gold = 1 - (pct_gastro_oligo + pct_diptera),
pct_arthropoda = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = phylum,
taxon = "arthropda"
),
pct_chironomidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "chironomidae"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_odonata = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "odonata"
),
pct_predator = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "predator"
),
pct_scrape = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "scrape"
),
# pct_urban_intol = taxa_pct(long.df = x, #################### LOOK UP
# unique.id.col = unique_id,
# count.col = reporting_value,
# taxon.col = family,
# taxon = c()),
rich_climb = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "climb"
),
rich_tol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 7:10
)
) %>%
select(-pct_gastro_oligo,-pct_diptera)
}
# napu --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "napu", "metric"]
napu_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
margalefs = taxa_div(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
low.taxa.col = NULL,
high.taxa.col = family,
job = "margalef"
),
pct_cling = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "cling"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
pct_ephemeroptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "ephemeroptera"
),
)
}
# nca --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "nca", "metric"]
nca_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# nrv --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "nrv", "metric"]
nrv_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# pied --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "pied", "metric"]
pied_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# sep --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "sep", "metric"]
sep_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# sgv --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "sgv", "metric"]
sgv_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# srv --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "srv", "metric"]
srv_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# unp --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "unp", "metric"]
unp_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
|
/dev/bio_fam_funs_dev_old.R
|
no_license
|
InterstateCommissionPotomacRiverBasin/bibi2.0
|
R
| false
| false
| 25,297
|
r
|
library(tidyverse)
library(toolbox)
# reference ---------------------------------------------------------------
met.thresh.df <-
data.table::fread(
"H:/Projects/Chessie_BIBI/report/FINAL_May25_2017/2017_Data/Metric_Thresholds/metric_thresholds.csv"
) %>%
toolbox::prep_df() %>%
filter(
taxonomic_resolution == "family",!spatial_resolution %in% c("basin", "inland", "coast")
) %>%
arrange(taxonomic_resolution, metric)
metrics <- sort(unique(met.thresh.df$metric))
# calc metrics ------------------------------------------------------------
bio_fam_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
aspt_mod = taxa_tol_index(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
tol.col = aspt_mod
),
pct_gastro_oligo = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = class,
taxon = c("gastropoda", "oligochatea")
),
pct_diptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "diptera"
),
gold = 1 - (pct_gastro_oligo + pct_diptera),
hbi = taxa_tol_index(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
tol.col = tol_value
),
pct_arthropoda = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = phylum,
taxon = "arthropda"
),
pct_burrow = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "burrow"
),
pct_chironomidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "chironomidae"
),
pct_cling = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "cling"
),
pct_burrow = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "burrow"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
pct_cote = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("coleoptera",
"odonata",
"trichoptera",
"ephemeroptera")
),
pct_ephemeroptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "ephemeroptera"
),
pct_baetidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "baetidae"
),
pct_ephemeroptera_no_baetid = pct_ephemeroptera - pct_baetidae,
pct_ept = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera",
"plecoptera",
"trichoptera")
),
pct_hydropsychidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "hydropsychidae"
),
pct_ept_no_hydro = pct_ept - pct_hydropsychidae,
pct_euholognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "euholognatha"
),
pct_filter = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "filter"
),
pct_heptageniidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "heptageniidae"
),
pct_hexapoda = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = subphylum,
taxon = "hexapoda"
),
pct_hydro_ept = ifelse(pct_ept == 0,
0,
(pct_hydropsychidae / pct_ept) * 100),
pct_intol_0_3 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 0:3
),
pct_intol_0_4 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 0:4
),
pct_amph_iso = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("amphipoda", "isopoda")
),
pct_ephemerellidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "ephemerellidae"
),
pct_limestone = pct_amph_iso + pct_ephemerellidae,
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_trichoptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "trichoptera"
),
pct_non_hydrop_trichoptera = pct_trichoptera - pct_hydropsychidae,
pct_odonata = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "odonata"
),
pct_pisciforma = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "pisciforma"
),
pct_predator = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "predator"
),
pct_pterygota = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = subclass,
taxon = "pterygota"
),
pct_retreat_caddisfly = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "annulipalpia"
),
pct_scrape = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "scrape"
),
pct_sprawl = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "sprawl"
),
pct_systellognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "systellognatha"
),
pct_tolerant_7_10 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 7:10
),
pct_urban_intol = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = c(
"aeshnidae",
"ameletidae",
"asellidae",
"athericidae",
"baetidae",
"brachycentridae",
"caenidae",
"calamoceratidae",
"cambaridae",
"capniidae",
"ceratopogonidae",
"chironomidae",
"chloroperlidae",
"cordulegastridae",
"corduliidae",
"corydalidae",
"crangonyctidae",
"elmidae",
"ephemerellidae",
"ephemeridae",
"glossosomatidae",
"gomphidae",
"heptageniidae",
"hydropsychidae",
"hydroptilidae",
"isonychiidae",
"lepidostomatidae",
"leptophlebiidae",
"leuctridae",
"libellulidae",
"metretopodidae",
"nemouridae",
"odontoceridae",
"peltoperlidae",
"perlidae",
"perlodidae",
"philopotamidae",
"phryganeidae",
"polycentropodidae",
"polymitarcyidae",
"potamanthidae",
"psephenidae",
"pteronarcyidae",
"rhyacophilidae",
"sericostomatidae",
"sialidae",
"simuliidae",
"stratiomyidae",
"tabanidae",
"taeniopterygidae",
"tipulidae",
"uenoidae",
"viviparidae"
)
),
# Richness/Diversity metrics require rarefied data.
margalefs = taxa_div(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
low.taxa.col = NULL,
high.taxa.col = family,
job = "margalef"
),
pct_ept_rich = taxa_pct_rich(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera", "plecoptera", "trichotpera"),
high.res.taxa.col = family,
exclusion.col = NULL,
exclusion.vec = NULL
),
pct_ept_rich_no_tol = taxa_pct_rich(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera", "plecoptera", "trichotpera"),
high.res.taxa.col = family,
exclusion.col = tol_val,
exclusion.vec = 7:10
),
pielou = taxa_div(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
low.taxa.col = NULL,
high.taxa.col = family,
job = "pielou"
),
rich_burrow = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "burrow"
),
rich_climb = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "climb"
),
rich_cling = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "cling"
),
rich_collect = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = c("filter", "gather")
),
rich_ephemeroptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "ephemeroptera"
),
rich_ept = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = c("ephemeroptera",
"plecoptera",
"trichoptera")
),
rich_filter = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "filter"
),
rich_gather = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "gather"
),
rich_intol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 0:3
),
rich_modtol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 4:6
),
rich_plecoptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "plecoptera"
),
rich_predator = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "predator"
),
rich_shred = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "shred"
),
rich_sprawl = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "sprawl"
),
rich_tol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 7:10
),
rich_trichoptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "trichoptera"
)
)
}
# blue --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "blue", "metric"]
blue_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
pct_systellognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "systellognatha"
),
pct_scrape = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "scrape"
),
pct_burrow = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "burrow"
),
rich_ephemeroptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "ephemeroptera"
)#,
# pct_ept_rich_no_tol =
)
}
# ca --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "ca", "metric"]
ca_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
# pct_ept_rich =
pct_euholognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "euholognatha"
),
pct_heptageniidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "heptageniidae"
),
pct_hydropsychidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "hydropsychidae"
),
pct_ept = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = c("ephemeroptera",
"plecoptera",
"trichoptera")
),
pct_hydro_ept = pct_ept - pct_hydropsychidae,
############################ CORRECT?
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_trichoptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "trichoptera"
),
pct_non_hydrop_trichoptera = pct_trichoptera - pct_hydropsychidae,
pct_pisciforma = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "pisciforma"
),
pct_systellognatha = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = suborder,
taxon = "systellognatha"
),
rich_burrow = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "burrow"
),
rich_collect = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = c("filter", "gather")
),
rich_filter = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "filter"
),
rich_plecoptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "plecoptera"
),
rich_predator = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = ffg,
high.taxa.col = family,
taxon = "predator"
)
) %>%
select(-pct_hydropsychidae,-pct_ept,-pct_trichoptera)
}
# lnp --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "lnp", "metric"]
lnp_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
#aspt_mod = ################################################################## build
pct_cling = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = habit,
taxon = "cling"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
#pct_ept_rich = ########################################################### build
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_predator = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "predator"
),
pct_pterygota = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = subclass,
taxon = "pterygota"
),
rich_cling = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "cling"
),
rich_ephemeroptera = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = order,
high.taxa.col = family,
taxon = "ephemeroptera"
)
)
}
# mac --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "mac", "metric"]
mac_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
#aspt_mod = ################################################################## build
pct_gastro_oligo = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = class,
taxon = c("gastropoda", "oligochatea")
),
pct_diptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "diptera"
),
gold = 1 - (pct_gastro_oligo + pct_diptera),
pct_arthropoda = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = phylum,
taxon = "arthropda"
),
pct_chironomidae = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = family,
taxon = "chironomidae"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
pct_mod_tol_4_6 = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = tol_val,
taxon = 4:6
),
pct_odonata = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = order,
taxon = "odonata"
),
pct_predator = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "predator"
),
pct_scrape = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "scrape"
),
# pct_urban_intol = taxa_pct(long.df = x, #################### LOOK UP
# unique.id.col = unique_id,
# count.col = reporting_value,
# taxon.col = family,
# taxon = c()),
rich_climb = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = habit,
high.taxa.col = family,
taxon = "climb"
),
rich_tol = taxa_rich(
long.df = x,
unique.id.col = unique_id,
low.taxa.col = tol_val,
high.taxa.col = family,
taxon = 7:10
)
) %>%
select(-pct_gastro_oligo,-pct_diptera)
}
# napu --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "napu", "metric"]
napu_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate(
margalefs = taxa_div(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
low.taxa.col = NULL,
high.taxa.col = family,
job = "margalef"
),
pct_cling = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "cling"
),
pct_collect = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = c("filter", "gather")
),
pct_ephemeroptera = taxa_pct(
long.df = x,
unique.id.col = unique_id,
count.col = reporting_value,
taxon.col = ffg,
taxon = "ephemeroptera"
),
)
}
# nca --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "nca", "metric"]
nca_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# nrv --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "nrv", "metric"]
nrv_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# pied --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "pied", "metric"]
pied_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# sep --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "sep", "metric"]
sep_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# sgv --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "sgv", "metric"]
sgv_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# srv --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "srv", "metric"]
srv_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
# unp --------------------------------------------------------------------
met.thresh.df[met.thresh.df$spatial_resolution == "unp", "metric"]
unp_metrics <- function(x) {
metrics.key <- x %>%
select(unique_id) %>%
distinct()
metrics.key %>%
dplyr::mutate()
}
|
#' @title Title
#'
#' @description Description
#'
#' @param x A number.
#' @param y A number.
#' @return return value here.
#' @details
#' Additional details here
#' @examples
#' example function call here
#' @export
risk_group_changes <- function(dat,at){
#wrapper for various transition functions for social attributes
#-- update generic attribute
if(!is.logical(dat$param$generic_nodal_att_values)){
dat <- social_generic_attribute_transition(dat,at)
}
#-- update agent roles
if(!is.logical(dat$param$role_props) && dat$param$model_sex=="msm"){
tempvals <- dat$attr$role
for( ii in names(dat$param$role_props))
{
index <- which(dat$attr$role == ii & dat$popStatus >= 0)
size <- length(index)
#role_trans_mat must have rownames "I","R","V"
probs <- dat$param$role_trans_mat[ii,]
new_vals <- sample( names(dat$param$role_props),
size = size,
prob = probs,
replace = T)
tempvals[index] <- new_vals
}
dat$attr$role <-tempvals
temp_match<- match(dat$attr$id,dat$attr$id)
#qaqc for now (10/8/15)
if(any(is.na(temp_match))){browser()}
if(!is.null(dat[['nw']])){
network::set.vertex.attribute( x = dat$nw, attr = "role",
value = dat$attr$role[temp_match])
}
# update the version of the attribute in dat$attr as well
dat$attr$role <- dat$attr$role[temp_match]
}
#-- end of role updates --------------------
return(dat)
}
|
/pkg/R/risk_group_changes.R
|
no_license
|
RodrigoAnderle/EvoNetHIV
|
R
| false
| false
| 1,520
|
r
|
#' @title Title
#'
#' @description Description
#'
#' @param x A number.
#' @param y A number.
#' @return return value here.
#' @details
#' Additional details here
#' @examples
#' example function call here
#' @export
risk_group_changes <- function(dat,at){
#wrapper for various transition functions for social attributes
#-- update generic attribute
if(!is.logical(dat$param$generic_nodal_att_values)){
dat <- social_generic_attribute_transition(dat,at)
}
#-- update agent roles
if(!is.logical(dat$param$role_props) && dat$param$model_sex=="msm"){
tempvals <- dat$attr$role
for( ii in names(dat$param$role_props))
{
index <- which(dat$attr$role == ii & dat$popStatus >= 0)
size <- length(index)
#role_trans_mat must have rownames "I","R","V"
probs <- dat$param$role_trans_mat[ii,]
new_vals <- sample( names(dat$param$role_props),
size = size,
prob = probs,
replace = T)
tempvals[index] <- new_vals
}
dat$attr$role <-tempvals
temp_match<- match(dat$attr$id,dat$attr$id)
#qaqc for now (10/8/15)
if(any(is.na(temp_match))){browser()}
if(!is.null(dat[['nw']])){
network::set.vertex.attribute( x = dat$nw, attr = "role",
value = dat$attr$role[temp_match])
}
# update the version of the attribute in dat$attr as well
dat$attr$role <- dat$attr$role[temp_match]
}
#-- end of role updates --------------------
return(dat)
}
|
battles <- read.csv("battles.csv")
deaths <- read.csv("character-deaths.csv")
predictions <- read.csv("character-predictions.csv")
str(battles)
temp <- as.factor(battles$year)
plot(temp)
#maximum battles in year 299, then year 300, then 298
summary(battles$battle_number)
table(battles$battle_number)
table(battles$attacker_king)
library(ggplot2)
ggplot(battles,aes(x = battles$attacker_king)) + geom_bar()+xlab("king")
# highest attacks done by joffrey/tommen baratheon
ggplot(battles,aes(x = battles$defender_king)) + geom_bar()+xlab("king")
summary(battles$defender_king)
# most defends done by robb stark followed by joffrey/tommen baratheon
table(battles$attacker_king,battles$defender_king)
#most fights between Robb stark and joffrey/tommen baratheon
table(battles$attacker_outcome,battles$attacker_king)
#maximum wins are achieved by joffrey/tommen baratheon followed by Robb stark, the most battles are won by baratheons
summary(battles$attacker_1)
table(battles$attacker_king,battles$attacker_1)
# in the fights of baratheon, baratheon being attackers we have lannisters as the their attackers in the fights while in other houses the attackers are mostly
#hence their names themselves indicating the dependency of baratheon on lannisters
table(battles$attacker_king,battles$battle_type)
#Robb stark has taken in highest number of ambush battles followed by tommen baratheon, Baratheon has fought highest number of pitched battles and siege battles
summary(battles$major_death)
summary(battles$major_capture)
table(battles$attacker_king,battles$attacker_size)
table(battles$attacker_outcome,battles$attacker_size)
#This reveals a striking result that the attacking size having army sizes like 100000,21000 have lost in the wars rather than the armies which had less army strength
#won the battles
#After closely analysing the data we come to know that the fight involving 100000 attackers was fought at castle black, defenders having the advantage of the wall
#and height, they won
table(battles$attacker_size,battles$defender_size)
table(battles$attacker_outcome)
battles$attacker_outcome <- as.character(battles$attacker_outcome)
battles$attacker_outcome <- ifelse((battles$attacker_outcome == ""),"loss",battles$attacker_outcome)
battles$attacker_commander
battles$attacker_commander <- as.character(battles$attacker_commander)
battles$attacker_commander <- ifelse((battles$attacker_commander == ""),"no",battles$attacker_commander)
splitdat = do.call("rbind", strsplit(battles$attacker_commander, ","))
splitdat = data.frame(apply(splitdat, 2, as.character))
colnames(splitdat) <- paste("commander", 1:6, sep = "")
splitdat
battles <- cbind(battles,splitdat)
temp <- ifelse(is.na(battles$attacker_size),0,battles$attacker_size)
avg <- mean(temp)
temp1 <- ifelse(is.na(battles$defender_size),0,battles$defender_size)
avg1 <- mean(temp1)
#filling missing values in attack size nad defend size
battles$attacker_size <- ifelse(is.na(battles$attacker_size),avg,battles$attacker_size)
battles$defender_size <- ifelse(is.na(battles$defender_size),avg,battles$defender_size)
cor(battles$defender_size,battles$attacker_size)
#this correlation comes out to be negative which seems to be a bit wierd cause this shows that in the battles, when one of the sides had an increasing army, the other side had decreasing army
#now we can see that there are a lot of categorical variables in this data set and they could be related in a specific fashion, now we will take two variables, i.e. outcome of the battle and
#the region in which battle took place and form a tree of this
library(rpart)
library(rpart.plot)
library(rattle)
library(RColorBrewer)
library(MASS)
install.packages("RColorBrewer")
tree <- rpart(battles$attacker_outcome~battles$region,data = battles,control=rpart.control(minsplit=5, cp=0.001),method = "class")
fancyRpartPlot(tree)
table <- table(battles$region,battles$attacker_outcome)
chisq.test(table)
#the data is very less so you will get a warning message, you can combine two or more regions so that
#the results become more efficient
#Further taking more categorical variables and applying chi-square test of independence
table1 <- table(battles$attacker_king,battles$attacker_outcome)
table1
chisq.test(table1)
#The p values shoe that the outcome of the battle is more dependent on the regions than the king
#The similar analysis could be done on the defender king and the statistical analysis could be done
|
/game of thrones.R
|
no_license
|
srikarth/Game-of-Thrones
|
R
| false
| false
| 4,442
|
r
|
battles <- read.csv("battles.csv")
deaths <- read.csv("character-deaths.csv")
predictions <- read.csv("character-predictions.csv")
str(battles)
temp <- as.factor(battles$year)
plot(temp)
#maximum battles in year 299, then year 300, then 298
summary(battles$battle_number)
table(battles$battle_number)
table(battles$attacker_king)
library(ggplot2)
ggplot(battles,aes(x = battles$attacker_king)) + geom_bar()+xlab("king")
# highest attacks done by joffrey/tommen baratheon
ggplot(battles,aes(x = battles$defender_king)) + geom_bar()+xlab("king")
summary(battles$defender_king)
# most defends done by robb stark followed by joffrey/tommen baratheon
table(battles$attacker_king,battles$defender_king)
#most fights between Robb stark and joffrey/tommen baratheon
table(battles$attacker_outcome,battles$attacker_king)
#maximum wins are achieved by joffrey/tommen baratheon followed by Robb stark, the most battles are won by baratheons
summary(battles$attacker_1)
table(battles$attacker_king,battles$attacker_1)
# in the fights of baratheon, baratheon being attackers we have lannisters as the their attackers in the fights while in other houses the attackers are mostly
#hence their names themselves indicating the dependency of baratheon on lannisters
table(battles$attacker_king,battles$battle_type)
#Robb stark has taken in highest number of ambush battles followed by tommen baratheon, Baratheon has fought highest number of pitched battles and siege battles
summary(battles$major_death)
summary(battles$major_capture)
table(battles$attacker_king,battles$attacker_size)
table(battles$attacker_outcome,battles$attacker_size)
#This reveals a striking result that the attacking size having army sizes like 100000,21000 have lost in the wars rather than the armies which had less army strength
#won the battles
#After closely analysing the data we come to know that the fight involving 100000 attackers was fought at castle black, defenders having the advantage of the wall
#and height, they won
table(battles$attacker_size,battles$defender_size)
table(battles$attacker_outcome)
battles$attacker_outcome <- as.character(battles$attacker_outcome)
battles$attacker_outcome <- ifelse((battles$attacker_outcome == ""),"loss",battles$attacker_outcome)
battles$attacker_commander
battles$attacker_commander <- as.character(battles$attacker_commander)
battles$attacker_commander <- ifelse((battles$attacker_commander == ""),"no",battles$attacker_commander)
splitdat = do.call("rbind", strsplit(battles$attacker_commander, ","))
splitdat = data.frame(apply(splitdat, 2, as.character))
colnames(splitdat) <- paste("commander", 1:6, sep = "")
splitdat
battles <- cbind(battles,splitdat)
temp <- ifelse(is.na(battles$attacker_size),0,battles$attacker_size)
avg <- mean(temp)
temp1 <- ifelse(is.na(battles$defender_size),0,battles$defender_size)
avg1 <- mean(temp1)
#filling missing values in attack size nad defend size
battles$attacker_size <- ifelse(is.na(battles$attacker_size),avg,battles$attacker_size)
battles$defender_size <- ifelse(is.na(battles$defender_size),avg,battles$defender_size)
cor(battles$defender_size,battles$attacker_size)
#this correlation comes out to be negative which seems to be a bit wierd cause this shows that in the battles, when one of the sides had an increasing army, the other side had decreasing army
#now we can see that there are a lot of categorical variables in this data set and they could be related in a specific fashion, now we will take two variables, i.e. outcome of the battle and
#the region in which battle took place and form a tree of this
library(rpart)
library(rpart.plot)
library(rattle)
library(RColorBrewer)
library(MASS)
install.packages("RColorBrewer")
tree <- rpart(battles$attacker_outcome~battles$region,data = battles,control=rpart.control(minsplit=5, cp=0.001),method = "class")
fancyRpartPlot(tree)
table <- table(battles$region,battles$attacker_outcome)
chisq.test(table)
#the data is very less so you will get a warning message, you can combine two or more regions so that
#the results become more efficient
#Further taking more categorical variables and applying chi-square test of independence
table1 <- table(battles$attacker_king,battles$attacker_outcome)
table1
chisq.test(table1)
#The p values shoe that the outcome of the battle is more dependent on the regions than the king
#The similar analysis could be done on the defender king and the statistical analysis could be done
|
#' Fit the probabilistic dropout parameters
#'
#' The method infers the position and scale of the dropout sigmoids, the
#' location prior of the means and the prior for the variance. In addition it
#' estimates some feature parameters (mean, uncertainty of mean and variance
#' for each protein and condition).
#'
#' @param X the numerical data where each column is one sample and each row
#' is one protein. Missing values are coded as \code{NA}.
#' @param experimental_design a vector that assignes each sample to one condition.
#' It has the same length as the number of columns in \code{X}. It can either be
#' a factor, a character or a numeric vector. Each unique element is one condition.
#' If \code{X} is a \code{SummarizedExperiment} or an \code{MSnSet} object,
#' \code{experimental_design} can also be the name of a column in the
#' \code{colData(X)} or \code{pData(X)}, respectively.
#' @param dropout_curve_calc string that specifies how the dropout curves are
#' estimated. There are three different modes. "sample": number of curves=
#' number of samples, "global": number of curves=1, "global_scale": estimate
#' only a single scale of the sigmoid, but estimate the position per sample.
#' Default: "sample".
#' @param frac_subsample number between 0 and 1. Often it is not necessary to
#' consider each protein, but the computation can be significantly sped up
#' by only considering a subset of the subsets. Default: 1.0.
#' @param n_subsample number between 1 and \code{nrow(X)}. Alternative way to
#' specify how many proteins are considered for estimating the hyper-parameters.
#' Default: \code{nrow(X) * frac_subsample}.
#' @param max_iter integer larger than 1. How many iterations are run at most
#' trying to reach convergence. Default: 10.
#' @param epsilon number larger than 0. How big is the maximum remaining error
#' for the algorithm to be considered converged. Default: 10^-3
#' @param verbose boolean. Specify how much extra information is printed
#' while the algorithm is running. Default: \code{FALSE}.
#'
#' @return a list containing the infered parameters. The list is tagged
#' with the class "prodd_parameters" for simpler handling in downstream
#' methods
#'
#' @export
fit_parameters <- function(X, experimental_design,
dropout_curve_calc=c("sample", "global_scale", "global"),
frac_subsample=1.0, n_subsample=round(nrow(X) * frac_subsample),
max_iter=10, epsilon=1e-3, verbose=FALSE){
dropout_curve_calc <- match.arg(dropout_curve_calc, c("sample", "global_scale", "global"))
experimental_design_fct <- as.factor(experimental_design)
experimental_design <- as.numeric(experimental_design_fct)
N_cond <- length(unique(experimental_design))
if(n_subsample >= nrow(X)){
X_bckp <- X
sel <- seq_len(nrow(X))
}else if(n_subsample > 0 && n_subsample < nrow(X)){
X_bckp <- X
sel <- sample(seq_len(nrow(X_bckp)), n_subsample)
X <- X_bckp[sel, ,drop=FALSE]
}else{
stop(paste0("Illegal argument n_subsample it must be larger than 0"))
}
#Initialize the parameters
mup <- mply_dbl(seq_len(nrow(X)), ncol=N_cond, function(idx){
vapply(seq_len(N_cond), function(cond){
mean(X[idx, which(experimental_design == cond)], na.rm=TRUE)
}, FUN.VALUE=0.0)
})
frac_mis <- sum(is.na(X)) / prod(dim(X))
mup[is.na(mup)] <- quantile(mup, 0.5 * frac_mis, na.rm=TRUE, names=FALSE)
mu0 <- mean(mup, na.rm=TRUE)
# Estimate variances
sigma2p <- apply(X, 1, function(row){
res <- sapply(seq_len(N_cond), function(cond){
x <- row[which(experimental_design == cond)]
nobs <- sum(! is.na(x))
if(nobs > 1){
c((nobs-1) * var(x, na.rm=TRUE), nobs-1)
}else{
c(NA, NA)
}
})
sum(res[1, ], na.rm=TRUE) / sum(res[2, ], na.rm=TRUE)
})
sigma20 <- mean(sigma2p, na.rm=TRUE)
sigma2p[is.na(sigma2p)] <- sigma20
sigma2_unreg <- sigma2p
# Sigmoid parameters
zeta <- rep(- sqrt(sigma20), ncol(X))
rho <- sapply(seq_len(ncol(X)), function(colidx){
sel <- which(is.na(c(X[, colidx])))
optimize(function(rho){
sum(invprobit(X[, colidx], rho, zeta[colidx], log=TRUE, oneminus = TRUE), na.rm=TRUE) +
sum(invprobit(mup[sel, experimental_design[colidx]], rho,
zeta[colidx] * sqrt(1 + sigma2p[sel] / zeta[colidx]^2), log=TRUE))
}, lower=-100, upper=100, maximum=TRUE)$maximum
})
# Variance prior
nu <- 3
eta <- sigma20 + 0.1
last_round_params <- list(eta,nu,mu0,sigma20,rho,zeta)
converged <- FALSE
iter <- 1
while(! converged && iter < max_iter){
if(verbose) message(paste0("Starting iter ", iter))
# Estimate dropout sigmoid
sigmoid_est <- if(dropout_curve_calc == "global") {
fit_global_dropout_curves(X, mup, sigma2p, experimental_design,
prev_zeta = zeta, prev_rho=rho)
}else if(dropout_curve_calc == "sample"){
fit_sample_dropout_curves(X, mup, sigma2p, experimental_design,
prev_zeta = zeta, prev_rho=rho)
}else if(dropout_curve_calc == "global_scale"){
fit_global_scale_dropout_curves(X, mup, sigma2p, experimental_design,
prev_zeta = zeta, prev_rho=rho)
}
rho <- sigmoid_est$rho
zeta <- sigmoid_est$zeta
# Make a good estimate for each mean
sigma2p <- fit_feature_variances(X, mup, rho, zeta, nu, eta, experimental_design)
mu_vars <- fit_feature_mean_uncertainties(X, rho, zeta, nu, eta, mu0,
sigma20, experimental_design)
mup <- fit_feature_means(X, sigma2p, mu_vars, rho, zeta, nu, eta, mu0,
sigma20, experimental_design)
# Fit the variance prior
var_est <- fit_variance_prior(X, rho, zeta, experimental_design)
nu <- var_est$df_prior
eta <- var_est$var_prior
# Fit the location prior
loc_est <- fit_location_prior(X, mup, zeta, rho, experimental_design)
mu0 <- loc_est$mu0
sigma20 <- loc_est$sigma20
if(verbose){
message(paste0("eta0 estimate: ", round(eta, 3)))
message(paste0("nu0 estimate: ", round(nu, 3)))
message(paste0("mu0 estimate: ", round(mu0, 3)))
message(paste0("sigma20 estimate: ", round(sigma20, 3)))
message(paste0("rho estimate: ", paste0(round(rho, 3), collapse = ",")))
message(paste0("zeta estimate: ", paste0(round(zeta, 3), collapse = ",")))
}
error <- sum(mapply(function(new, old){sum(new - old)/length(new)},
list(eta,nu,mu0,sigma20,rho,zeta), last_round_params )^2)
if(verbose) message(paste0("Error: ", error))
if(error < epsilon) {
if(verbose) message("converged!")
converged <- TRUE
}
last_round_params <- list(eta,nu,mu0,sigma20,rho,zeta)
iter <- iter + 1
}
names(last_round_params) <- c("eta", "nu", "mu0", "sigma20", "rho", "zeta")
names(last_round_params$rho) <- colnames(X)
names(last_round_params$zeta) <- colnames(X)
feature_params <- list(
mup=matrix(NA, nrow=nrow(X_bckp), ncol=N_cond),
sigma2p=rep(NA, times=nrow(X_bckp)),
sigma2mup=matrix(NA, nrow=nrow(X_bckp), ncol=N_cond)
)
feature_params$mup[sel, ] <- mup
feature_params$sigma2p[sel] <- sigma2p
feature_params$sigma2mup[sel, ] <- mu_vars
colnames(feature_params$mup) <- levels(experimental_design_fct)
colnames(feature_params$sigma2mup) <- levels(experimental_design_fct)
rownames(feature_params$mup) <- rownames(X_bckp)
rownames(feature_params$sigma2mup) <- rownames(X_bckp)
antisel <- setdiff(seq_len(nrow(X_bckp)), sel)
if(length(antisel) > 0){
if(verbose) message(paste0("Predicting features which were not in the subsample: ",
length(antisel), " elements."))
add_feats <- predict_feature_parameters(X_bckp[antisel, ], experimental_design_fct,
last_round_params, verbose=verbose)
feature_params$mup[antisel, ] <- add_feats$mup
feature_params$sigma2p[antisel] <- add_feats$sigma2p
feature_params$sigma2mup[antisel, ] <- add_feats$sigma2mup
}
ret <- list(hyper_params = last_round_params,
feature_params = feature_params,
experimental_design=experimental_design_fct,
error=error, converged=converged)
class(ret) <- "prodd_parameters"
ret
}
setGeneric("fit_parameters")
#' @describeIn fit_parameters S4 method of \code{fit_parameters} for
#' \code{SummarizedExperiment}
setMethod("fit_parameters",
c(X = "SummarizedExperiment"),
function(X, experimental_design,
dropout_curve_calc=c("sample", "global_scale", "global"),
frac_subsample=1.0, n_subsample=round(nrow(X) * frac_subsample),
max_iter=10, epsilon=1e-3, verbose=FALSE){
# First extract the experimental_design column from the colData
if(length(experimental_design) == 1){
if(! experimental_design %in% colnames(SummarizedExperiment::colData(X))) {
stop(paste0("'experimental_design' must reference a ",
"column in colData(X). Ie. one of: ",
paste0(colnames(SummarizedExperiment::colData(X)), collapse=", ")))
}
experimental_design <- SummarizedExperiment::colData(X)[, experimental_design, drop=TRUE]
}
params <- fit_parameters(SummarizedExperiment::assay(X), experimental_design,
dropout_curve_calc, frac_subsample, n_subsample,
max_iter, epsilon, verbose)
params
})
#' @describeIn fit_parameters S4 method of \code{fit_parameters} for
#' \code{MSnSet}
setMethod("fit_parameters",
c(X = "MSnSet"),
function(X, experimental_design,
dropout_curve_calc=c("sample", "global_scale", "global"),
frac_subsample=1.0, n_subsample=round(nrow(X) * frac_subsample),
max_iter=10, epsilon=1e-3, verbose=FALSE){
# First extract the experimental_design column from the pData
if(length(experimental_design) == 1){
if(! experimental_design %in% colnames(Biobase::pData(X))) {
stop(paste0("'experimental_design' must reference a ",
"column in pData(X). Ie. one of: ",
paste0(colnames(Biobase::pData(X)), collapse=", ")))
}
experimental_design <- Biobase::pData(X)[, experimental_design, drop=TRUE]
}
params <- fit_parameters(Biobase::exprs(X), experimental_design,
dropout_curve_calc, frac_subsample, n_subsample,
max_iter, epsilon, verbose)
params
})
#' Fit a Gaussian location prior over all samples
#'
#' The function takes the regularized feature means. The global mu0 is the
#' mean of the regularized feature means. It then calculates the unregularized
#' feature means right of the global mean (so that missing values are less
#' problematic). The global variance estimate is the variance of those
#' unregularized values to the global mean.
#'
#' @return list with elements mu0 and sigma20
#' @keywords internal
fit_location_prior <- function(X, mup, zeta, rho, experimental_design){
mu0 <- mean(mup, na.rm=TRUE)
mu_unreg <- fit_unregularized_feature_means(X, mup, mu0, zeta, rho, experimental_design)
sigma20 <- sum((mu_unreg[! is.na(mu_unreg)] - mu0)^2/sum(! is.na(mu_unreg)))
list(mu0=mu0, sigma20=sigma20)
}
#' Fit a inverse Chi-squared variance prior
#'
#' Run maximum likelihood estimate on the density of the F distribution with
#' the unregularized variance estimates.
#' @keywords internal
fit_variance_prior <- function(X, rho, zeta, experimental_design){
DF_eff <- calc_df_eff(X, experimental_design)
sigma2_unreg <- fit_unregularized_feature_variances(X, rho, zeta, experimental_design)
var_est <- optim(par=c(eta=1, nu=1), function(par){
if(par[1] < 0 || par[2] < 0 ) return(Inf)
- sum(sapply(seq_len(nrow(X))[DF_eff >= 1 & ! is.na(sigma2_unreg)], function(idx){
df(sigma2_unreg[idx]/par[1], df1=DF_eff[idx], df2=par[2], log=TRUE) - log(par[1])
}))
})
names(var_est$par) <- NULL
list(var_prior=var_est$par[1], df_prior=var_est$par[2])
}
|
/R/fit_hyperparameters.R
|
no_license
|
const-ae/proDD
|
R
| false
| false
| 13,152
|
r
|
#' Fit the probabilistic dropout parameters
#'
#' The method infers the position and scale of the dropout sigmoids, the
#' location prior of the means and the prior for the variance. In addition it
#' estimates some feature parameters (mean, uncertainty of mean and variance
#' for each protein and condition).
#'
#' @param X the numerical data where each column is one sample and each row
#' is one protein. Missing values are coded as \code{NA}.
#' @param experimental_design a vector that assignes each sample to one condition.
#' It has the same length as the number of columns in \code{X}. It can either be
#' a factor, a character or a numeric vector. Each unique element is one condition.
#' If \code{X} is a \code{SummarizedExperiment} or an \code{MSnSet} object,
#' \code{experimental_design} can also be the name of a column in the
#' \code{colData(X)} or \code{pData(X)}, respectively.
#' @param dropout_curve_calc string that specifies how the dropout curves are
#' estimated. There are three different modes. "sample": number of curves=
#' number of samples, "global": number of curves=1, "global_scale": estimate
#' only a single scale of the sigmoid, but estimate the position per sample.
#' Default: "sample".
#' @param frac_subsample number between 0 and 1. Often it is not necessary to
#' consider each protein, but the computation can be significantly sped up
#' by only considering a subset of the subsets. Default: 1.0.
#' @param n_subsample number between 1 and \code{nrow(X)}. Alternative way to
#' specify how many proteins are considered for estimating the hyper-parameters.
#' Default: \code{nrow(X) * frac_subsample}.
#' @param max_iter integer larger than 1. How many iterations are run at most
#' trying to reach convergence. Default: 10.
#' @param epsilon number larger than 0. How big is the maximum remaining error
#' for the algorithm to be considered converged. Default: 10^-3
#' @param verbose boolean. Specify how much extra information is printed
#' while the algorithm is running. Default: \code{FALSE}.
#'
#' @return a list containing the infered parameters. The list is tagged
#' with the class "prodd_parameters" for simpler handling in downstream
#' methods
#'
#' @export
fit_parameters <- function(X, experimental_design,
dropout_curve_calc=c("sample", "global_scale", "global"),
frac_subsample=1.0, n_subsample=round(nrow(X) * frac_subsample),
max_iter=10, epsilon=1e-3, verbose=FALSE){
dropout_curve_calc <- match.arg(dropout_curve_calc, c("sample", "global_scale", "global"))
experimental_design_fct <- as.factor(experimental_design)
experimental_design <- as.numeric(experimental_design_fct)
N_cond <- length(unique(experimental_design))
if(n_subsample >= nrow(X)){
X_bckp <- X
sel <- seq_len(nrow(X))
}else if(n_subsample > 0 && n_subsample < nrow(X)){
X_bckp <- X
sel <- sample(seq_len(nrow(X_bckp)), n_subsample)
X <- X_bckp[sel, ,drop=FALSE]
}else{
stop(paste0("Illegal argument n_subsample it must be larger than 0"))
}
#Initialize the parameters
mup <- mply_dbl(seq_len(nrow(X)), ncol=N_cond, function(idx){
vapply(seq_len(N_cond), function(cond){
mean(X[idx, which(experimental_design == cond)], na.rm=TRUE)
}, FUN.VALUE=0.0)
})
frac_mis <- sum(is.na(X)) / prod(dim(X))
mup[is.na(mup)] <- quantile(mup, 0.5 * frac_mis, na.rm=TRUE, names=FALSE)
mu0 <- mean(mup, na.rm=TRUE)
# Estimate variances
sigma2p <- apply(X, 1, function(row){
res <- sapply(seq_len(N_cond), function(cond){
x <- row[which(experimental_design == cond)]
nobs <- sum(! is.na(x))
if(nobs > 1){
c((nobs-1) * var(x, na.rm=TRUE), nobs-1)
}else{
c(NA, NA)
}
})
sum(res[1, ], na.rm=TRUE) / sum(res[2, ], na.rm=TRUE)
})
sigma20 <- mean(sigma2p, na.rm=TRUE)
sigma2p[is.na(sigma2p)] <- sigma20
sigma2_unreg <- sigma2p
# Sigmoid parameters
zeta <- rep(- sqrt(sigma20), ncol(X))
rho <- sapply(seq_len(ncol(X)), function(colidx){
sel <- which(is.na(c(X[, colidx])))
optimize(function(rho){
sum(invprobit(X[, colidx], rho, zeta[colidx], log=TRUE, oneminus = TRUE), na.rm=TRUE) +
sum(invprobit(mup[sel, experimental_design[colidx]], rho,
zeta[colidx] * sqrt(1 + sigma2p[sel] / zeta[colidx]^2), log=TRUE))
}, lower=-100, upper=100, maximum=TRUE)$maximum
})
# Variance prior
nu <- 3
eta <- sigma20 + 0.1
last_round_params <- list(eta,nu,mu0,sigma20,rho,zeta)
converged <- FALSE
iter <- 1
while(! converged && iter < max_iter){
if(verbose) message(paste0("Starting iter ", iter))
# Estimate dropout sigmoid
sigmoid_est <- if(dropout_curve_calc == "global") {
fit_global_dropout_curves(X, mup, sigma2p, experimental_design,
prev_zeta = zeta, prev_rho=rho)
}else if(dropout_curve_calc == "sample"){
fit_sample_dropout_curves(X, mup, sigma2p, experimental_design,
prev_zeta = zeta, prev_rho=rho)
}else if(dropout_curve_calc == "global_scale"){
fit_global_scale_dropout_curves(X, mup, sigma2p, experimental_design,
prev_zeta = zeta, prev_rho=rho)
}
rho <- sigmoid_est$rho
zeta <- sigmoid_est$zeta
# Make a good estimate for each mean
sigma2p <- fit_feature_variances(X, mup, rho, zeta, nu, eta, experimental_design)
mu_vars <- fit_feature_mean_uncertainties(X, rho, zeta, nu, eta, mu0,
sigma20, experimental_design)
mup <- fit_feature_means(X, sigma2p, mu_vars, rho, zeta, nu, eta, mu0,
sigma20, experimental_design)
# Fit the variance prior
var_est <- fit_variance_prior(X, rho, zeta, experimental_design)
nu <- var_est$df_prior
eta <- var_est$var_prior
# Fit the location prior
loc_est <- fit_location_prior(X, mup, zeta, rho, experimental_design)
mu0 <- loc_est$mu0
sigma20 <- loc_est$sigma20
if(verbose){
message(paste0("eta0 estimate: ", round(eta, 3)))
message(paste0("nu0 estimate: ", round(nu, 3)))
message(paste0("mu0 estimate: ", round(mu0, 3)))
message(paste0("sigma20 estimate: ", round(sigma20, 3)))
message(paste0("rho estimate: ", paste0(round(rho, 3), collapse = ",")))
message(paste0("zeta estimate: ", paste0(round(zeta, 3), collapse = ",")))
}
error <- sum(mapply(function(new, old){sum(new - old)/length(new)},
list(eta,nu,mu0,sigma20,rho,zeta), last_round_params )^2)
if(verbose) message(paste0("Error: ", error))
if(error < epsilon) {
if(verbose) message("converged!")
converged <- TRUE
}
last_round_params <- list(eta,nu,mu0,sigma20,rho,zeta)
iter <- iter + 1
}
names(last_round_params) <- c("eta", "nu", "mu0", "sigma20", "rho", "zeta")
names(last_round_params$rho) <- colnames(X)
names(last_round_params$zeta) <- colnames(X)
feature_params <- list(
mup=matrix(NA, nrow=nrow(X_bckp), ncol=N_cond),
sigma2p=rep(NA, times=nrow(X_bckp)),
sigma2mup=matrix(NA, nrow=nrow(X_bckp), ncol=N_cond)
)
feature_params$mup[sel, ] <- mup
feature_params$sigma2p[sel] <- sigma2p
feature_params$sigma2mup[sel, ] <- mu_vars
colnames(feature_params$mup) <- levels(experimental_design_fct)
colnames(feature_params$sigma2mup) <- levels(experimental_design_fct)
rownames(feature_params$mup) <- rownames(X_bckp)
rownames(feature_params$sigma2mup) <- rownames(X_bckp)
antisel <- setdiff(seq_len(nrow(X_bckp)), sel)
if(length(antisel) > 0){
if(verbose) message(paste0("Predicting features which were not in the subsample: ",
length(antisel), " elements."))
add_feats <- predict_feature_parameters(X_bckp[antisel, ], experimental_design_fct,
last_round_params, verbose=verbose)
feature_params$mup[antisel, ] <- add_feats$mup
feature_params$sigma2p[antisel] <- add_feats$sigma2p
feature_params$sigma2mup[antisel, ] <- add_feats$sigma2mup
}
ret <- list(hyper_params = last_round_params,
feature_params = feature_params,
experimental_design=experimental_design_fct,
error=error, converged=converged)
class(ret) <- "prodd_parameters"
ret
}
setGeneric("fit_parameters")
#' @describeIn fit_parameters S4 method of \code{fit_parameters} for
#' \code{SummarizedExperiment}
setMethod("fit_parameters",
c(X = "SummarizedExperiment"),
function(X, experimental_design,
dropout_curve_calc=c("sample", "global_scale", "global"),
frac_subsample=1.0, n_subsample=round(nrow(X) * frac_subsample),
max_iter=10, epsilon=1e-3, verbose=FALSE){
# First extract the experimental_design column from the colData
if(length(experimental_design) == 1){
if(! experimental_design %in% colnames(SummarizedExperiment::colData(X))) {
stop(paste0("'experimental_design' must reference a ",
"column in colData(X). Ie. one of: ",
paste0(colnames(SummarizedExperiment::colData(X)), collapse=", ")))
}
experimental_design <- SummarizedExperiment::colData(X)[, experimental_design, drop=TRUE]
}
params <- fit_parameters(SummarizedExperiment::assay(X), experimental_design,
dropout_curve_calc, frac_subsample, n_subsample,
max_iter, epsilon, verbose)
params
})
#' @describeIn fit_parameters S4 method of \code{fit_parameters} for
#' \code{MSnSet}
setMethod("fit_parameters",
c(X = "MSnSet"),
function(X, experimental_design,
dropout_curve_calc=c("sample", "global_scale", "global"),
frac_subsample=1.0, n_subsample=round(nrow(X) * frac_subsample),
max_iter=10, epsilon=1e-3, verbose=FALSE){
# First extract the experimental_design column from the pData
if(length(experimental_design) == 1){
if(! experimental_design %in% colnames(Biobase::pData(X))) {
stop(paste0("'experimental_design' must reference a ",
"column in pData(X). Ie. one of: ",
paste0(colnames(Biobase::pData(X)), collapse=", ")))
}
experimental_design <- Biobase::pData(X)[, experimental_design, drop=TRUE]
}
params <- fit_parameters(Biobase::exprs(X), experimental_design,
dropout_curve_calc, frac_subsample, n_subsample,
max_iter, epsilon, verbose)
params
})
#' Fit a Gaussian location prior over all samples
#'
#' The function takes the regularized feature means. The global mu0 is the
#' mean of the regularized feature means. It then calculates the unregularized
#' feature means right of the global mean (so that missing values are less
#' problematic). The global variance estimate is the variance of those
#' unregularized values to the global mean.
#'
#' @return list with elements mu0 and sigma20
#' @keywords internal
fit_location_prior <- function(X, mup, zeta, rho, experimental_design){
mu0 <- mean(mup, na.rm=TRUE)
mu_unreg <- fit_unregularized_feature_means(X, mup, mu0, zeta, rho, experimental_design)
sigma20 <- sum((mu_unreg[! is.na(mu_unreg)] - mu0)^2/sum(! is.na(mu_unreg)))
list(mu0=mu0, sigma20=sigma20)
}
#' Fit a inverse Chi-squared variance prior
#'
#' Run maximum likelihood estimate on the density of the F distribution with
#' the unregularized variance estimates.
#' @keywords internal
fit_variance_prior <- function(X, rho, zeta, experimental_design){
DF_eff <- calc_df_eff(X, experimental_design)
sigma2_unreg <- fit_unregularized_feature_variances(X, rho, zeta, experimental_design)
var_est <- optim(par=c(eta=1, nu=1), function(par){
if(par[1] < 0 || par[2] < 0 ) return(Inf)
- sum(sapply(seq_len(nrow(X))[DF_eff >= 1 & ! is.na(sigma2_unreg)], function(idx){
df(sigma2_unreg[idx]/par[1], df1=DF_eff[idx], df2=par[2], log=TRUE) - log(par[1])
}))
})
names(var_est$par) <- NULL
list(var_prior=var_est$par[1], df_prior=var_est$par[2])
}
|
meshRows_hda <-
function(df1, df2) {
rn <- rownames(df1)[{rownames(df1) %in% rownames(df2)}];
ndf1 <- df1[rn, ];
ndf2 <- df2[rn, ];
return(list(ndf1, ndf2))}
|
/R/meshRows_hda.R
|
no_license
|
chronchi/simpleTTMap
|
R
| false
| false
| 174
|
r
|
meshRows_hda <-
function(df1, df2) {
rn <- rownames(df1)[{rownames(df1) %in% rownames(df2)}];
ndf1 <- df1[rn, ];
ndf2 <- df2[rn, ];
return(list(ndf1, ndf2))}
|
#' Trojkat
#'
#' @description funkcja tworzaca obiekt jakim jest trojkat na podstawie
#' odpowiednich parametrow - wspolrzednych.
#'
#' @param x1 wspolrzedna pierwszego punktu na osi x
#' @param x2 wspolrzedna drugiego punktu na osi x
#' @param x3 wspolrzedna trzeciego punktu na osi x
#' @param y1 wspolrzedna pierwszego punktu na osi y
#' @param y2 wspolrzedna drugiego punktu na osi y
#' @param y3 wspolrzedna trzeciego punktu na osi y
#'
#' @return obiekt o klasie "trojkat"
#' @export
#'
#' @examples
#' trojkat(log(10), 2, 3, 100, 50, 12)
#'
#' super_trojkat = trojkat(1, 4, 12, 18, 1, 7)
#'
#' trojkat(log10(10), pi, 12^2, sqrt(7), 5, 94)
trojkat = function(x1, x2, x3, y1, y2, y3){
values = c(x1, x2, x3, y1, y2, y3)
if (!(is.numeric(values))){
stop("Błąd! Upewnij się, czy wszystkie argumenty są typu numerycznego")
}
if (!all(c(length(x1), length(x2), length(x3),
length(y1), length(y2), length(y3)) == 1)){
stop("Każdy z argumentów może przyjmować tylko jedną wartość")
}
if (values[c(1,4)] == values[c(2,5)] || values[c(1,4)] == values[c(3,6)]
|| values[c(2,5)] == values[c(3,6)]){
stop("Punkty muszą być w różnych miejscach.")
}
x = matrix(values, ncol = 2, dimnames = list(c("a", "b", "c"), c("x","y")))
structure(x, class = "trojkat")
}
|
/R/trojkat.R
|
no_license
|
bartlomiejtyrcha/mathobjects
|
R
| false
| false
| 1,317
|
r
|
#' Trojkat
#'
#' @description funkcja tworzaca obiekt jakim jest trojkat na podstawie
#' odpowiednich parametrow - wspolrzednych.
#'
#' @param x1 wspolrzedna pierwszego punktu na osi x
#' @param x2 wspolrzedna drugiego punktu na osi x
#' @param x3 wspolrzedna trzeciego punktu na osi x
#' @param y1 wspolrzedna pierwszego punktu na osi y
#' @param y2 wspolrzedna drugiego punktu na osi y
#' @param y3 wspolrzedna trzeciego punktu na osi y
#'
#' @return obiekt o klasie "trojkat"
#' @export
#'
#' @examples
#' trojkat(log(10), 2, 3, 100, 50, 12)
#'
#' super_trojkat = trojkat(1, 4, 12, 18, 1, 7)
#'
#' trojkat(log10(10), pi, 12^2, sqrt(7), 5, 94)
trojkat = function(x1, x2, x3, y1, y2, y3){
values = c(x1, x2, x3, y1, y2, y3)
if (!(is.numeric(values))){
stop("Błąd! Upewnij się, czy wszystkie argumenty są typu numerycznego")
}
if (!all(c(length(x1), length(x2), length(x3),
length(y1), length(y2), length(y3)) == 1)){
stop("Każdy z argumentów może przyjmować tylko jedną wartość")
}
if (values[c(1,4)] == values[c(2,5)] || values[c(1,4)] == values[c(3,6)]
|| values[c(2,5)] == values[c(3,6)]){
stop("Punkty muszą być w różnych miejscach.")
}
x = matrix(values, ncol = 2, dimnames = list(c("a", "b", "c"), c("x","y")))
structure(x, class = "trojkat")
}
|
# ----------------------------------------
# Temporal Scaling Analyses -- Create baseline growing season model
# Non-linear driver effects through time
# Christy Rollinson, crollinson@gmail.com
# Date Created: 10 July 2015
# ----------------------------------------
# -------------------------
# Objectives & Overview
# -------------------------
# Driving Questions: What is the relative control of different drivers within each model?
# Rationale: Not all models use all inputs, and many drivers are correlated, so we need to
# see if the temperature pattern is really a radiation pattern, etc.
# -------------------------
#
# -------------------------
# Data/Results Generation:
# -------------------------
# (Fit GAMM per site per m.name)
# 1) Temporal Grain (Resolution)
# -- Fit GAMM over constant wind.gsow with different degrees of smoothing (1 yr - 250 yr)
# -------------------------
#
# -------------------------
# Interpretation Analyses:
# -------------------------
# 1) Space-Time Comparison
# -- Hypothesis: Driver responses across sites within a m.name converge at coarser temporal grains
# and larger extents because the models have time to adjust and seek equilibrium.
#
# -- Analysis: Use the posterior CIs for each smoothing term to see if the driver curves for sites
# within a m.name are statstically different at different sites at different scales (or
# alternatively if there are statistical differences in [parts of] the curves between
# scales)
#
#
# 2) Multi-Model Driver Comparison
# -- Hypothesis: Because models were built & parameterized to perform well in the modern era, there
# will be greater agreement of the direction & primary driver of change in the more recent time
# periods than over the full extent of the PalEON runs.
# -- Hypothesis about temporal grain?
#
# -- Analysis: For each given scale, compare the m.name response curves for each driver. Determine
# which drivers are most similar/variable among models and at what scales? Are there
# particular ranges of each driver response where models responses are most similar/different?
# -------------------------
# ----------------------------------------
# ----------------------------------------
# Load Libaries
# ----------------------------------------
library(parallel)
library(mgcv)
# library(ncdf4)
# library(lme4)
# library(R2jags)
library(ggplot2); library(grid)
library(car)
# library(zoo)
# library(mvtnorm)
# library(MCMCpack)
# ----------------------------------------
# ----------------------------------------
# Define constants
# ----------------------------------------
sec2yr <- 1*60*60*24*365
# ----------------------------------------
# ----------------------------------------
# Set Directories
# ----------------------------------------
# setwd("~/Desktop/Dropbox/PalEON CR/PalEON_MIP_Site/Analyses/Temporal-Scaling")
setwd("..")
dat.base="Data/gamms"
fig.base="Figures/gamms"
# Making sure the appropriate file paths exist
if(!dir.exists(dat.base)) dir.create(dat.base)
if(!dir.exists(fig.base)) dir.create(fig.base)
# Setting the data & figure directories
fig.dir <- file.path(fig.base, "Big4_AGB_GS_lag1_byResolution")
dat.dir <- file.path(dat.base, "Big4_AGB_GS_lag1_byResolution")
# Make sure the appropriate file paths are in place
if(!dir.exists(dat.dir)) dir.create(dat.dir)
if(!dir.exists(fig.dir)) dir.create(fig.dir)
# ----------------------------------------
# ----------------------------------------
# Load data files & function scripts
# ----------------------------------------
# Ecosys file = organized, post-processed m.name outputs
# generated with 1_generate_ecosys.R
load(file.path("Data", "EcosysData_Raw.Rdata"))
summary(ecosys)
model.colors
source('R/0_calculate.sensitivity_4drivers_lag1.R', chdir = TRUE)
# Read in model color scheme
model.colors
# ----------------------------------------
# -------------------------------------------------
# Settings for the rest of this script
# -------------------------------------------------
# Get rid of CLM-BGC because its actual drivers are messed up
ecosys <- ecosys[!ecosys$Model=="clm.bgc",]
# Setting up a loop for 1 m.name, 1 temporal scale
sites <- unique(ecosys$Site)
model.name <- unique(ecosys$Model)
model.order <- unique(ecosys$Model.Order)
resolutions <- c("t.001", "t.010", "t.050", "t.100")
response.all <- c("NPP", "AGB.diff", "NEE")
# predictors.all <- c("tair", "precipf", "swdown", "lwdown", "psurf", "qair", "wind", "CO2")
predictors.all <- c("tair", "precipf", "swdown", "CO2")
predictor.suffix <- c(".gs")
k=4
y.lag=5
# r=1
# -------------------------------------------------
# -------------------------------------------------
# Set up the appropriate data for each model into a list
# -------------------------------------------------
# for(y in 1:length(response.all)){
y=2
response <- response.all[y]
print("-------------------------------------")
print("-------------------------------------")
print(paste0("------ Processing Var: ", response, " ------"))
# M1 <- 1:length(model.name)
# M2 <- which(!model.name=="jules.stat")
#if(# response=="AGB.diff") models <- which(!model.name=="jules.stat") else models <- 1:length(model.name)
for(m in 1:length(model.name)){
paleon.models <- list()
m.name <- model.name[m]
m.order <- model.order[m]
print("-------------------------------------")
print(paste0("------ Processing Model: ", m.order, " ------"))
# Note: Here we're renaming things that had the suffix to just be generalized tair, etc
dat.mod <- ecosys[ecosys$Model==m.name, c("Model", "Updated", "Model.Order", "Site", "Year", response, paste0(predictors.all, predictor.suffix))]
names(dat.mod)[(ncol(dat.mod)-length(predictors.all)+1):ncol(dat.mod)] <- predictors.all
if(!max(dat.mod[,response], na.rm=T)>0) next # If a variable is missing, just skip over this model for now
for(s in sites){
for(y in (min(dat.mod$Year)+y.lag):max(dat.mod$Year)){
dat.mod[dat.mod$Site==s & dat.mod$Year==y,"Y.lag"] <- mean(dat.mod[dat.mod$Site==s & dat.mod$Year>=(y-y.lag) & dat.mod$Year<y,response], na.rm=T)
}
}
for(r in 1:length(resolutions)){ # Loop through different resolutions
# Figure out which years to take:
# Note: working backwards to help make sure we get modern end of the CO2.yr & temperature distributions
run.end <- ifelse(substr(m.name,1,3)=="jul", max(ecosys$Year)-1, max(ecosys$Year)) # Note: Jules missing 2010, so
run.start <- 850
inc <- round(as.numeric(substr(resolutions[r],3,5)),0) # making sure we're always dealing with whole numbers
yrs <- seq(from=run.end-round(inc/2,0), to=run.start+round(inc/2,0), by=-inc)
data.temp <- dat.mod[(dat.mod$Year %in% yrs), c("Model", "Updated", "Model.Order", "Site", "Year")]
# Making a note of the extent & resolution
ext <- as.factor("850-2010")
data.temp$Extent <- as.factor(ext)
data.temp$Resolution <- as.factor(resolutions[r])
# Making place-holders for the response & predictors so the loop works correctly
data.temp[,c(response, predictors.all, "Y.lag")] <- NA
# Calculating the mean for each wind.yrow for resolution
# Note: because we're now only analyzing single points rathern than the full running mean,
# we're now making the year in the middle of the resolution
if(inc==1){ # if we're working at coarser than annual scale, we need to find the mean for each bin
data.temp[,c(response, predictors.all, "Y.lag")] <- dat.mod[,c(response, predictors.all, "Y.lag")]
} else {
for(s in sites){
for(y in yrs){
data.temp[data.temp$Site==s & data.temp$Year==y,c(response, predictors.all, "Y.lag")] <- apply(dat.mod[dat.mod$Site==s & dat.mod$Year>=round(y-inc/2, 0) & dat.mod$Year<=round(y+inc/2, 0),c(response, predictors.all, "Y.lag")], 2, FUN=mean)
}
}
}
# Getting rid of NAs; note: this has to happen AFTER extent definition otherwise scale & extent are compounded
data.temp <- data.temp[complete.cases(data.temp[,c(response, "Y.lag")]),]
# Make a new variable called Y with the response variable so it can be generalized
data.temp$Y <- data.temp[,response]
paleon.models[[paste(resolutions[r])]] <- data.temp
} # End Resolution Loop
# --------------------------------
# -------------------------------------------------
# Run the gamms
# -------------------------------------------------
models.base <- mclapply(paleon.models, paleon.gams.models, mc.cores=length(paleon.models), response=response, k=k, predictors.all=predictors.all, site.effects=T)
# -------------------------------------------------
# -------------------------------------------------
# Bind Resolutions together to make them easier to work with
# -------------------------------------------------
for(i in 1:length(models.base)){
if(i==1) {
mod.out <- list()
mod.out$data <- models.base[[i]]$data
mod.out$weights <- models.base[[i]]$weights
mod.out$ci.response <- models.base[[i]]$ci.response
mod.out$sim.response <- models.base[[i]]$sim.response
mod.out$ci.terms <- models.base[[i]]$ci.terms
mod.out$sim.terms <- models.base[[i]]$sim.terms
mod.out[[paste("gamm", ext, substr(names(models.base)[i],3,nchar(paste(names(models.base)))), sep=".")]] <- models.base[[i]]$gamm
} else {
mod.out$data <- rbind(mod.out$data, models.base[[i]]$data)
mod.out$weights <- rbind(mod.out$weights, models.base[[i]]$weights)
mod.out$ci.response <- rbind(mod.out$ci.response, models.base[[i]]$ci.response)
mod.out$sim.response <- rbind(mod.out$sim.response, models.base[[i]]$sim.response)
mod.out$ci.terms <- rbind(mod.out$ci.terms, models.base[[i]]$ci.terms)
mod.out$sim.terms <- rbind(mod.out$sim.terms, models.base[[i]]$sim.terms)
mod.out[[paste("gamm", ext, substr(names(models.base)[i],3,nchar(paste(names(models.base)))), sep=".")]] <- models.base[[i]]$gamm
}
}
m.order <- unique(mod.out$data$Model.Order)
col.model <- model.colors[model.colors$Model.Order %in% m.order,"color"]
save(mod.out, file=file.path(dat.dir, paste0("gamm_AllDrivers_Yr_", m.name, "_", response, "_Lag5.Rdata")))
pdf(file.path(fig.dir, paste0("GAMM_ResponsePrediction_AllDrivers_GS_", m.order, "_", response, "_Lag5.pdf")))
print(
ggplot(data=mod.out$ci.response[,]) + facet_grid(Site~Resolution, scales="free") + theme_bw() +
geom_line(data= mod.out$data[,], aes(x=Year, y=Y), alpha=0.5) +
geom_ribbon(aes(x=Year, ymin=lwr, ymax=upr), alpha=0.5, fill=col.model) +
geom_line(aes(x=Year, y=mean), size=0.35, color= col.model) +
# scale_x_continuous(limits=c(850,2010)) +
# scale_y_continuous(limits=quantile(mod.out$data$response, c(0.01, 0.99),na.rm=T)) +
# scale_fill_manual(values=col.model) +
# scale_color_manual(values=col.model) +
labs(title=paste(m.order, response, sep=" - "), x="Year", y=response)
)
print(
ggplot(data=mod.out$ci.response[,]) + facet_grid(Site~Resolution, scales="free") + theme_bw() +
geom_line(data= mod.out$data[,], aes(x=Year, y=Y), alpha=0.5) +
geom_ribbon(aes(x=Year, ymin=lwr, ymax=upr), alpha=0.5, fill=col.model) +
geom_line(aes(x=Year, y=mean), size=0.35, color= col.model) +
scale_x_continuous(limits=c(1900,2010)) +
# scale_y_continuous(limits=quantile(mod.out$data[mod.out$data$Year>=1900,"response"], c(0.01, 0.99),na.rm=T)) +
# scale_fill_manual(values=col.model) +
# scale_color_manual(values=col.model) +
labs(title=paste(m.order, response, sep=" - "), x="Year", y=response)
)
dev.off()
# print(
ggplot(data=mod.out$ci.response[mod.out$ci.response$Resolution=="t.010",]) + facet_grid(Site~Resolution, scales="free") + theme_bw() +
geom_line(data= mod.out$data[mod.out$data$Resolution=="t.010",], aes(x=Year, y=Y), alpha=0.5) +
geom_ribbon(aes(x=Year, ymin=lwr, ymax=upr), alpha=0.5, fill=col.model) +
geom_line(aes(x=Year, y=mean), size=0.35, color= col.model) +
# scale_x_continuous(limits=c(1900,2010)) +
# scale_y_continuous(limits=quantile(mod.out$data[mod.out$data$Year>=1900,"response"], c(0.01, 0.99),na.rm=T)) +
# scale_fill_manual(values=col.model) +
# scale_color_manual(values=col.model) +
labs(title=paste(m.order, response, "Decadal", sep=" - "), x="Year", y=response)
# )
pdf(file.path(fig.dir, paste0("GAMM_DriverEffects_AllDrivers_GS_", m.order, "_", response, "_Lag10.pdf")))
print(
ggplot(data=mod.out$ci.terms[!mod.out$ci.terms$Effect=="Y.lag",]) + facet_wrap(~ Effect, scales="free") + theme_bw() +
geom_ribbon(aes(x=x, ymin=lwr, ymax=upr, fill=Resolution), alpha=0.5) +
geom_line(aes(x=x, y=mean, color=Resolution), size=2) +
geom_hline(yintercept=0, linetype="dashed") +
# scale_color_manual(values=c("red2", "blue", "green3")) +
# scale_fill_manual(values=c("red2", "blue", "green3")) +
labs(title=paste0("Driver Effects: ",m.order), y="Effect Size") # +
)
dev.off()
# -------------------------------------------------
} # End by Model Loop
# } # End Response Loop
|
/R/Exploratory2/2a_process_drivers_all_drivers_byResolution_GS_dAGB.R
|
no_license
|
PalEON-Project/Temporal-Scaling-MS
|
R
| false
| false
| 12,931
|
r
|
# ----------------------------------------
# Temporal Scaling Analyses -- Create baseline growing season model
# Non-linear driver effects through time
# Christy Rollinson, crollinson@gmail.com
# Date Created: 10 July 2015
# ----------------------------------------
# -------------------------
# Objectives & Overview
# -------------------------
# Driving Questions: What is the relative control of different drivers within each model?
# Rationale: Not all models use all inputs, and many drivers are correlated, so we need to
# see if the temperature pattern is really a radiation pattern, etc.
# -------------------------
#
# -------------------------
# Data/Results Generation:
# -------------------------
# (Fit GAMM per site per m.name)
# 1) Temporal Grain (Resolution)
# -- Fit GAMM over constant wind.gsow with different degrees of smoothing (1 yr - 250 yr)
# -------------------------
#
# -------------------------
# Interpretation Analyses:
# -------------------------
# 1) Space-Time Comparison
# -- Hypothesis: Driver responses across sites within a m.name converge at coarser temporal grains
# and larger extents because the models have time to adjust and seek equilibrium.
#
# -- Analysis: Use the posterior CIs for each smoothing term to see if the driver curves for sites
# within a m.name are statstically different at different sites at different scales (or
# alternatively if there are statistical differences in [parts of] the curves between
# scales)
#
#
# 2) Multi-Model Driver Comparison
# -- Hypothesis: Because models were built & parameterized to perform well in the modern era, there
# will be greater agreement of the direction & primary driver of change in the more recent time
# periods than over the full extent of the PalEON runs.
# -- Hypothesis about temporal grain?
#
# -- Analysis: For each given scale, compare the m.name response curves for each driver. Determine
# which drivers are most similar/variable among models and at what scales? Are there
# particular ranges of each driver response where models responses are most similar/different?
# -------------------------
# ----------------------------------------
# ----------------------------------------
# Load Libaries
# ----------------------------------------
library(parallel)
library(mgcv)
# library(ncdf4)
# library(lme4)
# library(R2jags)
library(ggplot2); library(grid)
library(car)
# library(zoo)
# library(mvtnorm)
# library(MCMCpack)
# ----------------------------------------
# ----------------------------------------
# Define constants
# ----------------------------------------
sec2yr <- 1*60*60*24*365
# ----------------------------------------
# ----------------------------------------
# Set Directories
# ----------------------------------------
# setwd("~/Desktop/Dropbox/PalEON CR/PalEON_MIP_Site/Analyses/Temporal-Scaling")
setwd("..")
dat.base="Data/gamms"
fig.base="Figures/gamms"
# Making sure the appropriate file paths exist
if(!dir.exists(dat.base)) dir.create(dat.base)
if(!dir.exists(fig.base)) dir.create(fig.base)
# Setting the data & figure directories
fig.dir <- file.path(fig.base, "Big4_AGB_GS_lag1_byResolution")
dat.dir <- file.path(dat.base, "Big4_AGB_GS_lag1_byResolution")
# Make sure the appropriate file paths are in place
if(!dir.exists(dat.dir)) dir.create(dat.dir)
if(!dir.exists(fig.dir)) dir.create(fig.dir)
# ----------------------------------------
# ----------------------------------------
# Load data files & function scripts
# ----------------------------------------
# Ecosys file = organized, post-processed m.name outputs
# generated with 1_generate_ecosys.R
load(file.path("Data", "EcosysData_Raw.Rdata"))
summary(ecosys)
model.colors
source('R/0_calculate.sensitivity_4drivers_lag1.R', chdir = TRUE)
# Read in model color scheme
model.colors
# ----------------------------------------
# -------------------------------------------------
# Settings for the rest of this script
# -------------------------------------------------
# Get rid of CLM-BGC because its actual drivers are messed up
ecosys <- ecosys[!ecosys$Model=="clm.bgc",]
# Setting up a loop for 1 m.name, 1 temporal scale
sites <- unique(ecosys$Site)
model.name <- unique(ecosys$Model)
model.order <- unique(ecosys$Model.Order)
resolutions <- c("t.001", "t.010", "t.050", "t.100")
response.all <- c("NPP", "AGB.diff", "NEE")
# predictors.all <- c("tair", "precipf", "swdown", "lwdown", "psurf", "qair", "wind", "CO2")
predictors.all <- c("tair", "precipf", "swdown", "CO2")
predictor.suffix <- c(".gs")
k=4
y.lag=5
# r=1
# -------------------------------------------------
# -------------------------------------------------
# Set up the appropriate data for each model into a list
# -------------------------------------------------
# for(y in 1:length(response.all)){
y=2
response <- response.all[y]
print("-------------------------------------")
print("-------------------------------------")
print(paste0("------ Processing Var: ", response, " ------"))
# M1 <- 1:length(model.name)
# M2 <- which(!model.name=="jules.stat")
#if(# response=="AGB.diff") models <- which(!model.name=="jules.stat") else models <- 1:length(model.name)
for(m in 1:length(model.name)){
paleon.models <- list()
m.name <- model.name[m]
m.order <- model.order[m]
print("-------------------------------------")
print(paste0("------ Processing Model: ", m.order, " ------"))
# Note: Here we're renaming things that had the suffix to just be generalized tair, etc
dat.mod <- ecosys[ecosys$Model==m.name, c("Model", "Updated", "Model.Order", "Site", "Year", response, paste0(predictors.all, predictor.suffix))]
names(dat.mod)[(ncol(dat.mod)-length(predictors.all)+1):ncol(dat.mod)] <- predictors.all
if(!max(dat.mod[,response], na.rm=T)>0) next # If a variable is missing, just skip over this model for now
for(s in sites){
for(y in (min(dat.mod$Year)+y.lag):max(dat.mod$Year)){
dat.mod[dat.mod$Site==s & dat.mod$Year==y,"Y.lag"] <- mean(dat.mod[dat.mod$Site==s & dat.mod$Year>=(y-y.lag) & dat.mod$Year<y,response], na.rm=T)
}
}
for(r in 1:length(resolutions)){ # Loop through different resolutions
# Figure out which years to take:
# Note: working backwards to help make sure we get modern end of the CO2.yr & temperature distributions
run.end <- ifelse(substr(m.name,1,3)=="jul", max(ecosys$Year)-1, max(ecosys$Year)) # Note: Jules missing 2010, so
run.start <- 850
inc <- round(as.numeric(substr(resolutions[r],3,5)),0) # making sure we're always dealing with whole numbers
yrs <- seq(from=run.end-round(inc/2,0), to=run.start+round(inc/2,0), by=-inc)
data.temp <- dat.mod[(dat.mod$Year %in% yrs), c("Model", "Updated", "Model.Order", "Site", "Year")]
# Making a note of the extent & resolution
ext <- as.factor("850-2010")
data.temp$Extent <- as.factor(ext)
data.temp$Resolution <- as.factor(resolutions[r])
# Making place-holders for the response & predictors so the loop works correctly
data.temp[,c(response, predictors.all, "Y.lag")] <- NA
# Calculating the mean for each wind.yrow for resolution
# Note: because we're now only analyzing single points rathern than the full running mean,
# we're now making the year in the middle of the resolution
if(inc==1){ # if we're working at coarser than annual scale, we need to find the mean for each bin
data.temp[,c(response, predictors.all, "Y.lag")] <- dat.mod[,c(response, predictors.all, "Y.lag")]
} else {
for(s in sites){
for(y in yrs){
data.temp[data.temp$Site==s & data.temp$Year==y,c(response, predictors.all, "Y.lag")] <- apply(dat.mod[dat.mod$Site==s & dat.mod$Year>=round(y-inc/2, 0) & dat.mod$Year<=round(y+inc/2, 0),c(response, predictors.all, "Y.lag")], 2, FUN=mean)
}
}
}
# Getting rid of NAs; note: this has to happen AFTER extent definition otherwise scale & extent are compounded
data.temp <- data.temp[complete.cases(data.temp[,c(response, "Y.lag")]),]
# Make a new variable called Y with the response variable so it can be generalized
data.temp$Y <- data.temp[,response]
paleon.models[[paste(resolutions[r])]] <- data.temp
} # End Resolution Loop
# --------------------------------
# -------------------------------------------------
# Run the gamms
# -------------------------------------------------
models.base <- mclapply(paleon.models, paleon.gams.models, mc.cores=length(paleon.models), response=response, k=k, predictors.all=predictors.all, site.effects=T)
# -------------------------------------------------
# -------------------------------------------------
# Bind Resolutions together to make them easier to work with
# -------------------------------------------------
for(i in 1:length(models.base)){
if(i==1) {
mod.out <- list()
mod.out$data <- models.base[[i]]$data
mod.out$weights <- models.base[[i]]$weights
mod.out$ci.response <- models.base[[i]]$ci.response
mod.out$sim.response <- models.base[[i]]$sim.response
mod.out$ci.terms <- models.base[[i]]$ci.terms
mod.out$sim.terms <- models.base[[i]]$sim.terms
mod.out[[paste("gamm", ext, substr(names(models.base)[i],3,nchar(paste(names(models.base)))), sep=".")]] <- models.base[[i]]$gamm
} else {
mod.out$data <- rbind(mod.out$data, models.base[[i]]$data)
mod.out$weights <- rbind(mod.out$weights, models.base[[i]]$weights)
mod.out$ci.response <- rbind(mod.out$ci.response, models.base[[i]]$ci.response)
mod.out$sim.response <- rbind(mod.out$sim.response, models.base[[i]]$sim.response)
mod.out$ci.terms <- rbind(mod.out$ci.terms, models.base[[i]]$ci.terms)
mod.out$sim.terms <- rbind(mod.out$sim.terms, models.base[[i]]$sim.terms)
mod.out[[paste("gamm", ext, substr(names(models.base)[i],3,nchar(paste(names(models.base)))), sep=".")]] <- models.base[[i]]$gamm
}
}
m.order <- unique(mod.out$data$Model.Order)
col.model <- model.colors[model.colors$Model.Order %in% m.order,"color"]
save(mod.out, file=file.path(dat.dir, paste0("gamm_AllDrivers_Yr_", m.name, "_", response, "_Lag5.Rdata")))
pdf(file.path(fig.dir, paste0("GAMM_ResponsePrediction_AllDrivers_GS_", m.order, "_", response, "_Lag5.pdf")))
print(
ggplot(data=mod.out$ci.response[,]) + facet_grid(Site~Resolution, scales="free") + theme_bw() +
geom_line(data= mod.out$data[,], aes(x=Year, y=Y), alpha=0.5) +
geom_ribbon(aes(x=Year, ymin=lwr, ymax=upr), alpha=0.5, fill=col.model) +
geom_line(aes(x=Year, y=mean), size=0.35, color= col.model) +
# scale_x_continuous(limits=c(850,2010)) +
# scale_y_continuous(limits=quantile(mod.out$data$response, c(0.01, 0.99),na.rm=T)) +
# scale_fill_manual(values=col.model) +
# scale_color_manual(values=col.model) +
labs(title=paste(m.order, response, sep=" - "), x="Year", y=response)
)
print(
ggplot(data=mod.out$ci.response[,]) + facet_grid(Site~Resolution, scales="free") + theme_bw() +
geom_line(data= mod.out$data[,], aes(x=Year, y=Y), alpha=0.5) +
geom_ribbon(aes(x=Year, ymin=lwr, ymax=upr), alpha=0.5, fill=col.model) +
geom_line(aes(x=Year, y=mean), size=0.35, color= col.model) +
scale_x_continuous(limits=c(1900,2010)) +
# scale_y_continuous(limits=quantile(mod.out$data[mod.out$data$Year>=1900,"response"], c(0.01, 0.99),na.rm=T)) +
# scale_fill_manual(values=col.model) +
# scale_color_manual(values=col.model) +
labs(title=paste(m.order, response, sep=" - "), x="Year", y=response)
)
dev.off()
# print(
ggplot(data=mod.out$ci.response[mod.out$ci.response$Resolution=="t.010",]) + facet_grid(Site~Resolution, scales="free") + theme_bw() +
geom_line(data= mod.out$data[mod.out$data$Resolution=="t.010",], aes(x=Year, y=Y), alpha=0.5) +
geom_ribbon(aes(x=Year, ymin=lwr, ymax=upr), alpha=0.5, fill=col.model) +
geom_line(aes(x=Year, y=mean), size=0.35, color= col.model) +
# scale_x_continuous(limits=c(1900,2010)) +
# scale_y_continuous(limits=quantile(mod.out$data[mod.out$data$Year>=1900,"response"], c(0.01, 0.99),na.rm=T)) +
# scale_fill_manual(values=col.model) +
# scale_color_manual(values=col.model) +
labs(title=paste(m.order, response, "Decadal", sep=" - "), x="Year", y=response)
# )
pdf(file.path(fig.dir, paste0("GAMM_DriverEffects_AllDrivers_GS_", m.order, "_", response, "_Lag10.pdf")))
print(
ggplot(data=mod.out$ci.terms[!mod.out$ci.terms$Effect=="Y.lag",]) + facet_wrap(~ Effect, scales="free") + theme_bw() +
geom_ribbon(aes(x=x, ymin=lwr, ymax=upr, fill=Resolution), alpha=0.5) +
geom_line(aes(x=x, y=mean, color=Resolution), size=2) +
geom_hline(yintercept=0, linetype="dashed") +
# scale_color_manual(values=c("red2", "blue", "green3")) +
# scale_fill_manual(values=c("red2", "blue", "green3")) +
labs(title=paste0("Driver Effects: ",m.order), y="Effect Size") # +
)
dev.off()
# -------------------------------------------------
} # End by Model Loop
# } # End Response Loop
|
exp.fitter <- function(degrees = 150, inc = 1, bin.factor = 1, is.plot = TRUE, fit = exp.fit, x = i100[i100*FUV>0], y = FUV[i100*FUV>0], z = long[i100*FUV>0], mu = rep(1,9), sig = rep(1,9)){
x <- x[z < degrees + inc & z >= degrees];
y <- y[z < degrees + inc & z >= degrees];
#Fit the Model
exp.data <- list(N = length(x), x = x, y = y, priorMu = mu, priorSig = sig);
init.data <- list();
for(i in 1:4) { init.data[[i]] <- list(log_a = mu, log_sigma = 5.3);}
model.fit <- sampling(fit, data = exp.data, iter = 100, chains = 4, init = init.data);
if(is.plot){
# Plot Raw Data
degrees <- degrees / bin.factor;
plot(x, y, xlab = "i100", ylab = "FUV", main = bquote(theta == .(degrees) *degree ~ "-" ~ .(degrees+inc) *degree), cex = 1, bty = "l", col = "gray");
# Find and Plot Fitted Values of Model
xax <- c(0:(max(x)*100))/100;
A <- extract(model.fit)$a
for(i in 1:nrow(A)){
if(fit@model_name == "Exp Fit"){
fitted <- exp.curve(xax,A[i,]);
} else {
fitted <- exp.curve2(xax,A[i,]);
}
lines(xax, fitted, lwd = .5, lty = 1, col = alpha("red",.1));
}
}
return (model.fit)
}
inv.logit <- function(x){ return(1/(1+exp(-x))) }
exp.curve = function(x = 2, a) {
result <- a[1] + a[2]*a[3]*(1-exp(-x/(a[3]))-a[4]*exp(-.5*((x-a[5])/a[6])^2)) + a[7]*a[9]*x*log(1+exp((x-a[8])/a[9]))
return(result)
}
exp.curve2 = function(x = 2, a) {
result <- a[4]*a[5]*(1-exp(-x/(a[5]))-a[6]*exp(-.5*((x-a[7])/a[8])^2))
result <- result * inv.logit((x-a[2])/a[3]) + a[1]
return(result)
}
|
/Hierarchical Model/Exponential Model/Exp_Fitter.R
|
no_license
|
swupnil/astronomy_ep
|
R
| false
| false
| 1,584
|
r
|
exp.fitter <- function(degrees = 150, inc = 1, bin.factor = 1, is.plot = TRUE, fit = exp.fit, x = i100[i100*FUV>0], y = FUV[i100*FUV>0], z = long[i100*FUV>0], mu = rep(1,9), sig = rep(1,9)){
x <- x[z < degrees + inc & z >= degrees];
y <- y[z < degrees + inc & z >= degrees];
#Fit the Model
exp.data <- list(N = length(x), x = x, y = y, priorMu = mu, priorSig = sig);
init.data <- list();
for(i in 1:4) { init.data[[i]] <- list(log_a = mu, log_sigma = 5.3);}
model.fit <- sampling(fit, data = exp.data, iter = 100, chains = 4, init = init.data);
if(is.plot){
# Plot Raw Data
degrees <- degrees / bin.factor;
plot(x, y, xlab = "i100", ylab = "FUV", main = bquote(theta == .(degrees) *degree ~ "-" ~ .(degrees+inc) *degree), cex = 1, bty = "l", col = "gray");
# Find and Plot Fitted Values of Model
xax <- c(0:(max(x)*100))/100;
A <- extract(model.fit)$a
for(i in 1:nrow(A)){
if(fit@model_name == "Exp Fit"){
fitted <- exp.curve(xax,A[i,]);
} else {
fitted <- exp.curve2(xax,A[i,]);
}
lines(xax, fitted, lwd = .5, lty = 1, col = alpha("red",.1));
}
}
return (model.fit)
}
inv.logit <- function(x){ return(1/(1+exp(-x))) }
exp.curve = function(x = 2, a) {
result <- a[1] + a[2]*a[3]*(1-exp(-x/(a[3]))-a[4]*exp(-.5*((x-a[5])/a[6])^2)) + a[7]*a[9]*x*log(1+exp((x-a[8])/a[9]))
return(result)
}
exp.curve2 = function(x = 2, a) {
result <- a[4]*a[5]*(1-exp(-x/(a[5]))-a[6]*exp(-.5*((x-a[7])/a[8])^2))
result <- result * inv.logit((x-a[2])/a[3]) + a[1]
return(result)
}
|
PEVMAX0 <-
function(Train,Test, P, lambda=1e-5){
PTrain<-P[rownames(P)%in%Train,]
PEVmean<-max(diag(PTrain%*%solve(crossprod(PTrain)+lambda*diag(ncol(P)),t(PTrain))))
return(PEVmean)
}
|
/STPGA/R/PEVMAX0.R
|
no_license
|
ingted/R-Examples
|
R
| false
| false
| 201
|
r
|
PEVMAX0 <-
function(Train,Test, P, lambda=1e-5){
PTrain<-P[rownames(P)%in%Train,]
PEVmean<-max(diag(PTrain%*%solve(crossprod(PTrain)+lambda*diag(ncol(P)),t(PTrain))))
return(PEVmean)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/RcppExports.R
\name{crtTest}
\alias{crtTest}
\title{Test Rcpp function}
\usage{
crtTest(test)
}
\arguments{
\item{test}{test parameter}
}
\description{
Test Rcpp function
}
|
/man/crtTest.Rd
|
no_license
|
olssol/rwetools
|
R
| false
| true
| 251
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/RcppExports.R
\name{crtTest}
\alias{crtTest}
\title{Test Rcpp function}
\usage{
crtTest(test)
}
\arguments{
\item{test}{test parameter}
}
\description{
Test Rcpp function
}
|
#!/usr/bin/env Rscript
# Plots mean referring ability (RA) weight for round and calculates significance using a general linear model with random effects for dyad ("session").
#
#
# Copyright 2018 Todd Shore
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
args <- commandArgs(trailingOnly=TRUE)
if(length(args) < 2)
{
stop("Usage: <scriptname> INFILE OUTFILE")
}
#infile <- "~/Projects/tangrams-restricted/Data/Analysis/2018-04-27/results-cross-2.tsv"
infile <- args[1]
if (!file_test("-f", infile)) {
stop(sprintf("No file found at \"%s\".", infile));
}
outfile <- args[2]
library(ggplot2)
library(tools)
read_results <- function(inpath) {
#return(read.csv(inpath, sep = "\t", colClasses = c(Dyad="factor", round="integer", role="factor", word="factor")))
return(read.csv(inpath, sep = "\t", colClasses = c(cond="factor", session="factor", round="integer")))
}
# https://stackoverflow.com/a/27694724
try(windowsFonts(Times=windowsFont("Times New Roman")))
df <- read_results(infile)
sapply(df, class)
# Only select the rows using just RA weighting "Wgt"
df <- df[df$cond %in% c("Wgt"), ]
# Hack to change legend label
names(df)[names(df) == "cond"] <- "Condition"
names(df)[names(df) == "rank"] <- "Rank"
names(df)[names(df) == "round"] <- "Round"
names(df)[names(df) == "session"] <- "Dyad"
names(df)[names(df) == "weight"] <- "RA"
names(df)[names(df) == "words"] <- "Tokens"
# https://stackoverflow.com/a/15665536
df$Dyad <- factor(df$Dyad, levels = paste(sort(as.integer(levels(df$Dyad)))))
plot <- ggplot(df, aes(x=Round, y=RA))
plot <- plot + xlab(expression(paste("Game round ", italic("i")))) + ylab("Mean RA")
aspectRatio <- 9/16
plot <- plot + theme_light() + theme(text=element_text(family="Times"), aspect.ratio=aspectRatio, plot.margin=margin(12,0,0,0))
#break_datapoints <- df[df$Round %% 5 == 0, ]
#plot <- plot + stat_summary(data = break_datapoints, fun.data = mean_se, size=0.3)
plot <- plot + stat_summary(fun.data = mean_se, size=0.2)
plot <- plot + geom_smooth(method = "lm", formula = y ~ poly(x,2), level=0.95, fullrange=TRUE, size=0.7, color="darkred")
xmin <- 1
#xmax <- max(df$Round)
xmax <- 80
print(sprintf("Plotting round %d to %d.", xmin, xmax), quote=FALSE)
xb <- seq(xmin, xmax)
xb <- subset(xb, (xb %% 20 == 0) | (xb == xmin) | (xb == xmax))
print(xb)
plot <- plot + scale_x_continuous(breaks = xb, expand = c(0, 0))
ymin <- 0.05
#ymax <- max(df$RA)
ymax <- 0.3
print(sprintf("Plotting RA %f to %f.", ymin, ymax), quote=FALSE)
plot <- plot + coord_cartesian(xlim = c(xmin, xmax), ylim = c(ymin, ymax), expand = FALSE)
output_device <- file_ext(outfile)
print(sprintf("Writing plot to \"%s\" using format \"%s\".", outfile, output_device), quote=FALSE)
width <- 100 # EMNLP 2018
#width <- 80 # SemDial 2018
height <- width * aspectRatio
ggsave(outfile, plot = plot, device=output_device, width = width, height = height, units="mm", dpi=1000)
|
/plot_round_ra.R
|
permissive
|
errantlinguist/tangrams-analysis
|
R
| false
| false
| 3,393
|
r
|
#!/usr/bin/env Rscript
# Plots mean referring ability (RA) weight for round and calculates significance using a general linear model with random effects for dyad ("session").
#
#
# Copyright 2018 Todd Shore
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
args <- commandArgs(trailingOnly=TRUE)
if(length(args) < 2)
{
stop("Usage: <scriptname> INFILE OUTFILE")
}
#infile <- "~/Projects/tangrams-restricted/Data/Analysis/2018-04-27/results-cross-2.tsv"
infile <- args[1]
if (!file_test("-f", infile)) {
stop(sprintf("No file found at \"%s\".", infile));
}
outfile <- args[2]
library(ggplot2)
library(tools)
read_results <- function(inpath) {
#return(read.csv(inpath, sep = "\t", colClasses = c(Dyad="factor", round="integer", role="factor", word="factor")))
return(read.csv(inpath, sep = "\t", colClasses = c(cond="factor", session="factor", round="integer")))
}
# https://stackoverflow.com/a/27694724
try(windowsFonts(Times=windowsFont("Times New Roman")))
df <- read_results(infile)
sapply(df, class)
# Only select the rows using just RA weighting "Wgt"
df <- df[df$cond %in% c("Wgt"), ]
# Hack to change legend label
names(df)[names(df) == "cond"] <- "Condition"
names(df)[names(df) == "rank"] <- "Rank"
names(df)[names(df) == "round"] <- "Round"
names(df)[names(df) == "session"] <- "Dyad"
names(df)[names(df) == "weight"] <- "RA"
names(df)[names(df) == "words"] <- "Tokens"
# https://stackoverflow.com/a/15665536
df$Dyad <- factor(df$Dyad, levels = paste(sort(as.integer(levels(df$Dyad)))))
plot <- ggplot(df, aes(x=Round, y=RA))
plot <- plot + xlab(expression(paste("Game round ", italic("i")))) + ylab("Mean RA")
aspectRatio <- 9/16
plot <- plot + theme_light() + theme(text=element_text(family="Times"), aspect.ratio=aspectRatio, plot.margin=margin(12,0,0,0))
#break_datapoints <- df[df$Round %% 5 == 0, ]
#plot <- plot + stat_summary(data = break_datapoints, fun.data = mean_se, size=0.3)
plot <- plot + stat_summary(fun.data = mean_se, size=0.2)
plot <- plot + geom_smooth(method = "lm", formula = y ~ poly(x,2), level=0.95, fullrange=TRUE, size=0.7, color="darkred")
xmin <- 1
#xmax <- max(df$Round)
xmax <- 80
print(sprintf("Plotting round %d to %d.", xmin, xmax), quote=FALSE)
xb <- seq(xmin, xmax)
xb <- subset(xb, (xb %% 20 == 0) | (xb == xmin) | (xb == xmax))
print(xb)
plot <- plot + scale_x_continuous(breaks = xb, expand = c(0, 0))
ymin <- 0.05
#ymax <- max(df$RA)
ymax <- 0.3
print(sprintf("Plotting RA %f to %f.", ymin, ymax), quote=FALSE)
plot <- plot + coord_cartesian(xlim = c(xmin, xmax), ylim = c(ymin, ymax), expand = FALSE)
output_device <- file_ext(outfile)
print(sprintf("Writing plot to \"%s\" using format \"%s\".", outfile, output_device), quote=FALSE)
width <- 100 # EMNLP 2018
#width <- 80 # SemDial 2018
height <- width * aspectRatio
ggsave(outfile, plot = plot, device=output_device, width = width, height = height, units="mm", dpi=1000)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lib_writeme.R
\name{lib_writeme}
\alias{lib_writeme}
\title{Document the dependancies}
\usage{
lib_writeme(script)
}
\arguments{
\item{script}{a .R file}
}
\value{
markdown
}
\description{
Input a R script to prepare a markdown file documenting the dependancies. These can be included in a project
Readme file.
}
\examples{
lib_writeme("script.R")
}
|
/man/lib_writeme.Rd
|
permissive
|
UBC-MDS/librely
|
R
| false
| true
| 428
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/lib_writeme.R
\name{lib_writeme}
\alias{lib_writeme}
\title{Document the dependancies}
\usage{
lib_writeme(script)
}
\arguments{
\item{script}{a .R file}
}
\value{
markdown
}
\description{
Input a R script to prepare a markdown file documenting the dependancies. These can be included in a project
Readme file.
}
\examples{
lib_writeme("script.R")
}
|
\name{dgCMatrix-class}
\docType{class}
\title{Compressed, sparse, column-oriented numeric matrices}
\alias{dgCMatrix-class}
\alias{as.vector,dgCMatrix,missing-method}
\alias{coerce,matrix,dgCMatrix-method}
\alias{coerce,dgeMatrix,dgCMatrix-method}
\alias{coerce,dgCMatrix,dgTMatrix-method}
\alias{coerce,dgCMatrix,dsCMatrix-method}% deprecated
\alias{coerce,dgCMatrix,dtCMatrix-method}
\alias{coerce,dgCMatrix,lgCMatrix-method}
\alias{coerce,dgCMatrix,ngCMatrix-method}
\alias{coerce,dgCMatrix,dgeMatrix-method}
\alias{coerce,dgCMatrix,matrix-method}
\alias{coerce,dgCMatrix,vector-method}
\alias{coerce,factor,dgCMatrix-method}
\alias{diag,dgCMatrix-method}
\alias{dim,dgCMatrix-method}
%\alias{lu,dgCMatrix-method}-> ./lu.Rd
\alias{isSymmetric,dgCMatrix-method}
\alias{t,dgCMatrix-method}
%\alias{solve,dgCMatrix,matrix-method}--> solve-methods.Rd
%% Group methods --------- FIXME: These are not tested yet (or documented)
\alias{Arith,logical,dgCMatrix-method}
\alias{Arith,numeric,dgCMatrix-method}
\alias{Arith,dgCMatrix,logical-method}
\alias{Arith,dgCMatrix,numeric-method}
\alias{Arith,dgCMatrix,dgCMatrix-method}
%\alias{Math2,dgCMatrix,numeric-method}
\alias{Math,dgCMatrix-method}
% for silly reasons, need these 2+3 as well:
\alias{round,dgCMatrix,numeric-method}
\alias{signif,dgCMatrix,numeric-method}
\alias{log,dgCMatrix-method}
\alias{gamma,dgCMatrix-method}
\alias{lgamma,dgCMatrix-method}
%
\description{The \code{dgCMatrix} class is a class of sparse numeric
matrices in the compressed, sparse, column-oriented format. In this
implementation the non-zero elements in the columns are sorted into
increasing row order. \code{dgCMatrix} is the
\emph{\dQuote{standard}} class for sparse numeric matrices in the
\pkg{Matrix} package.
}
\section{Objects from the Class}{
Objects can be created by calls of the form \code{new("dgCMatrix",
...)}, more typically via \code{as(*, "CsparseMatrix")} or similar.
Often however, more easily via \code{\link{Matrix}(*, sparse = TRUE)},
or most efficiently via \code{\link{sparseMatrix}()}.
}
\section{Slots}{
\describe{
\item{\code{x}:}{Object of class \code{"numeric"} - the non-zero
elements of the matrix.}
\item{\dots}{all other slots are inherited from the superclass
\code{"\linkS4class{CsparseMatrix}"}.
}
}
}
\section{Methods}{
Matrix products (e.g., \link{crossprod-methods}), and (among other)
\describe{
\item{coerce}{\code{signature(from = "matrix", to = "dgCMatrix")}}
\item{coerce}{\code{signature(from = "dgCMatrix", to = "matrix")}}
\item{coerce}{\code{signature(from = "dgCMatrix", to = "dgTMatrix")}}
\item{diag}{\code{signature(x = "dgCMatrix")}: returns the diagonal
of \code{x}}
\item{dim}{\code{signature(x = "dgCMatrix")}: returns the dimensions
of \code{x}}
\item{image}{\code{signature(x = "dgCMatrix")}: plots an image of
\code{x} using the \code{\link[lattice]{levelplot}} function}
\item{solve}{\code{signature(a = "dgCMatrix", b = "...")}:
see \code{\link{solve-methods}}, notably the extra argument
\code{sparse}.}
\item{lu}{\code{signature(x = "dgCMatrix")}: computes the LU
decomposition of a square \code{dgCMatrix} object}
}
}
%\references{}
%\author{}
%\note{}
\seealso{
Classes \code{\linkS4class{dsCMatrix}},
\code{\linkS4class{dtCMatrix}}, \code{\link{lu}}
}
\examples{
(m <- Matrix(c(0,0,2:0), 3,5))
str(m)
m[,1]
\dontshow{## regression test: this must give a validity-check error:
stopifnot(inherits(try(new("dgCMatrix", i = 0:1, p = 0:2,
x = c(2,3), Dim = 3:4)),
"try-error"))
}
}
\keyword{classes}
\keyword{algebra}
|
/branches/Matrix-new-SuiteSparse/man/dgCMatrix-class.Rd
|
no_license
|
LTLA/Matrix
|
R
| false
| false
| 3,678
|
rd
|
\name{dgCMatrix-class}
\docType{class}
\title{Compressed, sparse, column-oriented numeric matrices}
\alias{dgCMatrix-class}
\alias{as.vector,dgCMatrix,missing-method}
\alias{coerce,matrix,dgCMatrix-method}
\alias{coerce,dgeMatrix,dgCMatrix-method}
\alias{coerce,dgCMatrix,dgTMatrix-method}
\alias{coerce,dgCMatrix,dsCMatrix-method}% deprecated
\alias{coerce,dgCMatrix,dtCMatrix-method}
\alias{coerce,dgCMatrix,lgCMatrix-method}
\alias{coerce,dgCMatrix,ngCMatrix-method}
\alias{coerce,dgCMatrix,dgeMatrix-method}
\alias{coerce,dgCMatrix,matrix-method}
\alias{coerce,dgCMatrix,vector-method}
\alias{coerce,factor,dgCMatrix-method}
\alias{diag,dgCMatrix-method}
\alias{dim,dgCMatrix-method}
%\alias{lu,dgCMatrix-method}-> ./lu.Rd
\alias{isSymmetric,dgCMatrix-method}
\alias{t,dgCMatrix-method}
%\alias{solve,dgCMatrix,matrix-method}--> solve-methods.Rd
%% Group methods --------- FIXME: These are not tested yet (or documented)
\alias{Arith,logical,dgCMatrix-method}
\alias{Arith,numeric,dgCMatrix-method}
\alias{Arith,dgCMatrix,logical-method}
\alias{Arith,dgCMatrix,numeric-method}
\alias{Arith,dgCMatrix,dgCMatrix-method}
%\alias{Math2,dgCMatrix,numeric-method}
\alias{Math,dgCMatrix-method}
% for silly reasons, need these 2+3 as well:
\alias{round,dgCMatrix,numeric-method}
\alias{signif,dgCMatrix,numeric-method}
\alias{log,dgCMatrix-method}
\alias{gamma,dgCMatrix-method}
\alias{lgamma,dgCMatrix-method}
%
\description{The \code{dgCMatrix} class is a class of sparse numeric
matrices in the compressed, sparse, column-oriented format. In this
implementation the non-zero elements in the columns are sorted into
increasing row order. \code{dgCMatrix} is the
\emph{\dQuote{standard}} class for sparse numeric matrices in the
\pkg{Matrix} package.
}
\section{Objects from the Class}{
Objects can be created by calls of the form \code{new("dgCMatrix",
...)}, more typically via \code{as(*, "CsparseMatrix")} or similar.
Often however, more easily via \code{\link{Matrix}(*, sparse = TRUE)},
or most efficiently via \code{\link{sparseMatrix}()}.
}
\section{Slots}{
\describe{
\item{\code{x}:}{Object of class \code{"numeric"} - the non-zero
elements of the matrix.}
\item{\dots}{all other slots are inherited from the superclass
\code{"\linkS4class{CsparseMatrix}"}.
}
}
}
\section{Methods}{
Matrix products (e.g., \link{crossprod-methods}), and (among other)
\describe{
\item{coerce}{\code{signature(from = "matrix", to = "dgCMatrix")}}
\item{coerce}{\code{signature(from = "dgCMatrix", to = "matrix")}}
\item{coerce}{\code{signature(from = "dgCMatrix", to = "dgTMatrix")}}
\item{diag}{\code{signature(x = "dgCMatrix")}: returns the diagonal
of \code{x}}
\item{dim}{\code{signature(x = "dgCMatrix")}: returns the dimensions
of \code{x}}
\item{image}{\code{signature(x = "dgCMatrix")}: plots an image of
\code{x} using the \code{\link[lattice]{levelplot}} function}
\item{solve}{\code{signature(a = "dgCMatrix", b = "...")}:
see \code{\link{solve-methods}}, notably the extra argument
\code{sparse}.}
\item{lu}{\code{signature(x = "dgCMatrix")}: computes the LU
decomposition of a square \code{dgCMatrix} object}
}
}
%\references{}
%\author{}
%\note{}
\seealso{
Classes \code{\linkS4class{dsCMatrix}},
\code{\linkS4class{dtCMatrix}}, \code{\link{lu}}
}
\examples{
(m <- Matrix(c(0,0,2:0), 3,5))
str(m)
m[,1]
\dontshow{## regression test: this must give a validity-check error:
stopifnot(inherits(try(new("dgCMatrix", i = 0:1, p = 0:2,
x = c(2,3), Dim = 3:4)),
"try-error"))
}
}
\keyword{classes}
\keyword{algebra}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/analysis.R
\name{elite.network.org}
\alias{elite.network.org}
\title{Elite network for affiliations}
\usage{
elite.network.org(den = den, sigma = 14)
}
\arguments{
\item{sigma}{the number of members in an affiliation above which all affiliations are weighted down}
\item{rel.all}{an affiliation edge list in the\link{den} format.}
}
\value{
a elite network object
}
\description{
Construct a weighted elite network of affiliations
}
|
/man/elite.network.org.Rd
|
no_license
|
antongrau/soc.elite
|
R
| false
| true
| 513
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/analysis.R
\name{elite.network.org}
\alias{elite.network.org}
\title{Elite network for affiliations}
\usage{
elite.network.org(den = den, sigma = 14)
}
\arguments{
\item{sigma}{the number of members in an affiliation above which all affiliations are weighted down}
\item{rel.all}{an affiliation edge list in the\link{den} format.}
}
\value{
a elite network object
}
\description{
Construct a weighted elite network of affiliations
}
|
\name{AM2016ClimateSensitiveSINorway}
\alias{AM2016ClimateSensitiveSINorway}
\title{
Climate-sensitive site index models for Norway
}
\description{
Implementation of models for climate-sensitive site index models for
Norway as described in Antón-Fernández et al. (2016).
}
\usage{
AM2016ClimateSensitiveSINorway(soilquality, t.early.summer, waterbal, SI.spp)
}
\arguments{
\item{soilquality}{
A factor with levels 1 to 5 indicating the soilquality category. 1
being the poorest soils and 5 the best soils
}
\item{t.early.summer}{
A vector with sum temperatures (in C) in spring and early summer (april, june and july)
}
\item{waterbal}{
A vector with the montly moisture surplus in June (difference between
the 30-year mean precipitation in June and mean potential evapotranspiration in June.).
}
\item{SI.spp}{
SI species, that is, the species for which SI should be calculated. 1 = spruce, 2 = pine, 3 = birch.
}
}
\value{
Returns a vector with the estimated SI.
}
\references{
Anton-Fernandez, Clara, Blas Mola-Yudego, Lise Dalsgaard, and Rasmus
Astrup. 2016. “Climate-Sensitive Site Index Models for Norway.” Canadian
Journal of Forest Research 46 (6). doi: 10.1139/cjfr-2015-0155
}
\author{
Clara Anton-Fernandez
}
\examples{
AM2016ClimateSensitiveSINorway (soilquality = as.factor(c(1,2,3,4)),
t.early.summer = c(10,20,30,10),
waterbal = c(-40, 20,10,10),
SI.spp = c(1,2,2,3))
}
|
/man/AM2016ClimateSensitiveSINorway.Rd
|
no_license
|
cran/sitreeE
|
R
| false
| false
| 1,506
|
rd
|
\name{AM2016ClimateSensitiveSINorway}
\alias{AM2016ClimateSensitiveSINorway}
\title{
Climate-sensitive site index models for Norway
}
\description{
Implementation of models for climate-sensitive site index models for
Norway as described in Antón-Fernández et al. (2016).
}
\usage{
AM2016ClimateSensitiveSINorway(soilquality, t.early.summer, waterbal, SI.spp)
}
\arguments{
\item{soilquality}{
A factor with levels 1 to 5 indicating the soilquality category. 1
being the poorest soils and 5 the best soils
}
\item{t.early.summer}{
A vector with sum temperatures (in C) in spring and early summer (april, june and july)
}
\item{waterbal}{
A vector with the montly moisture surplus in June (difference between
the 30-year mean precipitation in June and mean potential evapotranspiration in June.).
}
\item{SI.spp}{
SI species, that is, the species for which SI should be calculated. 1 = spruce, 2 = pine, 3 = birch.
}
}
\value{
Returns a vector with the estimated SI.
}
\references{
Anton-Fernandez, Clara, Blas Mola-Yudego, Lise Dalsgaard, and Rasmus
Astrup. 2016. “Climate-Sensitive Site Index Models for Norway.” Canadian
Journal of Forest Research 46 (6). doi: 10.1139/cjfr-2015-0155
}
\author{
Clara Anton-Fernandez
}
\examples{
AM2016ClimateSensitiveSINorway (soilquality = as.factor(c(1,2,3,4)),
t.early.summer = c(10,20,30,10),
waterbal = c(-40, 20,10,10),
SI.spp = c(1,2,2,3))
}
|
testlist <- list(cost = structure(c(1.44888560957826e+135, 1.6249392498385e+65, 5.27956628994611e-134, 1.56839475268612e-251, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 5L)), flow = structure(c(3.80768289350145e+125, 8.58414828913381e+155, 3.37787969964034e+43, 2.83184518248624e-19, 7.49487861616974e+223, 8.52929466674086e+86, 2.51852491380534e-303, 3.12954510408264e-253, 2.45741775099414e-215, 6.59159492364721e+70, 2.33952815237705e+77, 3.1674929214459e+282, 1.0709591854537e+63, 7.43876613929249e+191, 8.31920980250172e+78, 1.26747339146319e+161, 5.68076251052666e-141, 9.98610641272026e+182, 232665383858.491, 3.75587249552337e-34, 8.67688084914444e+71, 2.85936996201565e+135, 5.49642980516022e+268, 854537881567133, 1.33507119962914e+95, 2.76994725819545e+63, 4.08029273738449e+275, 4.93486427894025e+289, 1.24604061502336e+294, 3.2125809174767e-185, 9.58716852715016e+39, 6.94657888227078e+275, 3.46330348083089e+199, 3.28318446108869e-286, 6.12239214969922e-296 ), .Dim = c(5L, 7L)))
result <- do.call(epiphy:::costTotCPP,testlist)
str(result)
|
/epiphy/inst/testfiles/costTotCPP/AFL_costTotCPP/costTotCPP_valgrind_files/1615926790-test.R
|
no_license
|
akhikolla/updatedatatype-list2
|
R
| false
| false
| 1,101
|
r
|
testlist <- list(cost = structure(c(1.44888560957826e+135, 1.6249392498385e+65, 5.27956628994611e-134, 1.56839475268612e-251, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 5L)), flow = structure(c(3.80768289350145e+125, 8.58414828913381e+155, 3.37787969964034e+43, 2.83184518248624e-19, 7.49487861616974e+223, 8.52929466674086e+86, 2.51852491380534e-303, 3.12954510408264e-253, 2.45741775099414e-215, 6.59159492364721e+70, 2.33952815237705e+77, 3.1674929214459e+282, 1.0709591854537e+63, 7.43876613929249e+191, 8.31920980250172e+78, 1.26747339146319e+161, 5.68076251052666e-141, 9.98610641272026e+182, 232665383858.491, 3.75587249552337e-34, 8.67688084914444e+71, 2.85936996201565e+135, 5.49642980516022e+268, 854537881567133, 1.33507119962914e+95, 2.76994725819545e+63, 4.08029273738449e+275, 4.93486427894025e+289, 1.24604061502336e+294, 3.2125809174767e-185, 9.58716852715016e+39, 6.94657888227078e+275, 3.46330348083089e+199, 3.28318446108869e-286, 6.12239214969922e-296 ), .Dim = c(5L, 7L)))
result <- do.call(epiphy:::costTotCPP,testlist)
str(result)
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 3878
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 3864
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 3864
c
c Input Parameter (command line, file):
c input filename QBFLIB/MayerEichberger-Saffidine/PositionalGames_hex/hex_rand_5x5-6m-8.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 1259
c no.of clauses 3878
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 3864
c
c QBFLIB/MayerEichberger-Saffidine/PositionalGames_hex/hex_rand_5x5-6m-8.qdimacs 1259 3878 E1 [343 344 345 346 347 736 773 810 847 884 921 958 995 1032] 0 171 1074 3864 RED
|
/code/dcnf-ankit-optimized/Results/QBFLIB-2018/E1/Experiments/MayerEichberger-Saffidine/PositionalGames_hex/hex_rand_5x5-6m-8/hex_rand_5x5-6m-8.R
|
no_license
|
arey0pushpa/dcnf-autarky
|
R
| false
| false
| 830
|
r
|
c DCNF-Autarky [version 0.0.1].
c Copyright (c) 2018-2019 Swansea University.
c
c Input Clause Count: 3878
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 3864
c
c Performing E1-Autarky iteration.
c Remaining clauses count after E-Reduction: 3864
c
c Input Parameter (command line, file):
c input filename QBFLIB/MayerEichberger-Saffidine/PositionalGames_hex/hex_rand_5x5-6m-8.qdimacs
c output filename /tmp/dcnfAutarky.dimacs
c autarky level 1
c conformity level 0
c encoding type 2
c no.of var 1259
c no.of clauses 3878
c no.of taut cls 0
c
c Output Parameters:
c remaining no.of clauses 3864
c
c QBFLIB/MayerEichberger-Saffidine/PositionalGames_hex/hex_rand_5x5-6m-8.qdimacs 1259 3878 E1 [343 344 345 346 347 736 773 810 847 884 921 958 995 1032] 0 171 1074 3864 RED
|
meansArray <- vector('numeric')
for(i in 1:100){
system ("java -Xint Lab data1.txt result1.txt 600")
data1 <- read.csv('result1.txt')
data1 <- data1[100:nrow(data1),2]
meansArray <- c(meansArray,mean(data1))
}
meanOfMean <- mean(meansArray)
ci1 <-confidenceInterval(meansArray)
print(meanOfMean)
|
/R-workspace/Lab 5/meanNConfidenceScript.R
|
no_license
|
mcfr3d/EDAA35-Utv-rdering-av-programvarusystem
|
R
| false
| false
| 301
|
r
|
meansArray <- vector('numeric')
for(i in 1:100){
system ("java -Xint Lab data1.txt result1.txt 600")
data1 <- read.csv('result1.txt')
data1 <- data1[100:nrow(data1),2]
meansArray <- c(meansArray,mean(data1))
}
meanOfMean <- mean(meansArray)
ci1 <-confidenceInterval(meansArray)
print(meanOfMean)
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/grmCAT.R
\name{grmCAT}
\alias{grmCAT}
\title{Computerized Adaptive Testing Graded Response Model}
\usage{
grmCAT(data, object = NULL, ...)
}
\arguments{
\item{data}{a \code{data.frame} or a numeric \code{matrix} of manifest variables.}
\item{object}{an object of class \code{CATsurv} to be populated. If omitted, a new object of class \code{CATsurv} is created.}
\item{...}{arguments to be passed to methods. For more details about the arguments, see \code{\link{grm}}.}
}
\value{
An object of class \code{CATsurv} with components,
\itemize{
\item \code{difficulty} a named list of difficulty parameters for use with polytomous questions/items. Each element's name tells the question/item to which it applies.
\item \code{guessing} a vector of guessing parameter for each question/item.
\item \code{discrimination} a vector of disrimination parameter for each question/item.
\item \code{answers} a vector of answers to questions as given by the survey respondent.
\item \code{priorName} a character vector of length one giving the prior distribution to use for the latent trait estimates. The options are \code{normal} for the normal distirbution, \code{cauchy} for the Cauchy distribution, are \code{t} for the t-distribution. Defaults to \code{normal}.
\item \code{priorParams} a numeric vector of parameters for the distribution specified in the \code{priorName} slot. See the details section for more infomration. Defaults to \code{c(0,1)}.
}
}
\description{
This function fits the Graded Response model for ordinal polytomous data and populates the fitted values for discimination and difficulty parameters to an object of class \code{CATsurv}.
}
\note{
In case the Hessian matrix at convergence is not positive definite try to use \code{start.val="random"}.
}
\author{
Josh W. Cutler: \email{josh@zistle.com} and Jacob M. Montgomery: \email{jacob.montgomery@wustl.edu}
}
\seealso{
\code{\link{ltmCAT}},\code{\link{nextItem}}, \code{\link{question.path}}
}
|
/catSurv/man/grmCAT.Rd
|
no_license
|
drmiller1220/CATSurv
|
R
| false
| false
| 2,054
|
rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/grmCAT.R
\name{grmCAT}
\alias{grmCAT}
\title{Computerized Adaptive Testing Graded Response Model}
\usage{
grmCAT(data, object = NULL, ...)
}
\arguments{
\item{data}{a \code{data.frame} or a numeric \code{matrix} of manifest variables.}
\item{object}{an object of class \code{CATsurv} to be populated. If omitted, a new object of class \code{CATsurv} is created.}
\item{...}{arguments to be passed to methods. For more details about the arguments, see \code{\link{grm}}.}
}
\value{
An object of class \code{CATsurv} with components,
\itemize{
\item \code{difficulty} a named list of difficulty parameters for use with polytomous questions/items. Each element's name tells the question/item to which it applies.
\item \code{guessing} a vector of guessing parameter for each question/item.
\item \code{discrimination} a vector of disrimination parameter for each question/item.
\item \code{answers} a vector of answers to questions as given by the survey respondent.
\item \code{priorName} a character vector of length one giving the prior distribution to use for the latent trait estimates. The options are \code{normal} for the normal distirbution, \code{cauchy} for the Cauchy distribution, are \code{t} for the t-distribution. Defaults to \code{normal}.
\item \code{priorParams} a numeric vector of parameters for the distribution specified in the \code{priorName} slot. See the details section for more infomration. Defaults to \code{c(0,1)}.
}
}
\description{
This function fits the Graded Response model for ordinal polytomous data and populates the fitted values for discimination and difficulty parameters to an object of class \code{CATsurv}.
}
\note{
In case the Hessian matrix at convergence is not positive definite try to use \code{start.val="random"}.
}
\author{
Josh W. Cutler: \email{josh@zistle.com} and Jacob M. Montgomery: \email{jacob.montgomery@wustl.edu}
}
\seealso{
\code{\link{ltmCAT}},\code{\link{nextItem}}, \code{\link{question.path}}
}
|
devtools::load_all()
devtools::document()
devtools::build(binary = TRUE)
|
/previous_work/package_dev.R
|
no_license
|
ethanwhite/LDATS
|
R
| false
| false
| 73
|
r
|
devtools::load_all()
devtools::document()
devtools::build(binary = TRUE)
|
library(testthat)
library(covid19India)
test_check("covid19India")
|
/tests/testthat.R
|
permissive
|
shubhrampandey/covid19India
|
R
| false
| false
| 68
|
r
|
library(testthat)
library(covid19India)
test_check("covid19India")
|
############### SESYNC Research Support: Fisheries and food security ##########
## Importing and processing data from survey for the fisheries project at SESYNC.
##
## DATE CREATED: 06/06/2017
## DATE MODIFIED: 04/24/2018
## AUTHORS: Benoit Parmentier
## PROJECT: Garden Wealth (urban garden)
## ISSUE:
## TO DO:
##
## COMMIT: initial commit gDistance example
##
## Links to investigate:
###################################################
#
###### Library used
library(gtools) # loading some useful tools
library(sp) # Spatial pacakge with class definition by Bivand et al.
library(spdep) # Spatial pacakge with methods and spatial stat. by Bivand et al.
library(rgdal) # GDAL wrapper for R, spatial utilities
library(raster)
library(gdata) # various tools with xls reading, cbindX
library(rasterVis) # Raster plotting functions
library(parallel) # Parallelization of processes with multiple cores
library(maptools) # Tools and functions for sp and other spatial objects e.g. spCbind
library(maps) # Tools and data for spatial/geographic objects
library(plyr) # Various tools including rbind.fill
library(spgwr) # GWR method
library(rgeos) # Geometric, topologic library of functions
library(gridExtra) # Combining lattice plots
library(colorRamps) # Palette/color ramps for symbology
library(ggplot2)
library(lubridate)
library(dplyr)
library(rowr) # Contains cbind.fill
library(car)
library(sf)
library(gdistance)
library(rgrass7)
###### Functions used in this script and sourced from other files
create_dir_fun <- function(outDir,out_suffix=NULL){
#if out_suffix is not null then append out_suffix string
if(!is.null(out_suffix)){
out_name <- paste("output_",out_suffix,sep="")
outDir <- file.path(outDir,out_name)
}
#create if does not exists
if(!file.exists(outDir)){
dir.create(outDir)
}
return(outDir)
}
#Used to load RData object saved within the functions produced.
load_obj <- function(f){
env <- new.env()
nm <- load(f, env)[1]
env[[nm]]
}
### Other functions ####
#function_processing_data <- ".R" #PARAM 1
#script_path <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/scripts" #path to script #PARAM
#source(file.path(script_path,function_processing_data)) #source all functions used in this script 1.
############################################################################
##### Parameters and argument set up ###########
out_suffix <- "connectivity_example_04242018" #output suffix for the files and ouptut folder #param 12
in_dir <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/data_urban_garden"
out_dir <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/outputs"
in_dir_grass <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/data_urban_garden"
#in_dir_grass <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/grass_data_urban_garden"
# background reading:
# https://grass.osgeo.org/grass72/manuals/grass_database.html
gisBase <- '/usr/lib/grass72'
#gisDbase <- '/nfs/urbangi-data/grassdata'
gisDbase <- in_dir_grass #should be the same as in_dir
#location <- 'DEM_LiDAR_1ft_2010_Improved_NYC_int'
location <- 'NYC_example'
location <- 'connectivy_example'
file_format <- ".tif" #PARAM5
NA_flag_val <- -9999 #PARAM7
out_suffix <-"ny_example_04232018" #output suffix for the files and ouptu folder #PARAM 8
create_out_dir_param=TRUE #PARAM9
############## START SCRIPT ############################
######### PART 0: Set up the output dir ################
if(is.null(out_dir)){
out_dir <- in_dir #output will be created in the input dir
}
#out_dir <- in_dir #output will be created in the input dir
out_suffix_s <- out_suffix #can modify name of output suffix
if(create_out_dir_param==TRUE){
out_dir <- create_dir_fun(out_dir,out_suffix)
setwd(out_dir)
}else{
setwd(out_dir) #use previoulsy defined directory
}
mapset <- "nyc_site_test"
# initialize a mapset for watershed estimation results
initGRASS(gisBase = gisBase, #application location
gisDbase = gisDbase, #database dir
location = location, #grass location
mapset = mapset, # grass mapset
override = TRUE
)
### PART I READ AND PREPARE DATA #######
#set up the working directory
#Create output directory
###################### PART 2: compare with GRASS for random walk ###########
#### Hiking example
r <- raster(system.file("external/maungawhau.grd", package="gdistance"))
plot(r)
#The Hiking Function requires the slope (m) as input, which can be calculated from the altitude
#(z) and distance between cell centres (d).
#mij = (zj − zi)/dij
#The units of altitude and distance should be identical. Here, we use meters for both. First, we
#calculate the altitudinal differences between cells. Then we use the geoCorrection function
#to divide by the distance between cells.
altDiff <- function(x){x[2] - x[1]}
hd <- transition(r, altDiff, 8, symm=FALSE)
slope <- geoCorrection(hd)
plot(raster(slope))
adj <- adjacent(r, cells=1:ncell(r), pairs=TRUE, directions=8)
speed <- slope
speed[adj] <- 6 * exp(-3.5 * abs(slope[adj] + 0.05)) #Tobbler Hiking function
Conductance <- geoCorrection(speed)
plot(raster(Conductance))
##### Generate Nodes:
### Add a point
A <- c(2667670, 6479000)
B <- c(2667800, 6479400)
C <- c(2667899,6478800)
net2_sp <- SpatialPoints(rbind(A,B,C))
plot(r, xlab="x coordinate (m)", ylab="y coordinate (m)",legend.lab="Altitude (masl)")
plot(net2_sp,add=T)
test <- shortestPath(Conductance, net2_sp, net2_sp, output="SpatialLines")
class(test)
plot(r)
plot(test,add=T)
dist_test <- distance(r,net2_sp)
dist_test <- distanceFromPoints(r,net2_sp)
##### Shortest path
AtoB <- shortestPath(Conductance, A, B, output="SpatialLines")
BtoA <- shortestPath(Conductance, B, A, output="SpatialLines")
#Add new path/route
BtoC <- shortestPath(Conductance, B, C, output="SpatialLines")
CtoB <- shortestPath(Conductance, B, C, output="SpatialLines")
#Add new path/route
AtoC <- shortestPath(Conductance, A, C, output="SpatialLines")
CtoA <- shortestPath(Conductance, C, A, output="SpatialLines")
##### Random walk: commute distance
altDiff <- function(x){x[2] - x[1]}
hd <- transition(r, altDiff, 8, symm=FALSE)
#Create a Transition object from the raster
tr <- transition(r,function(x) 1/mean(x),8)
test_path <- commuteDistance(tr,net2_sp)
plot(net2_sp)
net2_sf <- as(net2_sp,"sf")
plot(net2_sf$geometry)
#View(net2_sf)
net2_sf$ID <- 1:nrow(net2_sf)
node_1_sf <- subset(net2_sf,ID==1)
plot(node_1_sf$geometry,add=T)
st_write(net2_sf,"network_nodes.shp",delete_layer = T)
writeRaster(r,"r_surf.tif")
#### Add GRASS code here:
execGRASS("v.in.ogr",flags = c("o","overwrite"),
input="network_nodes.shp",
output="nodes_origin")
execGRASS("r.in.gdal",flags=c("o","overwrite"),
input="r_surf.tif",
output="r_surf")
system("r.info r_surf")
r #check we have the same res, etc.
#### Set region extent and resolution first
system("g.region -p") #Exaine current region properties
#system("g.region -p") #Exaine current region properties
system("g.region rast=r_surf")
system("g.region -p")
system("v.to.rast --overwrite input=nodes_origin use=attr output=nodes_origin_surf attribute_column=ID")
system("r.info nodes_origin_surf")
system("r.mapcalc 'r_friction = 1'") #creates a raster with value 1
system("r.info r_friction")
# compute cumulative cost surfaces
system("r.walk -k elev=r_surf friction=r_friction output=walk.cost start_points=nodes_origin stop_points=nodes_origin lambda=1")
#system("r.walk -k elev=r_surf friction=r_friction output=walk.cost start_points=nodes_origin stop_points=nodes_origin lambda=1")
execGRASS("r.cost", flags=c("k","overwrite"),
input="r_surf",
output="r_surf_cost",
outdir="r_surf_direction",
start_raster="nodes_origin_surf")
# compute shortest path from start to end points
#execGRASS()
#system("r.drain in=walk.cost out=walk.drain vector_points=end")
system("r.drain input=walk.cost output=walk.drain vector_points=nodes_origin")
system("r.drain input=r_surf_cost output=cost_drain vector_points=nodes_origin")
system("r.out.gdal input=walk.drain output=path_r_walk.tif")
system("r.out.gdal input=walk.cost output=walk_cost.tif")
system("r.out.gdal input=cost_drain output=cost_drain.tif")
r_path_walk <- raster("path_r_walk.tif")
r_walk_cost <- raster("walk_cost.tif")
r_cost_drain <- raster("cost_drain.tif")
plot(r_path_walk)
plot(r_walk_cost)
plot(r_cost_drain)
#### Test random walk
#execGRASS("r.randomwalk",flags=c("o","overwrite"),
# elevation="r_surf",
# releasemp="nodes_origin_surf",
# output="r_surf")
#r.randomwalk help
#r.randomwalk [-abkmnpqsvx] prefix=string [cores=integer] [cellsize=float]
#[aoicoords=float,...][aoimap=name] elevation=name [releasefile=string]
#[caserules=integer,integer,...] [releasemap=name] [depositmap=name]
#[impactmap=name] [probmap=name] [scoremap=name] [impactobjects=name]
#[objectscores=string] models=string mparams=string [sampling=integer]
#[retain=float] [functype=integer] [backfile=string] [cdffile=string]
#[zonalfile=string] [profile=float,...] [--verbose] [--quiet]
###################### END OF SCRIPT ################
|
/connectivity_and_resistance_surface_example.R
|
no_license
|
bparment1/cost_and_resistance_surface_analyses
|
R
| false
| false
| 9,659
|
r
|
############### SESYNC Research Support: Fisheries and food security ##########
## Importing and processing data from survey for the fisheries project at SESYNC.
##
## DATE CREATED: 06/06/2017
## DATE MODIFIED: 04/24/2018
## AUTHORS: Benoit Parmentier
## PROJECT: Garden Wealth (urban garden)
## ISSUE:
## TO DO:
##
## COMMIT: initial commit gDistance example
##
## Links to investigate:
###################################################
#
###### Library used
library(gtools) # loading some useful tools
library(sp) # Spatial pacakge with class definition by Bivand et al.
library(spdep) # Spatial pacakge with methods and spatial stat. by Bivand et al.
library(rgdal) # GDAL wrapper for R, spatial utilities
library(raster)
library(gdata) # various tools with xls reading, cbindX
library(rasterVis) # Raster plotting functions
library(parallel) # Parallelization of processes with multiple cores
library(maptools) # Tools and functions for sp and other spatial objects e.g. spCbind
library(maps) # Tools and data for spatial/geographic objects
library(plyr) # Various tools including rbind.fill
library(spgwr) # GWR method
library(rgeos) # Geometric, topologic library of functions
library(gridExtra) # Combining lattice plots
library(colorRamps) # Palette/color ramps for symbology
library(ggplot2)
library(lubridate)
library(dplyr)
library(rowr) # Contains cbind.fill
library(car)
library(sf)
library(gdistance)
library(rgrass7)
###### Functions used in this script and sourced from other files
create_dir_fun <- function(outDir,out_suffix=NULL){
#if out_suffix is not null then append out_suffix string
if(!is.null(out_suffix)){
out_name <- paste("output_",out_suffix,sep="")
outDir <- file.path(outDir,out_name)
}
#create if does not exists
if(!file.exists(outDir)){
dir.create(outDir)
}
return(outDir)
}
#Used to load RData object saved within the functions produced.
load_obj <- function(f){
env <- new.env()
nm <- load(f, env)[1]
env[[nm]]
}
### Other functions ####
#function_processing_data <- ".R" #PARAM 1
#script_path <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/scripts" #path to script #PARAM
#source(file.path(script_path,function_processing_data)) #source all functions used in this script 1.
############################################################################
##### Parameters and argument set up ###########
out_suffix <- "connectivity_example_04242018" #output suffix for the files and ouptut folder #param 12
in_dir <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/data_urban_garden"
out_dir <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/outputs"
in_dir_grass <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/data_urban_garden"
#in_dir_grass <- "/nfs/bparmentier-data/Data/projects/urban_garden_pursuit/grass_data_urban_garden"
# background reading:
# https://grass.osgeo.org/grass72/manuals/grass_database.html
gisBase <- '/usr/lib/grass72'
#gisDbase <- '/nfs/urbangi-data/grassdata'
gisDbase <- in_dir_grass #should be the same as in_dir
#location <- 'DEM_LiDAR_1ft_2010_Improved_NYC_int'
location <- 'NYC_example'
location <- 'connectivy_example'
file_format <- ".tif" #PARAM5
NA_flag_val <- -9999 #PARAM7
out_suffix <-"ny_example_04232018" #output suffix for the files and ouptu folder #PARAM 8
create_out_dir_param=TRUE #PARAM9
############## START SCRIPT ############################
######### PART 0: Set up the output dir ################
if(is.null(out_dir)){
out_dir <- in_dir #output will be created in the input dir
}
#out_dir <- in_dir #output will be created in the input dir
out_suffix_s <- out_suffix #can modify name of output suffix
if(create_out_dir_param==TRUE){
out_dir <- create_dir_fun(out_dir,out_suffix)
setwd(out_dir)
}else{
setwd(out_dir) #use previoulsy defined directory
}
mapset <- "nyc_site_test"
# initialize a mapset for watershed estimation results
initGRASS(gisBase = gisBase, #application location
gisDbase = gisDbase, #database dir
location = location, #grass location
mapset = mapset, # grass mapset
override = TRUE
)
### PART I READ AND PREPARE DATA #######
#set up the working directory
#Create output directory
###################### PART 2: compare with GRASS for random walk ###########
#### Hiking example
r <- raster(system.file("external/maungawhau.grd", package="gdistance"))
plot(r)
#The Hiking Function requires the slope (m) as input, which can be calculated from the altitude
#(z) and distance between cell centres (d).
#mij = (zj − zi)/dij
#The units of altitude and distance should be identical. Here, we use meters for both. First, we
#calculate the altitudinal differences between cells. Then we use the geoCorrection function
#to divide by the distance between cells.
altDiff <- function(x){x[2] - x[1]}
hd <- transition(r, altDiff, 8, symm=FALSE)
slope <- geoCorrection(hd)
plot(raster(slope))
adj <- adjacent(r, cells=1:ncell(r), pairs=TRUE, directions=8)
speed <- slope
speed[adj] <- 6 * exp(-3.5 * abs(slope[adj] + 0.05)) #Tobbler Hiking function
Conductance <- geoCorrection(speed)
plot(raster(Conductance))
##### Generate Nodes:
### Add a point
A <- c(2667670, 6479000)
B <- c(2667800, 6479400)
C <- c(2667899,6478800)
net2_sp <- SpatialPoints(rbind(A,B,C))
plot(r, xlab="x coordinate (m)", ylab="y coordinate (m)",legend.lab="Altitude (masl)")
plot(net2_sp,add=T)
test <- shortestPath(Conductance, net2_sp, net2_sp, output="SpatialLines")
class(test)
plot(r)
plot(test,add=T)
dist_test <- distance(r,net2_sp)
dist_test <- distanceFromPoints(r,net2_sp)
##### Shortest path
AtoB <- shortestPath(Conductance, A, B, output="SpatialLines")
BtoA <- shortestPath(Conductance, B, A, output="SpatialLines")
#Add new path/route
BtoC <- shortestPath(Conductance, B, C, output="SpatialLines")
CtoB <- shortestPath(Conductance, B, C, output="SpatialLines")
#Add new path/route
AtoC <- shortestPath(Conductance, A, C, output="SpatialLines")
CtoA <- shortestPath(Conductance, C, A, output="SpatialLines")
##### Random walk: commute distance
altDiff <- function(x){x[2] - x[1]}
hd <- transition(r, altDiff, 8, symm=FALSE)
#Create a Transition object from the raster
tr <- transition(r,function(x) 1/mean(x),8)
test_path <- commuteDistance(tr,net2_sp)
plot(net2_sp)
net2_sf <- as(net2_sp,"sf")
plot(net2_sf$geometry)
#View(net2_sf)
net2_sf$ID <- 1:nrow(net2_sf)
node_1_sf <- subset(net2_sf,ID==1)
plot(node_1_sf$geometry,add=T)
st_write(net2_sf,"network_nodes.shp",delete_layer = T)
writeRaster(r,"r_surf.tif")
#### Add GRASS code here:
execGRASS("v.in.ogr",flags = c("o","overwrite"),
input="network_nodes.shp",
output="nodes_origin")
execGRASS("r.in.gdal",flags=c("o","overwrite"),
input="r_surf.tif",
output="r_surf")
system("r.info r_surf")
r #check we have the same res, etc.
#### Set region extent and resolution first
system("g.region -p") #Exaine current region properties
#system("g.region -p") #Exaine current region properties
system("g.region rast=r_surf")
system("g.region -p")
system("v.to.rast --overwrite input=nodes_origin use=attr output=nodes_origin_surf attribute_column=ID")
system("r.info nodes_origin_surf")
system("r.mapcalc 'r_friction = 1'") #creates a raster with value 1
system("r.info r_friction")
# compute cumulative cost surfaces
system("r.walk -k elev=r_surf friction=r_friction output=walk.cost start_points=nodes_origin stop_points=nodes_origin lambda=1")
#system("r.walk -k elev=r_surf friction=r_friction output=walk.cost start_points=nodes_origin stop_points=nodes_origin lambda=1")
execGRASS("r.cost", flags=c("k","overwrite"),
input="r_surf",
output="r_surf_cost",
outdir="r_surf_direction",
start_raster="nodes_origin_surf")
# compute shortest path from start to end points
#execGRASS()
#system("r.drain in=walk.cost out=walk.drain vector_points=end")
system("r.drain input=walk.cost output=walk.drain vector_points=nodes_origin")
system("r.drain input=r_surf_cost output=cost_drain vector_points=nodes_origin")
system("r.out.gdal input=walk.drain output=path_r_walk.tif")
system("r.out.gdal input=walk.cost output=walk_cost.tif")
system("r.out.gdal input=cost_drain output=cost_drain.tif")
r_path_walk <- raster("path_r_walk.tif")
r_walk_cost <- raster("walk_cost.tif")
r_cost_drain <- raster("cost_drain.tif")
plot(r_path_walk)
plot(r_walk_cost)
plot(r_cost_drain)
#### Test random walk
#execGRASS("r.randomwalk",flags=c("o","overwrite"),
# elevation="r_surf",
# releasemp="nodes_origin_surf",
# output="r_surf")
#r.randomwalk help
#r.randomwalk [-abkmnpqsvx] prefix=string [cores=integer] [cellsize=float]
#[aoicoords=float,...][aoimap=name] elevation=name [releasefile=string]
#[caserules=integer,integer,...] [releasemap=name] [depositmap=name]
#[impactmap=name] [probmap=name] [scoremap=name] [impactobjects=name]
#[objectscores=string] models=string mparams=string [sampling=integer]
#[retain=float] [functype=integer] [backfile=string] [cdffile=string]
#[zonalfile=string] [profile=float,...] [--verbose] [--quiet]
###################### END OF SCRIPT ################
|
/fundflow and risktaking/09-netflow大小于0.R
|
no_license
|
shenfan2018/shenfan2018
|
R
| false
| false
| 2,995
|
r
| ||
all_aes <- function(geom, n, .values) {
list(
required = if (n == 1) "x" else c("x", "y"),
optional_class = .values$plot$GEOM_CLASS_OPTIONAL_AES[[geom_class(geom, .values)]],
optional_geom = c(
filter(.values$plot$GEOM, name == !!geom)$optional[[1]],
.values$plot$ALWAYS_OPTIONAL
)
)
}
aes_class <- function(aes, .values) {
if (!aes %in% names(.values$plot$AES_CLASSES)) print(paste(aes, "is missing in .values$plot$AES_CLASSES"))
.values$plot$AES_CLASSES[aes]
}
helper_aes_geom_allowed <- function(geom, .values) {
row <- dplyr::filter(.values$plot$GEOM, name == !!geom)
c(x = row$allowed_x, y = row$allowed_y)
}
|
/modules/Operations/Plot/Aes/helper.R
|
no_license
|
DavidBarke/shinyplyr
|
R
| false
| false
| 658
|
r
|
all_aes <- function(geom, n, .values) {
list(
required = if (n == 1) "x" else c("x", "y"),
optional_class = .values$plot$GEOM_CLASS_OPTIONAL_AES[[geom_class(geom, .values)]],
optional_geom = c(
filter(.values$plot$GEOM, name == !!geom)$optional[[1]],
.values$plot$ALWAYS_OPTIONAL
)
)
}
aes_class <- function(aes, .values) {
if (!aes %in% names(.values$plot$AES_CLASSES)) print(paste(aes, "is missing in .values$plot$AES_CLASSES"))
.values$plot$AES_CLASSES[aes]
}
helper_aes_geom_allowed <- function(geom, .values) {
row <- dplyr::filter(.values$plot$GEOM, name == !!geom)
c(x = row$allowed_x, y = row$allowed_y)
}
|
#plot2
# Download data file 'household_power_consumption.zip' from:
# https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
# and unzip in working directory
setClass("CDate")
setAs("character","CDate", function(from) as.Date(from, format="%d/%m/%Y") )
data <- read.csv("household_power_consumption.txt",colClasses = c("CDate","character",rep("numeric",7)) ,sep=";",na.strings="?")
ss = subset(data, Date >= as.Date("2007-02-01") & Date <= as.Date("2007-02-02"))
ss$DateTime <- as.POSIXlt(paste(ss$Date, ss$Time," "))
png(filename = "plot2.png",
width = 480, height = 480, units = "px", pointsize = 12,
bg = "white", res = NA,
type = "cairo")
plot(ss$DateTime,ss$Global_active_power,type="l",ylab="Global Active Power (kilowatts)",xlab="")
box()
dev.off()
|
/plot2.R
|
no_license
|
mmaul/ExData_Plotting1
|
R
| false
| false
| 804
|
r
|
#plot2
# Download data file 'household_power_consumption.zip' from:
# https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
# and unzip in working directory
setClass("CDate")
setAs("character","CDate", function(from) as.Date(from, format="%d/%m/%Y") )
data <- read.csv("household_power_consumption.txt",colClasses = c("CDate","character",rep("numeric",7)) ,sep=";",na.strings="?")
ss = subset(data, Date >= as.Date("2007-02-01") & Date <= as.Date("2007-02-02"))
ss$DateTime <- as.POSIXlt(paste(ss$Date, ss$Time," "))
png(filename = "plot2.png",
width = 480, height = 480, units = "px", pointsize = 12,
bg = "white", res = NA,
type = "cairo")
plot(ss$DateTime,ss$Global_active_power,type="l",ylab="Global Active Power (kilowatts)",xlab="")
box()
dev.off()
|
library(tidyverse)
library(dynwrap)
library(dynutils)
library(furrr)
source("data-raw/1a-helper_functions.R")
files <- list.files("../methods/", pattern = "Dockerfile", recursive = TRUE, full.names = TRUE)
# iterate over the containers and generate R scripts for each of them
# this loads in the current version from the version files
definitions <-
map(files, function(file) {
cat(file, "\n", sep = "")
definition <- create_ti_method_definition(definition = str_replace(file, "Dockerfile", "definition.yml"), script = NULL, return_function = FALSE)
version <-
system(paste0(
"cd ", str_replace(file, "Dockerfile", ""), "; ",
read_lines(str_replace(file, "Dockerfile", "version")), "; ",
"echo $VERSION"
), intern = TRUE)
# generate file from definition
generate_file_from_container(definition, version)
definition$version <- version
# return the definition
definition
})
methods <- dynutils::list_as_tibble(definitions)
for (n in rev(c("method", "wrapper", "container", "manuscript"))) {
cat("Processing ", n, "\n", sep = "")
newtib <-
methods[[n]] %>%
map(function(x) { if (is.list(x)) x else list() }) %>%
list_as_tibble()
newtib[[".object_class"]] <- NULL
colnames(newtib) <- paste0(n, "_", colnames(newtib))
methods <- bind_cols(newtib, methods)
methods[[n]] <- NULL
}
methods[c(".object_class", "run")] <- NULL
usethis::use_data(methods, overwrite = TRUE)
# don't forget to regenerate the documentation
devtools::document()
devtools::install(dependencies = FALSE)
|
/data-raw/1-generate_r_code_from_containers.R
|
no_license
|
zorrodong/dynmethods
|
R
| false
| false
| 1,578
|
r
|
library(tidyverse)
library(dynwrap)
library(dynutils)
library(furrr)
source("data-raw/1a-helper_functions.R")
files <- list.files("../methods/", pattern = "Dockerfile", recursive = TRUE, full.names = TRUE)
# iterate over the containers and generate R scripts for each of them
# this loads in the current version from the version files
definitions <-
map(files, function(file) {
cat(file, "\n", sep = "")
definition <- create_ti_method_definition(definition = str_replace(file, "Dockerfile", "definition.yml"), script = NULL, return_function = FALSE)
version <-
system(paste0(
"cd ", str_replace(file, "Dockerfile", ""), "; ",
read_lines(str_replace(file, "Dockerfile", "version")), "; ",
"echo $VERSION"
), intern = TRUE)
# generate file from definition
generate_file_from_container(definition, version)
definition$version <- version
# return the definition
definition
})
methods <- dynutils::list_as_tibble(definitions)
for (n in rev(c("method", "wrapper", "container", "manuscript"))) {
cat("Processing ", n, "\n", sep = "")
newtib <-
methods[[n]] %>%
map(function(x) { if (is.list(x)) x else list() }) %>%
list_as_tibble()
newtib[[".object_class"]] <- NULL
colnames(newtib) <- paste0(n, "_", colnames(newtib))
methods <- bind_cols(newtib, methods)
methods[[n]] <- NULL
}
methods[c(".object_class", "run")] <- NULL
usethis::use_data(methods, overwrite = TRUE)
# don't forget to regenerate the documentation
devtools::document()
devtools::install(dependencies = FALSE)
|
\name{sellStock}
\alias{sellStock}
\title{Sell Stocks over a fix connection}
\usage{
sellStock(ticker, price, quantity)
}
\arguments{
\item{ticker}{A string representing the ticker of the security}
\item{price}{A double value representing the price}
\item{quantity}{ A double value representing the quantity }
}
\value{
Nonde
}
\description{
It executes a Sell Order on fix connection. For now, it assumes that a FIX server on the local machine
with a server config that is provided in the package
}
\examples{
sellStock("MSFT", 10, 10)
getPortfolio()
# "MSFT,10,10"
}
|
/man/sellStock.Rd
|
no_license
|
arrebagrove/FIX
|
R
| false
| false
| 577
|
rd
|
\name{sellStock}
\alias{sellStock}
\title{Sell Stocks over a fix connection}
\usage{
sellStock(ticker, price, quantity)
}
\arguments{
\item{ticker}{A string representing the ticker of the security}
\item{price}{A double value representing the price}
\item{quantity}{ A double value representing the quantity }
}
\value{
Nonde
}
\description{
It executes a Sell Order on fix connection. For now, it assumes that a FIX server on the local machine
with a server config that is provided in the package
}
\examples{
sellStock("MSFT", 10, 10)
getPortfolio()
# "MSFT,10,10"
}
|
## Copyright (C) 2012, 2013 Bitergia
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##
## This file is a part of the vizGrimoire.R package
## http://vizgrimoire.bitergia.org/
##
##
## Authors:
## Marina Doria Garcia de Cortazar <marina@bitergia.com>
## Daniel Izquierdo Cortazar <dizquierdo@bitergia.com>
##
## Usage:
## R --vanilla --args -d dbname -u dbuser -p dbpassword -v dverbose < validator_dbstatus.R
##
library(optparse)
library(DBI)
library(RMySQL)
ConfFromOptParse <- function () {
option_list <- list(
make_option(c("-d", "--database"), dest="database",
help="Database with data"),
make_option(c("-u", "--dbuser"), dest="dbuser",
help="Database user", default="root"),
make_option(c("-p", "--dbpassword"), dest="dbpassword",
help="Database user password", default=""),
make_option(c("-t", "--dbtype"), dest="dbtype",
help="Type of database; scm, mls, its"),
make_option(c("-v", "--verbose"), dest="dverbose",
help="Option to show more information (yes/no) ", default="no")
)
parser <- OptionParser(usage = "%prog [options]", option_list = option_list)
options <- parse_args(parser)
if (is.null(options$database)) {
print_help(parser)
stop("Database param is required")
}
return(options)
}
#---
conf <- ConfFromOptParse()
print(conf)
con <- dbConnect(MySQL(), dbname = conf$database, user = conf$dbuser, password = conf$dbpassword)
query<-paste("show tables")
rs<-dbSendQuery(con, query)
all<-c()
rows<-c()
tables<-fetch(rs,n=-1)
colnames(tables)<-"names"
for( i in 1:nrow(tables))
{
query2<-paste("select count(*) from",tables[i,])
rs2<-dbSendQuery(con, query2)
total<-fetch(rs2,n=-1)
colnames(total)<-paste("total row",tables[i,])
rows<-c(rows,total)
i<-i+1
}
trow<-matrix(rows)
totalr<-data.frame(trow)
table_row<-data.frame(totalr,tables)
colnames(table_row)<-c("rows","names")
#This function classified core and optional tables with number of rows.
Control<-function()
{
i<-0
cores<-NULL
ops<-NULL
errs<-NULL
cat("\n TABLES ANALYSIS:\n ")
for(i in 1:nrow(table_row))
{
if (is.element(table_row$names[i], core)){
co<-paste(table_row$names[i],table_row$rows[i])
cores<-c(cores,co)
i<-i+1
}
else if (is.element(table_row$names[i], optional)){
op<-paste(table_row$names[i],table_row$rows[i])
ops<-c(ops,op)
i<-i+1
}
else {
er<-paste("error; table unidentified:",table_row$names[i])
errs<-c(errs,er)
i<-i+1
}
}
x<-paste(" CORE TABLE", cores)
print(x)
y<-paste(" OPTIONAL TABLE",ops)
print(y)
print(errs)
}
Compare<-function(table1,table2,value1,value2)
{
#This function compares number of rows between pair of tables
#table1=Table to compare ; value1=pk in table1 linking with the other table.
#table2=Table to compare ; value2=pk in table2 linking with the other table.
query<-paste("select count(", table1,".",value1,")",
" from ",table1,
" where ", table1,".",value1," not in (select distinct(",table2,".",value2,") from ",table2,")", sep="")
rs<-dbSendQuery(con, query)
missrow<-fetch(rs,n=-1)
comp<-paste("Total missing values=",missrow)
print(comp)
}
Errors<-function(put,table,colum)
#This function finds strings values in a given field.
#put: value to find
#table: data.frame
#colum:field in table.
{ query<-paste("select * from",table)
rs<-dbSendQuery(con, query)
tables<-fetch(rs,n=-1)
error<-grep(put,tables[[colum]])
total_error<-length(error)
total_error<-paste("Total error:", total_error)
print(total_error)
if(conf$dverbose=="yes")
{
print("IN ROWS:")
print(error)
}
#visual<-tables[[colum]][error]
#print("LOOK ERRORS")
#print(visual)
return(error)
}
if(conf$dbtype=="scm")#SPECIAL VALIDATOR FOR SCM
{
core<-c("actions","branches","file_copies","file_links","files","people","repositories","scmlog","tag_revisions","tags")
optional<-c("action_files","actions_file_names","commits_lines","companies","companies_all","extra", "file_types","identities", "months","people_upeople","upeople","upeople_companies","weeks")
Control()
cat("\n PART 1: POSSIBLE ERRORS \n")
print(" 1.1.Table=PEOPLE Field=name")
print(" 1. ERROR; @")
error_name1<-Errors("@","people","name")
print(" 2. ERROR; root")
people_name2<-Errors("root","people","name")
print(" 3. ERROR; bot")
people_name3<-Errors("bot","people","name")
print(" 1.2.Table=PEOPLE Field=email")
print(" 1. ERROR; root")
people_email1<-Errors("root","people","email")
print(" 2. ERROR; bot")
people_email2<-Errors("bot","people","email")
print(" 3. ERROR; miss value")
miss_people_email<-Errors("^$|^( +)$", "people", "email")
print(" 1.3. Table=EXTRA Field=site")
print(" 1. ERROR; miss value")
miss_extra_site<-Errors("^$|^( +)$", "extra", "site")
cat("\n PART 2: TABLES COMPARISON ; DIF BETWEEN ROWS \n")
print(" 2.1 From SCMLOG author_id to PEOPLE id")
compare1<-Compare("scmlog","people","author_id","id")
print(" 2.2 From SCMLOG commiter_id to PEOPLE id")
compare2<-Compare("scmlog","people","committer_id","id")
print(" 2.3 From PEOPLE id to PEOPLE_UPEOPLE people_id")
compare3<-Compare("people","people_upeople","id","people_id")
print(" 2.4 From PEOPLE_UPEOPLE people_id to UPEOPLE upeople_id")
compare4<-Compare("people_upeople","upeople","people_id","id")
print(" 2.5 From UPEOPLE upeople_id to UPEOPLE_COMPANIES upeople_id")
compare5<-Compare("upeople","upeople_companies","id","upeople_id")
######NUMERICAL ANALYSIS
cat("\n NUMERICAL ANALYSIS \n")
cat("\n PART 1: STATIC DATA SUMMARY \n")
print("1.1. BY PEOPLE")
query<-paste("select people_upeople.people_id as id_people,
scmlog.id as total_commits,
commits_lines.added as total_added,
commits_lines.removed as total_removed,
companies.name as company
from commits_lines,
companies, scmlog, people, people_upeople, upeople, upeople_companies
where commits_lines.commit_id=scmlog.id
and scmlog.author_id=people.id
and people.id=people_upeople.people_id
and people_upeople.upeople_id=upeople.id
and upeople.id=upeople_companies.upeople_id and upeople_companies.company_id=companies.id
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
S<-fetch(rs,n=-1)
print("SHOW HEAD DATA")
print(head(S))
print("SHOW SUMMARY")
print(summary(S[2:4]))
print(" Nº PEOPLE IN COMPANIES")
print(table(S$company))
cat("\n PART 2: LAST WEEK SUMMARY \n")
cat("\n 2.1 COMMITS & LINES\n")
query <- paste("select
count(distinct(commits_lines.commit_id)) as commits,
sum(commits_lines.added) as added,
sum(commits_lines.removed) as removed,
year(date) as year,
month(date) as month,
day(date) as days
from commits_lines, scmlog
where commits_lines.commit_id=scmlog.id
group by year(date), month(date), day(date)")
rs <- dbSendQuery(con, query)
lines<-fetch(rs,n=-1)
last<-lines[(nrow(lines)-6):nrow(lines),]
print("SHOW HEAD DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[1:3]))
cat("\n 2.2. FILES TOUCHED\n")
query <- paste("select
count(distinct(actions.file_id))
as total_files,
year(date)
as year,
month(date)
as month,
day(date)
as day
from scmlog, actions
where actions.commit_id=scmlog.id
group by year(date), month(date), day(date)")
rs <- dbSendQuery(con, query)
actions<-fetch(rs,n=-1)
last<-actions[(nrow(actions)-6):nrow(actions),]
print("SHOW HEAD DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[1]))
}
if(conf$dbtype=="mls")#SPECIAL VALIDATOR FOR MLS
{
core<-c("compressed_files","mailing_lists","mailing_lists_people","messages","messages_people","people","people_upeople")
optional<-c()
Control()
cat("\n PART 1: POSSIBLE ERRORS \n")
print(" 1.1.Table=PEOPLE Field=name")
print(" 1. ERROR; @")
error_name1<-Errors("@","people","name")
print(" 2. ERROR; root")
people_name2<-Errors("root","people","name")
print(" 3. ERROR; bot")
people_name3<-Errors("bot","people","name")
print(" 1.2.Table=PEOPLE Field=email_adress")
print(" 1. ERROR; root")
people_email1<-Errors("root","people","email_address")
print(" 2. ERROR; bot")
people_email2<-Errors("bot","people","email_address")
print(" 3. ERROR; miss value")
miss_people_email<-Errors("^$|^( +)$", "people", "email_address")
cat("\n PART 2: TABLES COMPARISON ; DIF BETWEEN ROWS \n")
print(" 2.1 From PEOPLE to PEOPLE_UPEOPLE")
compare1<-Compare("people","people_upeople","email_address","people_id")
######NUMERICAL ANALYSIS
cat("\n NUMERICAL ANALYSIS \n")
cat("\n PART 1: STATIC DATA SUMMARY \n")
print(" 1.1. BY PEOPLE")
query<-paste("select count(distinct(messages_people.email_address)) as total_messages,
people_upeople.upeople_id as people_id
from messages_people, people_upeople
where messages_people.email_address=people_upeople.people_id
group by people_upeople.upeople_id")
rs<-dbSendQuery(con, query)
MESS<-fetch(rs,n=-1)
print("SHOW HEAD DATA")
print(head(MESS))
print("SHOW SUMMARY")
print(summary(MESS[1]))
cat("\n PART 2: LAST WEEK SUMMARY \n ")
print(" 2.1: MESSAGES")
query<-paste("select count(distinct(message_ID)) as messages_id,
year(first_date) as year,
month(first_date) as month,
day(first_date) as day
from messages
group by year(first_date), month(first_date), day(first_date)")
rs<-dbSendQuery(con, query)
TimeMess<-fetch(rs,n=-1)
last<-TimeMess[(nrow(TimeMess)-6):nrow(TimeMess),]
print("SHOW HEAD DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[1]))
}
if(conf$dbtype=="its")#HERE START SPECIAL VALIDATOR FOR ITS
{
core<-c("attachments","changes","comments","issues","issues_watchers","people","people_upeople","related_to","supported_trackers","trackers","weeks")
optional<-c("issues_ext_launchpad","issues_log_launchpad")
Control()
cat("\n PART 1: ERRORS IN TABLES \n")
print(" 1.1.Table=PEOPLE Field=name")
print(" 1. ERROR; @")
error_name1<-Errors("@","people","name")
print(" 2. ERROR; root")
people_name2<-Errors("root","people","name")
print(" 3. ERROR; bot")
people_name3<-Errors("bot","people","name")
print(" 1.2.Table=PEOPLE Field=email")
print(" 1. ERROR; root")
people_email1<-Errors("root","people","email")
print(" 2. ERROR; bot")
people_email2<-Errors("bot","people","email")
print(" 3. ERROR; miss value")
miss_people_email<-Errors("None", "people", "email")
cat("\n PART 2: TABLES COMPARISON ; DIF BETWEEN ROWS \n")
print(" 2.1 From PEOPLE to PEOPLE_UPEOPLE")
compare1<-Compare("people","people_upeople","id","people_id")
######NUMERICAL ANALYSIS
cat("\n NUMERICAL ANALYSIS \n")
cat("\n PART 1: STATIC DATA SUMMARY \n")
print(" 1.1. BY PEOPLE")
query<-paste("select people_upeople.people_id as people_id,
count(distinct(issues.id)) as total_submitted
from issues, people_upeople
where people_upeople.people_id=issues.submitted_by
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
SUBM<-fetch(rs,n=-1)
query<-paste("select people_upeople.people_id as people_id,
count(distinct(issues.id)) as total_assigned
from issues, people_upeople
where people_upeople.people_id=issues.assigned_to
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
ASSIG<-fetch(rs,n=-1)
ASSIG$people_id<-row.names(ASSIG)
X<-merge(ASSIG,SUBM,by="people_id")
query<-paste("select people_upeople.people_id as people_id,
count(distinct(comments.issue_id)) as total_comments
from people_upeople, comments
where people_upeople.people_id=comments.submitted_by
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
COMM<-fetch(rs,n=-1)
COMM$people_id<-row.names(COMM)
query<-paste("select people_upeople.people_id as people_id,
count(distinct(changes.issue_id)) as total_changes
from people_upeople, changes
where people_upeople.people_id=changes.changed_by
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
CHAN<-fetch(rs,n=-1)
CHAN$people_id<-row.names(CHAN)
Y<-merge(COMM,CHAN,by="people_id")
M<-merge(X,Y,by="people_id")
print("SHOW HEAD DATA")
print(head(M))
print("SHOW SUMMARY")
print(summary(M[2:5]))
cat("\n PART 2: LAST WEEK SUMMARY \n ")
print(" 2.1 ISSUES")
query<-paste("select year(submitted_on) as year,
month(submitted_on) as month,
day(submitted_on) as day,
count(distinct(issues.issue)) as total_issue
from issues
group by year(submitted_on), month(submitted_on), day(submitted_on)")
rs<-dbSendQuery(con, query)
tempo_issue<-fetch(rs,n=-1)
last<-tempo_issue[(nrow(tempo_issue)-6):nrow(tempo_issue),]
print("SHOW DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[4]))
}
|
/vizGrimoireJS/validator_dbstatus.R
|
no_license
|
rodrigoprimo/VizGrimoireR
|
R
| false
| false
| 13,607
|
r
|
## Copyright (C) 2012, 2013 Bitergia
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##
## This file is a part of the vizGrimoire.R package
## http://vizgrimoire.bitergia.org/
##
##
## Authors:
## Marina Doria Garcia de Cortazar <marina@bitergia.com>
## Daniel Izquierdo Cortazar <dizquierdo@bitergia.com>
##
## Usage:
## R --vanilla --args -d dbname -u dbuser -p dbpassword -v dverbose < validator_dbstatus.R
##
library(optparse)
library(DBI)
library(RMySQL)
ConfFromOptParse <- function () {
option_list <- list(
make_option(c("-d", "--database"), dest="database",
help="Database with data"),
make_option(c("-u", "--dbuser"), dest="dbuser",
help="Database user", default="root"),
make_option(c("-p", "--dbpassword"), dest="dbpassword",
help="Database user password", default=""),
make_option(c("-t", "--dbtype"), dest="dbtype",
help="Type of database; scm, mls, its"),
make_option(c("-v", "--verbose"), dest="dverbose",
help="Option to show more information (yes/no) ", default="no")
)
parser <- OptionParser(usage = "%prog [options]", option_list = option_list)
options <- parse_args(parser)
if (is.null(options$database)) {
print_help(parser)
stop("Database param is required")
}
return(options)
}
#---
conf <- ConfFromOptParse()
print(conf)
con <- dbConnect(MySQL(), dbname = conf$database, user = conf$dbuser, password = conf$dbpassword)
query<-paste("show tables")
rs<-dbSendQuery(con, query)
all<-c()
rows<-c()
tables<-fetch(rs,n=-1)
colnames(tables)<-"names"
for( i in 1:nrow(tables))
{
query2<-paste("select count(*) from",tables[i,])
rs2<-dbSendQuery(con, query2)
total<-fetch(rs2,n=-1)
colnames(total)<-paste("total row",tables[i,])
rows<-c(rows,total)
i<-i+1
}
trow<-matrix(rows)
totalr<-data.frame(trow)
table_row<-data.frame(totalr,tables)
colnames(table_row)<-c("rows","names")
#This function classified core and optional tables with number of rows.
Control<-function()
{
i<-0
cores<-NULL
ops<-NULL
errs<-NULL
cat("\n TABLES ANALYSIS:\n ")
for(i in 1:nrow(table_row))
{
if (is.element(table_row$names[i], core)){
co<-paste(table_row$names[i],table_row$rows[i])
cores<-c(cores,co)
i<-i+1
}
else if (is.element(table_row$names[i], optional)){
op<-paste(table_row$names[i],table_row$rows[i])
ops<-c(ops,op)
i<-i+1
}
else {
er<-paste("error; table unidentified:",table_row$names[i])
errs<-c(errs,er)
i<-i+1
}
}
x<-paste(" CORE TABLE", cores)
print(x)
y<-paste(" OPTIONAL TABLE",ops)
print(y)
print(errs)
}
Compare<-function(table1,table2,value1,value2)
{
#This function compares number of rows between pair of tables
#table1=Table to compare ; value1=pk in table1 linking with the other table.
#table2=Table to compare ; value2=pk in table2 linking with the other table.
query<-paste("select count(", table1,".",value1,")",
" from ",table1,
" where ", table1,".",value1," not in (select distinct(",table2,".",value2,") from ",table2,")", sep="")
rs<-dbSendQuery(con, query)
missrow<-fetch(rs,n=-1)
comp<-paste("Total missing values=",missrow)
print(comp)
}
Errors<-function(put,table,colum)
#This function finds strings values in a given field.
#put: value to find
#table: data.frame
#colum:field in table.
{ query<-paste("select * from",table)
rs<-dbSendQuery(con, query)
tables<-fetch(rs,n=-1)
error<-grep(put,tables[[colum]])
total_error<-length(error)
total_error<-paste("Total error:", total_error)
print(total_error)
if(conf$dverbose=="yes")
{
print("IN ROWS:")
print(error)
}
#visual<-tables[[colum]][error]
#print("LOOK ERRORS")
#print(visual)
return(error)
}
if(conf$dbtype=="scm")#SPECIAL VALIDATOR FOR SCM
{
core<-c("actions","branches","file_copies","file_links","files","people","repositories","scmlog","tag_revisions","tags")
optional<-c("action_files","actions_file_names","commits_lines","companies","companies_all","extra", "file_types","identities", "months","people_upeople","upeople","upeople_companies","weeks")
Control()
cat("\n PART 1: POSSIBLE ERRORS \n")
print(" 1.1.Table=PEOPLE Field=name")
print(" 1. ERROR; @")
error_name1<-Errors("@","people","name")
print(" 2. ERROR; root")
people_name2<-Errors("root","people","name")
print(" 3. ERROR; bot")
people_name3<-Errors("bot","people","name")
print(" 1.2.Table=PEOPLE Field=email")
print(" 1. ERROR; root")
people_email1<-Errors("root","people","email")
print(" 2. ERROR; bot")
people_email2<-Errors("bot","people","email")
print(" 3. ERROR; miss value")
miss_people_email<-Errors("^$|^( +)$", "people", "email")
print(" 1.3. Table=EXTRA Field=site")
print(" 1. ERROR; miss value")
miss_extra_site<-Errors("^$|^( +)$", "extra", "site")
cat("\n PART 2: TABLES COMPARISON ; DIF BETWEEN ROWS \n")
print(" 2.1 From SCMLOG author_id to PEOPLE id")
compare1<-Compare("scmlog","people","author_id","id")
print(" 2.2 From SCMLOG commiter_id to PEOPLE id")
compare2<-Compare("scmlog","people","committer_id","id")
print(" 2.3 From PEOPLE id to PEOPLE_UPEOPLE people_id")
compare3<-Compare("people","people_upeople","id","people_id")
print(" 2.4 From PEOPLE_UPEOPLE people_id to UPEOPLE upeople_id")
compare4<-Compare("people_upeople","upeople","people_id","id")
print(" 2.5 From UPEOPLE upeople_id to UPEOPLE_COMPANIES upeople_id")
compare5<-Compare("upeople","upeople_companies","id","upeople_id")
######NUMERICAL ANALYSIS
cat("\n NUMERICAL ANALYSIS \n")
cat("\n PART 1: STATIC DATA SUMMARY \n")
print("1.1. BY PEOPLE")
query<-paste("select people_upeople.people_id as id_people,
scmlog.id as total_commits,
commits_lines.added as total_added,
commits_lines.removed as total_removed,
companies.name as company
from commits_lines,
companies, scmlog, people, people_upeople, upeople, upeople_companies
where commits_lines.commit_id=scmlog.id
and scmlog.author_id=people.id
and people.id=people_upeople.people_id
and people_upeople.upeople_id=upeople.id
and upeople.id=upeople_companies.upeople_id and upeople_companies.company_id=companies.id
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
S<-fetch(rs,n=-1)
print("SHOW HEAD DATA")
print(head(S))
print("SHOW SUMMARY")
print(summary(S[2:4]))
print(" Nº PEOPLE IN COMPANIES")
print(table(S$company))
cat("\n PART 2: LAST WEEK SUMMARY \n")
cat("\n 2.1 COMMITS & LINES\n")
query <- paste("select
count(distinct(commits_lines.commit_id)) as commits,
sum(commits_lines.added) as added,
sum(commits_lines.removed) as removed,
year(date) as year,
month(date) as month,
day(date) as days
from commits_lines, scmlog
where commits_lines.commit_id=scmlog.id
group by year(date), month(date), day(date)")
rs <- dbSendQuery(con, query)
lines<-fetch(rs,n=-1)
last<-lines[(nrow(lines)-6):nrow(lines),]
print("SHOW HEAD DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[1:3]))
cat("\n 2.2. FILES TOUCHED\n")
query <- paste("select
count(distinct(actions.file_id))
as total_files,
year(date)
as year,
month(date)
as month,
day(date)
as day
from scmlog, actions
where actions.commit_id=scmlog.id
group by year(date), month(date), day(date)")
rs <- dbSendQuery(con, query)
actions<-fetch(rs,n=-1)
last<-actions[(nrow(actions)-6):nrow(actions),]
print("SHOW HEAD DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[1]))
}
if(conf$dbtype=="mls")#SPECIAL VALIDATOR FOR MLS
{
core<-c("compressed_files","mailing_lists","mailing_lists_people","messages","messages_people","people","people_upeople")
optional<-c()
Control()
cat("\n PART 1: POSSIBLE ERRORS \n")
print(" 1.1.Table=PEOPLE Field=name")
print(" 1. ERROR; @")
error_name1<-Errors("@","people","name")
print(" 2. ERROR; root")
people_name2<-Errors("root","people","name")
print(" 3. ERROR; bot")
people_name3<-Errors("bot","people","name")
print(" 1.2.Table=PEOPLE Field=email_adress")
print(" 1. ERROR; root")
people_email1<-Errors("root","people","email_address")
print(" 2. ERROR; bot")
people_email2<-Errors("bot","people","email_address")
print(" 3. ERROR; miss value")
miss_people_email<-Errors("^$|^( +)$", "people", "email_address")
cat("\n PART 2: TABLES COMPARISON ; DIF BETWEEN ROWS \n")
print(" 2.1 From PEOPLE to PEOPLE_UPEOPLE")
compare1<-Compare("people","people_upeople","email_address","people_id")
######NUMERICAL ANALYSIS
cat("\n NUMERICAL ANALYSIS \n")
cat("\n PART 1: STATIC DATA SUMMARY \n")
print(" 1.1. BY PEOPLE")
query<-paste("select count(distinct(messages_people.email_address)) as total_messages,
people_upeople.upeople_id as people_id
from messages_people, people_upeople
where messages_people.email_address=people_upeople.people_id
group by people_upeople.upeople_id")
rs<-dbSendQuery(con, query)
MESS<-fetch(rs,n=-1)
print("SHOW HEAD DATA")
print(head(MESS))
print("SHOW SUMMARY")
print(summary(MESS[1]))
cat("\n PART 2: LAST WEEK SUMMARY \n ")
print(" 2.1: MESSAGES")
query<-paste("select count(distinct(message_ID)) as messages_id,
year(first_date) as year,
month(first_date) as month,
day(first_date) as day
from messages
group by year(first_date), month(first_date), day(first_date)")
rs<-dbSendQuery(con, query)
TimeMess<-fetch(rs,n=-1)
last<-TimeMess[(nrow(TimeMess)-6):nrow(TimeMess),]
print("SHOW HEAD DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[1]))
}
if(conf$dbtype=="its")#HERE START SPECIAL VALIDATOR FOR ITS
{
core<-c("attachments","changes","comments","issues","issues_watchers","people","people_upeople","related_to","supported_trackers","trackers","weeks")
optional<-c("issues_ext_launchpad","issues_log_launchpad")
Control()
cat("\n PART 1: ERRORS IN TABLES \n")
print(" 1.1.Table=PEOPLE Field=name")
print(" 1. ERROR; @")
error_name1<-Errors("@","people","name")
print(" 2. ERROR; root")
people_name2<-Errors("root","people","name")
print(" 3. ERROR; bot")
people_name3<-Errors("bot","people","name")
print(" 1.2.Table=PEOPLE Field=email")
print(" 1. ERROR; root")
people_email1<-Errors("root","people","email")
print(" 2. ERROR; bot")
people_email2<-Errors("bot","people","email")
print(" 3. ERROR; miss value")
miss_people_email<-Errors("None", "people", "email")
cat("\n PART 2: TABLES COMPARISON ; DIF BETWEEN ROWS \n")
print(" 2.1 From PEOPLE to PEOPLE_UPEOPLE")
compare1<-Compare("people","people_upeople","id","people_id")
######NUMERICAL ANALYSIS
cat("\n NUMERICAL ANALYSIS \n")
cat("\n PART 1: STATIC DATA SUMMARY \n")
print(" 1.1. BY PEOPLE")
query<-paste("select people_upeople.people_id as people_id,
count(distinct(issues.id)) as total_submitted
from issues, people_upeople
where people_upeople.people_id=issues.submitted_by
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
SUBM<-fetch(rs,n=-1)
query<-paste("select people_upeople.people_id as people_id,
count(distinct(issues.id)) as total_assigned
from issues, people_upeople
where people_upeople.people_id=issues.assigned_to
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
ASSIG<-fetch(rs,n=-1)
ASSIG$people_id<-row.names(ASSIG)
X<-merge(ASSIG,SUBM,by="people_id")
query<-paste("select people_upeople.people_id as people_id,
count(distinct(comments.issue_id)) as total_comments
from people_upeople, comments
where people_upeople.people_id=comments.submitted_by
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
COMM<-fetch(rs,n=-1)
COMM$people_id<-row.names(COMM)
query<-paste("select people_upeople.people_id as people_id,
count(distinct(changes.issue_id)) as total_changes
from people_upeople, changes
where people_upeople.people_id=changes.changed_by
group by people_upeople.people_id")
rs<-dbSendQuery(con, query)
CHAN<-fetch(rs,n=-1)
CHAN$people_id<-row.names(CHAN)
Y<-merge(COMM,CHAN,by="people_id")
M<-merge(X,Y,by="people_id")
print("SHOW HEAD DATA")
print(head(M))
print("SHOW SUMMARY")
print(summary(M[2:5]))
cat("\n PART 2: LAST WEEK SUMMARY \n ")
print(" 2.1 ISSUES")
query<-paste("select year(submitted_on) as year,
month(submitted_on) as month,
day(submitted_on) as day,
count(distinct(issues.issue)) as total_issue
from issues
group by year(submitted_on), month(submitted_on), day(submitted_on)")
rs<-dbSendQuery(con, query)
tempo_issue<-fetch(rs,n=-1)
last<-tempo_issue[(nrow(tempo_issue)-6):nrow(tempo_issue),]
print("SHOW DATA")
print(last)
print("SHOW SUMMARY")
print(summary(last[4]))
}
|
#####
#
# streamflow testing - regression
library(optparse)
source("/data2/3to5/I35/scripts/analysisfunctions.R")
#source("/data2/3to5/I35/scripts/colorramp.R")
library(ncdf4)
library(maps)
library(fields)
library(sp)
library(raster)
library(rasterVis)
library(maptools)
library(ggplot2)
library(zoo)
library(lars)
library(mailR)
# email settings
emadd = "amwootte@ou.edu"
pswd = "xKFkcBZ6oN"
streamflow = read.table("/home/woot0002/streamflow_08146000",header=TRUE,sep="\t",fill=TRUE)
climate = read.table("/home/woot0002/2444385.csv",header=TRUE,sep=",")
names(streamflow) = c("agency","site","DATE","streamflow_mean","streamflow_mean_QC","streamflow_max","streamflow_max_QC","streamflow_min","streamflow_min_QC")
fulldata = merge(streamflow,climate,by="DATE")
fulldata$streamflow_mean=as.numeric(fulldata$streamflow_mean)
tmp = c(NA,NA,rollapply(fulldata$streamflow_mean,5,mean,na.rm=TRUE),NA,NA)
fulldata$streamflow_mean=tmp
fulldata$PRCP=as.numeric(fulldata$PRCP)
fulldata$TMAX=as.numeric(fulldata$TMAX)
fulldata$TMIN=as.numeric(fulldata$TMIN)
fulldata$TAVG=(as.numeric(fulldata$TMAX)+as.numeric(fulldata$TMIN))/2
fulldata$SNOW=as.numeric(fulldata$SNOW)
fulldata$DAPR=as.numeric(fulldata$DAPR)
fulldata$DASF=as.numeric(fulldata$DASF)
fulldata$MDPR=as.numeric(fulldata$MDPR)
fulldata$MDSF=as.numeric(fulldata$MDSF)
fulldata$SNWD=as.numeric(fulldata$SNWD)
fulldata$HOT1S = ifelse(fulldata$TMAX>mean(fulldata$TMAX,na.rm=TRUE)+sd(fulldata$TMAX,na.rm=TRUE),1,0) # hotdays 1 sd, 2 sd, 3 sd, and above 90F
fulldata$HOT2S = ifelse(fulldata$TMAX>mean(fulldata$TMAX,na.rm=TRUE)+2*sd(fulldata$TMAX,na.rm=TRUE),1,0)
fulldata$HOT3S = ifelse(fulldata$TMAX>mean(fulldata$TMAX,na.rm=TRUE)+3*sd(fulldata$TMAX,na.rm=TRUE),1,0)
fulldata$HOT90 = ifelse(fulldata$TMAX>90,1,0)
fulldata$COLD1S = ifelse(fulldata$TMIN<mean(fulldata$TMIN,na.rm=TRUE)+sd(fulldata$TMIN,na.rm=TRUE),1,0) # hotdays 1 sd, 2 sd, 3 sd, and above 90F
fulldata$COLD2S = ifelse(fulldata$TMIN<mean(fulldata$TMIN,na.rm=TRUE)+2*sd(fulldata$TMIN,na.rm=TRUE),1,0)
fulldata$COLD3S = ifelse(fulldata$TMIN<mean(fulldata$TMIN,na.rm=TRUE)+3*sd(fulldata$TMIN,na.rm=TRUE),1,0)
fulldata$COLD32 = ifelse(fulldata$TMIN<32,1,0)
fulldata$TAVG_3D = c(rep(NA,2),rollapply(fulldata$TAVG,width=3,FUN=mean,na.rm=TRUE))
fulldata$TAVG_1W = c(rep(NA,6),rollapply(fulldata$TAVG,width=7,FUN=mean,na.rm=TRUE))
fulldata$TAVG_2W = c(rep(NA,13),rollapply(fulldata$TAVG,width=14,FUN=mean,na.rm=TRUE))
fulldata$TAVG_3W = c(rep(NA,20),rollapply(fulldata$TAVG,width=21,FUN=mean,na.rm=TRUE))
fulldata$TAVG_4W = c(rep(NA,27),rollapply(fulldata$TAVG,width=28,FUN=mean,na.rm=TRUE))
fulldata$TAVG_1M = c(rep(NA,29),rollapply(fulldata$TAVG,width=30,FUN=mean,na.rm=TRUE))
fulldata$TAVG_2M = c(rep(NA,59),rollapply(fulldata$TAVG,width=60,FUN=mean,na.rm=TRUE))
fulldata$TAVG_3M = c(rep(NA,89),rollapply(fulldata$TAVG,width=90,FUN=mean,na.rm=TRUE))
fulldata$TAVG_4M = c(rep(NA,119),rollapply(fulldata$TAVG,width=120,FUN=mean,na.rm=TRUE))
fulldata$TAVG_5M = c(rep(NA,149),rollapply(fulldata$TAVG,width=150,FUN=mean,na.rm=TRUE))
fulldata$TAVG_6M = c(rep(NA,179),rollapply(fulldata$TAVG,width=180,FUN=mean,na.rm=TRUE))
fulldata$TAVG_12M = c(rep(NA,364),rollapply(fulldata$TAVG,width=365,FUN=mean,na.rm=TRUE))
fulldata$TAVG_24M = c(rep(NA,729),rollapply(fulldata$TAVG,width=730,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_3D = c(rep(NA,2),rollapply(fulldata$PRCP,width=3,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_1W = c(rep(NA,6),rollapply(fulldata$PRCP,width=7,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_2W = c(rep(NA,13),rollapply(fulldata$PRCP,width=14,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_3W = c(rep(NA,20),rollapply(fulldata$PRCP,width=21,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_4W = c(rep(NA,27),rollapply(fulldata$PRCP,width=28,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_1M = c(rep(NA,29),rollapply(fulldata$PRCP,width=30,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_2M = c(rep(NA,59),rollapply(fulldata$PRCP,width=60,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_3M = c(rep(NA,89),rollapply(fulldata$PRCP,width=90,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_4M = c(rep(NA,119),rollapply(fulldata$PRCP,width=120,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_5M = c(rep(NA,149),rollapply(fulldata$PRCP,width=150,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_6M = c(rep(NA,179),rollapply(fulldata$PRCP,width=180,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_12M = c(rep(NA,364),rollapply(fulldata$PRCP,width=365,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_24M = c(rep(NA,729),rollapply(fulldata$PRCP,width=730,FUN=mean,na.rm=TRUE))
fulldata$PRCP_3D = c(rep(NA,2),rollapply(fulldata$PRCP,width=3,FUN=sum,na.rm=TRUE))
fulldata$PRCP_1W = c(rep(NA,6),rollapply(fulldata$PRCP,width=7,FUN=sum,na.rm=TRUE))
fulldata$PRCP_2W = c(rep(NA,13),rollapply(fulldata$PRCP,width=14,FUN=sum,na.rm=TRUE))
fulldata$PRCP_3W = c(rep(NA,20),rollapply(fulldata$PRCP,width=21,FUN=sum,na.rm=TRUE))
fulldata$PRCP_4W = c(rep(NA,27),rollapply(fulldata$PRCP,width=28,FUN=sum,na.rm=TRUE))
fulldata$PRCP_1M = c(rep(NA,29),rollapply(fulldata$PRCP,width=30,FUN=sum,na.rm=TRUE))
fulldata$PRCP_2M = c(rep(NA,59),rollapply(fulldata$PRCP,width=60,FUN=sum,na.rm=TRUE))
fulldata$PRCP_3M = c(rep(NA,89),rollapply(fulldata$PRCP,width=90,FUN=sum,na.rm=TRUE))
fulldata$PRCP_4M = c(rep(NA,119),rollapply(fulldata$PRCP,width=120,FUN=sum,na.rm=TRUE))
fulldata$PRCP_5M = c(rep(NA,149),rollapply(fulldata$PRCP,width=150,FUN=sum,na.rm=TRUE))
fulldata$PRCP_6M = c(rep(NA,179),rollapply(fulldata$PRCP,width=180,FUN=sum,na.rm=TRUE))
fulldata$PRCP_12M = c(rep(NA,364),rollapply(fulldata$PRCP,width=365,FUN=sum,na.rm=TRUE))
fulldata$PRCP_24M = c(rep(NA,729),rollapply(fulldata$PRCP,width=730,FUN=sum,na.rm=TRUE))
fulldata$MAXPRCP1W_2W = c(rep(NA,13),rollapply(fulldata$PRCP_1W,width=14,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_3W = c(rep(NA,20),rollapply(fulldata$PRCP_1W,width=21,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_4W = c(rep(NA,27),rollapply(fulldata$PRCP_1W,width=28,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_1M = c(rep(NA,29),rollapply(fulldata$PRCP_1W,width=30,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_2M = c(rep(NA,59),rollapply(fulldata$PRCP_1W,width=60,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_3M = c(rep(NA,89),rollapply(fulldata$PRCP_1W,width=90,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_4M = c(rep(NA,119),rollapply(fulldata$PRCP_1W,width=120,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_5M = c(rep(NA,149),rollapply(fulldata$PRCP_1W,width=150,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_6M = c(rep(NA,179),rollapply(fulldata$PRCP_1W,width=180,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_12M = c(rep(NA,364),rollapply(fulldata$PRCP_1W,width=365,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_24M = c(rep(NA,729),rollapply(fulldata$PRCP_1W,width=730,FUN=max,na.rm=TRUE))
fulldata$MDRN = ifelse(fulldata$PRCP<0.01,0,1)
fulldata$MDRN_1W = c(rep(NA,6),rollapply(fulldata$MDRN,width=7,FUN=sum,na.rm=TRUE))
fulldata$MDRN_2W = c(rep(NA,13),rollapply(fulldata$MDRN,width=14,FUN=sum,na.rm=TRUE))
fulldata$MDRN_3W = c(rep(NA,20),rollapply(fulldata$MDRN,width=21,FUN=sum,na.rm=TRUE))
fulldata$MDRN_4W = c(rep(NA,27),rollapply(fulldata$MDRN,width=28,FUN=sum,na.rm=TRUE))
fulldata$MDRN_1M = c(rep(NA,29),rollapply(fulldata$MDRN,width=30,FUN=sum,na.rm=TRUE))
fulldata$MDRN_2M = c(rep(NA,59),rollapply(fulldata$MDRN,width=60,FUN=sum,na.rm=TRUE))
fulldata$MDRN_3M = c(rep(NA,89),rollapply(fulldata$MDRN,width=90,FUN=sum,na.rm=TRUE))
fulldata$MDRN_4M = c(rep(NA,119),rollapply(fulldata$MDRN,width=120,FUN=sum,na.rm=TRUE))
fulldata$MDRN_5M = c(rep(NA,149),rollapply(fulldata$MDRN,width=150,FUN=sum,na.rm=TRUE))
fulldata$MDRN_6M = c(rep(NA,179),rollapply(fulldata$MDRN,width=180,FUN=sum,na.rm=TRUE))
fulldata$MDRN_12M = c(rep(NA,364),rollapply(fulldata$MDRN,width=365,FUN=sum,na.rm=TRUE))
fulldata$MDRN_24M = c(rep(NA,729),rollapply(fulldata$MDRN,width=730,FUN=sum,na.rm=TRUE))
fulldata$TMAXAVG_1W = c(rep(NA,6),rollapply(fulldata$TMAX,width=7,FUN=mean,na.rm=TRUE))
fulldata$MAXTMAX1W_2W = c(rep(NA,13),rollapply(fulldata$TMAXAVG_1W,width=14,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_3W = c(rep(NA,20),rollapply(fulldata$TMAXAVG_1W,width=21,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_4W = c(rep(NA,27),rollapply(fulldata$TMAXAVG_1W,width=28,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_1M = c(rep(NA,29),rollapply(fulldata$TMAXAVG_1W,width=30,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_2M = c(rep(NA,59),rollapply(fulldata$TMAXAVG_1W,width=60,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_3M = c(rep(NA,89),rollapply(fulldata$TMAXAVG_1W,width=90,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_4M = c(rep(NA,119),rollapply(fulldata$TMAXAVG_1W,width=120,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_5M = c(rep(NA,149),rollapply(fulldata$TMAXAVG_1W,width=150,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_6M = c(rep(NA,179),rollapply(fulldata$TMAXAVG_1W,width=180,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_12M = c(rep(NA,364),rollapply(fulldata$TMAXAVG_1W,width=365,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_24M = c(rep(NA,729),rollapply(fulldata$TMAXAVG_1W,width=730,FUN=max,na.rm=TRUE))
fulldata$TMINAVG_1W = c(rep(NA,6),rollapply(fulldata$TMAX,width=7,FUN=mean,na.rm=TRUE))
fulldata$MINTMIN1W_2W = c(rep(NA,13),rollapply(fulldata$TMINAVG_1W,width=14,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_3W = c(rep(NA,20),rollapply(fulldata$TMINAVG_1W,width=21,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_4W = c(rep(NA,27),rollapply(fulldata$TMINAVG_1W,width=28,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_1M = c(rep(NA,29),rollapply(fulldata$TMINAVG_1W,width=30,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_2M = c(rep(NA,59),rollapply(fulldata$TMINAVG_1W,width=60,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_3M = c(rep(NA,89),rollapply(fulldata$TMINAVG_1W,width=90,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_4M = c(rep(NA,119),rollapply(fulldata$TMINAVG_1W,width=120,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_5M = c(rep(NA,149),rollapply(fulldata$TMINAVG_1W,width=150,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_6M = c(rep(NA,179),rollapply(fulldata$TMINAVG_1W,width=180,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_12M = c(rep(NA,364),rollapply(fulldata$TMINAVG_1W,width=365,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_24M = c(rep(NA,729),rollapply(fulldata$TMINAVG_1W,width=730,FUN=min,na.rm=TRUE))
fulldata$HOT1S_1W = c(rep(NA,6),rollapply(fulldata$HOT1S,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_2W = c(rep(NA,13),rollapply(fulldata$HOT1S,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_3W = c(rep(NA,20),rollapply(fulldata$HOT1S,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_4W = c(rep(NA,27),rollapply(fulldata$HOT1S,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_1M = c(rep(NA,29),rollapply(fulldata$HOT1S,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_2M = c(rep(NA,59),rollapply(fulldata$HOT1S,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_3M = c(rep(NA,89),rollapply(fulldata$HOT1S,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_4M = c(rep(NA,119),rollapply(fulldata$HOT1S,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_5M = c(rep(NA,149),rollapply(fulldata$HOT1S,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_6M = c(rep(NA,179),rollapply(fulldata$HOT1S,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_12M = c(rep(NA,364),rollapply(fulldata$HOT1S,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_24M = c(rep(NA,729),rollapply(fulldata$HOT1S,width=730,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_1W = c(rep(NA,6),rollapply(fulldata$HOT2S,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_2W = c(rep(NA,13),rollapply(fulldata$HOT2S,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_3W = c(rep(NA,20),rollapply(fulldata$HOT2S,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_4W = c(rep(NA,27),rollapply(fulldata$HOT2S,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_1M = c(rep(NA,29),rollapply(fulldata$HOT2S,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_2M = c(rep(NA,59),rollapply(fulldata$HOT2S,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_3M = c(rep(NA,89),rollapply(fulldata$HOT2S,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_4M = c(rep(NA,119),rollapply(fulldata$HOT2S,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_5M = c(rep(NA,149),rollapply(fulldata$HOT2S,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_6M = c(rep(NA,179),rollapply(fulldata$HOT2S,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_12M = c(rep(NA,364),rollapply(fulldata$HOT2S,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_24M = c(rep(NA,729),rollapply(fulldata$HOT2S,width=730,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_1W = c(rep(NA,6),rollapply(fulldata$HOT3S,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_2W = c(rep(NA,13),rollapply(fulldata$HOT3S,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_3W = c(rep(NA,20),rollapply(fulldata$HOT3S,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_4W = c(rep(NA,27),rollapply(fulldata$HOT3S,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_1M = c(rep(NA,29),rollapply(fulldata$HOT3S,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_2M = c(rep(NA,59),rollapply(fulldata$HOT3S,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_3M = c(rep(NA,89),rollapply(fulldata$HOT3S,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_4M = c(rep(NA,119),rollapply(fulldata$HOT3S,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_5M = c(rep(NA,149),rollapply(fulldata$HOT3S,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_6M = c(rep(NA,179),rollapply(fulldata$HOT3S,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_12M = c(rep(NA,364),rollapply(fulldata$HOT3S,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_24M = c(rep(NA,729),rollapply(fulldata$HOT3S,width=730,FUN=sum,na.rm=TRUE))
fulldata$HOT90_1W = c(rep(NA,6),rollapply(fulldata$HOT90,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT90_2W = c(rep(NA,13),rollapply(fulldata$HOT90,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT90_3W = c(rep(NA,20),rollapply(fulldata$HOT90,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT90_4W = c(rep(NA,27),rollapply(fulldata$HOT90,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT90_1M = c(rep(NA,29),rollapply(fulldata$HOT90,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT90_2M = c(rep(NA,59),rollapply(fulldata$HOT90,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT90_3M = c(rep(NA,89),rollapply(fulldata$HOT90,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT90_4M = c(rep(NA,119),rollapply(fulldata$HOT90,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT90_5M = c(rep(NA,149),rollapply(fulldata$HOT90,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT90_6M = c(rep(NA,179),rollapply(fulldata$HOT90,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT90_12M = c(rep(NA,364),rollapply(fulldata$HOT90,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT90_24M = c(rep(NA,729),rollapply(fulldata$HOT90,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_1W = c(rep(NA,6),rollapply(fulldata$COLD1S,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_2W = c(rep(NA,13),rollapply(fulldata$COLD1S,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_3W = c(rep(NA,20),rollapply(fulldata$COLD1S,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_4W = c(rep(NA,27),rollapply(fulldata$COLD1S,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_1M = c(rep(NA,29),rollapply(fulldata$COLD1S,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_2M = c(rep(NA,59),rollapply(fulldata$COLD1S,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_3M = c(rep(NA,89),rollapply(fulldata$COLD1S,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_4M = c(rep(NA,119),rollapply(fulldata$COLD1S,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_5M = c(rep(NA,149),rollapply(fulldata$COLD1S,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_6M = c(rep(NA,179),rollapply(fulldata$COLD1S,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_12M = c(rep(NA,364),rollapply(fulldata$COLD1S,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_24M = c(rep(NA,729),rollapply(fulldata$COLD1S,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_1W = c(rep(NA,6),rollapply(fulldata$COLD2S,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_2W = c(rep(NA,13),rollapply(fulldata$COLD2S,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_3W = c(rep(NA,20),rollapply(fulldata$COLD2S,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_4W = c(rep(NA,27),rollapply(fulldata$COLD2S,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_1M = c(rep(NA,29),rollapply(fulldata$COLD2S,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_2M = c(rep(NA,59),rollapply(fulldata$COLD2S,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_3M = c(rep(NA,89),rollapply(fulldata$COLD2S,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_4M = c(rep(NA,119),rollapply(fulldata$COLD2S,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_5M = c(rep(NA,149),rollapply(fulldata$COLD2S,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_6M = c(rep(NA,179),rollapply(fulldata$COLD2S,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_12M = c(rep(NA,364),rollapply(fulldata$COLD2S,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_24M = c(rep(NA,729),rollapply(fulldata$COLD2S,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_1W = c(rep(NA,6),rollapply(fulldata$COLD3S,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_2W = c(rep(NA,13),rollapply(fulldata$COLD3S,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_3W = c(rep(NA,20),rollapply(fulldata$COLD3S,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_4W = c(rep(NA,27),rollapply(fulldata$COLD3S,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_1M = c(rep(NA,29),rollapply(fulldata$COLD3S,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_2M = c(rep(NA,59),rollapply(fulldata$COLD3S,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_3M = c(rep(NA,89),rollapply(fulldata$COLD3S,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_4M = c(rep(NA,119),rollapply(fulldata$COLD3S,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_5M = c(rep(NA,149),rollapply(fulldata$COLD3S,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_6M = c(rep(NA,179),rollapply(fulldata$COLD3S,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_12M = c(rep(NA,364),rollapply(fulldata$COLD3S,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_24M = c(rep(NA,729),rollapply(fulldata$COLD3S,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD32_1W = c(rep(NA,6),rollapply(fulldata$COLD32,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD32_2W = c(rep(NA,13),rollapply(fulldata$COLD32,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD32_3W = c(rep(NA,20),rollapply(fulldata$COLD32,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD32_4W = c(rep(NA,27),rollapply(fulldata$COLD32,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD32_1M = c(rep(NA,29),rollapply(fulldata$COLD32,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD32_2M = c(rep(NA,59),rollapply(fulldata$COLD32,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD32_3M = c(rep(NA,89),rollapply(fulldata$COLD32,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD32_4M = c(rep(NA,119),rollapply(fulldata$COLD32,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD32_5M = c(rep(NA,149),rollapply(fulldata$COLD32,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD32_6M = c(rep(NA,179),rollapply(fulldata$COLD32,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD32_12M = c(rep(NA,364),rollapply(fulldata$COLD32,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD32_24M = c(rep(NA,729),rollapply(fulldata$COLD32,width=730,FUN=sum,na.rm=TRUE))
percentile_bottom = quantile(fulldata$PRCP_1M,probs=0.25,na.rm=TRUE)
percentile_top = quantile(fulldata$PRCP_1M,probs=0.75,na.rm=TRUE)
precip_hardcode = fulldata$PRCP_1M
precip_hardcode=ifelse(fulldata$PRCP_1M<=percentile_bottom | fulldata$PRCP_1M>=percentile_top,ifelse(fulldata$PRCP_1M<=percentile_bottom,0,2),1)
tmp = precip_hardcode[1:(length(fulldata$PRCP_1M)-10)]-precip_hardcode[11:length(fulldata$PRCP_1M)]
tmpdp = c(ifelse(tmp==-2,1,0),rep(NA,10))
tmppd = c(ifelse(tmp==2,1,0),rep(NA,10))
PDcount_PRCP = sum(tmppd,na.rm=TRUE)
DPcount_PRCP = sum(tmpdp,na.rm=TRUE)
fulldata$PRCP_DP = tmpdp
fulldata$PRCP_PD = tmppd
fulldata$PRCP_WP = c(tmp,rep(NA,10))
fulldata$SFM_1M = c(rep(NA,29),rollapply(fulldata$streamflow_mean,width=30,FUN=mean,na.rm=TRUE))
#fulldata$SFM_1M = c(rep(NA,29),rollapply(fulldata$streamflow_mean,width=30,FUN=sum,na.rm=TRUE))
percentile_bottom = quantile(fulldata$SFM_1M,probs=0.25,na.rm=TRUE)
percentile_top = quantile(fulldata$SFM_1M,probs=0.75,na.rm=TRUE)
precip_hardcode = fulldata$SFM_1M
precip_hardcode=ifelse(fulldata$SFM_1M<=percentile_bottom | fulldata$SFM_1M>=percentile_top,ifelse(fulldata$SFM_1M<=percentile_bottom,0,2),1)
tmp = precip_hardcode[1:(length(fulldata$SFM_1M)-10)]-precip_hardcode[11:length(fulldata$SFM_1M)]
tmpdp = c(ifelse(tmp==-2,1,0),rep(NA,10))
tmppd = c(ifelse(tmp==2,1,0),rep(NA,10))
PDcount_SFM = sum(tmppd,na.rm=TRUE)
DPcount_SFM = sum(tmpdp,na.rm=TRUE)
fulldata$SFM_DP = tmpdp
fulldata$SFM_PD = tmppd
fulldata$SFM_WP = c(tmp,rep(NA,10))
#####
# correlation table
fulldata$YEAR = as.numeric(substr(fulldata$DATE,1,4))
years = unique(fulldata$YEAR)
fulldata2 = fulldata[which(fulldata$YEAR>=1950 & fulldata$YEAR<=2015),]
years2 = unique(fulldata2$YEAR)
cortable = NULL
for(j in 16:ncol(fulldata2)){
J=j
varname = names(fulldata2)[j]
corval = cor(as.numeric(fulldata2$streamflow_mean),as.numeric(fulldata2[,j]),method="spearman",use="pairwise.complete.obs")
tmp=data.frame(J,varname,corval)
cortable=rbind(cortable,tmp)
}
cortable$abscor = abs(cortable$corval)
sortidx = order(cortable$abscor,decreasing=TRUE)
cortable= cortable[sortidx,]
TMAXGroup1 = c("TAVG","TMAX","TMIN","TOBS","TAVG_3D","HOT1S","HOT2S","HOT3S","HOT90","COLD1S","COLD2S","COLD3S","COLD32")
PRCPGroup1 = c("SNOW","SNWD","PRCP","PRCP_3D","MDRN","PRCPAVG_3D")
TMAXGroup2 = c("TAVG_1W","TAVG_2W","TAVG_3W","TAVG_4W","TMAXAVG_1W","MAXTMAX1W_2W","MAXTMAX1W_3W","MAXTMAX1W_4W","TMINAVG_1W","MINTMIN1W_2W","MINTMIN1W_3W","MINTMIN1W_4W"
,"HOT1S_1W","HOT1S_2W","HOT1S_3W","HOT1S_4W","HOT2S_1W","HOT2S_2W","HOT2S_3W","HOT2S_4W","HOT3S_1W","HOT3S_2W","HOT3S_3W","HOT3S_4W"
,"HOT90_1W","HOT90_2W","HOT90_3W","HOT90_4W","COLD1S_1W","COLD1S_2W","COLD1S_3W","COLD1S_4W","COLD2S_1W","COLD2S_2W","COLD2S_3W","COLD2S_4W"
,"COLD3S_1W","COLD3S_2W","COLD3S_3W","COLD3S_4W","COLD32_1W","COLD32_2W","COLD32_3W","COLD32_4W")
PRCPGroup2 = c("PRCPAVG_1W","PRCPAVG_2W","PRCPAVG_3W","PRCPAVG_4W","PRCP_1W","PRCP_2W","PRCP_3W","PRCP_4W"
,"MDRN_1W","MDRN_2W","MDRN_3W","MDRN_4W","MAXPRCP1W_2W","MAXPRCP1W_3W","MAXPRCP1W_4W")
TMAXGroup3 = c("TAVG_1M","TAVG_2M","TAVG_3M","TAVG_4M","TAVG_5M","TAVG_6M","MAXTMAX1W_1M","MAXTMAX1W_2M","MAXTMAX1W_3M"
,"MAXTMAX1W_4M","MAXTMAX1W_5M","MAXTMAX1W_6M","MINTMIN1W_1M","MINTMIN1W_2M","MINTMIN1W_3M","MINTMIN1W_4M"
,"MINTMIN1W_5M","MINTMIN1W_6M","HOT1S_1M","HOT1S_2M","HOT1S_3M","HOT1S_4M","HOT1S_5M","HOT1S_6M"
,"HOT2S_1M","HOT2S_2M","HOT2S_3M","HOT2S_4M","HOT2S_5M","HOT2S_6M"
,"HOT3S_1M","HOT3S_2M","HOT3S_3M","HOT3S_4M","HOT3S_5M","HOT3S_6M"
,"HOT90_1M","HOT90_2M","HOT90_3M","HOT90_4M","HOT90_5M","HOT90_6M"
,"COLD1S_1M","COLD1S_2M","COLD1S_3M","COLD1S_4M","COLD1S_5M","COLD1S_6M"
,"COLD2S_1M","COLD2S_2M","COLD2S_3M","COLD2S_4M","COLD2S_5M","COLD2S_6M"
,"COLD3S_1M","COLD3S_2M","COLD3S_3M","COLD3S_4M","COLD3S_5M","COLD3S_6M"
,"COLD32_1M","COLD32_2M","COLD32_3M","COLD32_4M","COLD32_5M","COLD32_6M")
PRCPGroup3 = c("PRCPAVG_1M","PRCPAVG_2M","PRCPAVG_3M","PRCPAVG_4M","PRCPAVG_5M","PRCPAVG_6M"
,"PRCP_1M","PRCP_2M","PRCP_3M","PRCP_4M","PRCP_5M","PRCP_6M"
,"MAXPRCP1W_1M","MAXPRCP1W_2M","MAXPRCP1W_3M","MAXPRCP1W_4M","MAXPRCP1W_5M","MAXPRCP1W_6M"
,"MDRN_1M","MDRN_2M","MDRN_3M","MDRN_4M","MDRN_5M","MDRN_6M")
TMAXGroup4 = c("TAVG_12M","TAVG_24M","MAXTMAX1W_12M","MAXTMAX1W_24M","MINTMIN1W_12M","MINTMIN1W_24M"
,"HOT1S_12M","HOT1S_24M","HOT2S_12M","HOT2S_24M","HOT3S_12M","HOT3S_24M","HOT90_12M","HOT90_24M"
,"COLD1S_12M","COLD1S_24M","COLD2S_12M","COLD2S_24M","COLD2S_12M","COLD2S_24M","COLD32_12M","COLD32_24M")
PRCPGroup4 = c("PRCPAVG_12M","PRCPAVG_24M","PRCP_12M","PRCP_24M","MAXPRCP1W_12M","MAXPRCP1W_24M"
,"MDRN_12M","MDRN_24M")
corTMAXgroup1 = cortable[which(cortable$varname %in% TMAXGroup1),]
corPRCPgroup1 = cortable[which(cortable$varname %in% PRCPGroup1),]
corTMAXgroup2 = cortable[which(cortable$varname %in% TMAXGroup2),]
corPRCPgroup2 = cortable[which(cortable$varname %in% PRCPGroup2),]
corTMAXgroup3 = cortable[which(cortable$varname %in% TMAXGroup3),]
corPRCPgroup3 = cortable[which(cortable$varname %in% PRCPGroup3),]
corTMAXgroup4 = cortable[which(cortable$varname %in% TMAXGroup4),]
corPRCPgroup4 = cortable[which(cortable$varname %in% PRCPGroup4),]
usevaridx = c(23,44,85,70,118,94,124,38,88,54,55,79,164,42)
#####
# Make regression models to test
is.odd <- function(x) x %% 2 != 0
oddix = which(is.odd(years2)==TRUE)
evenix = which(is.odd(years2)==FALSE)
traingroup = NULL
predgroup = NULL
for(i in 1:length(oddix)){
traingroup = rbind(traingroup,fulldata2[which(fulldata2$YEAR==years2[oddix[i]]),])
}
for(i in 1:length(evenix)){
predgroup = rbind(predgroup,fulldata2[which(fulldata2$YEAR==years2[evenix[i]]),])
}
######
xmat = as.matrix(traingroup[,usevaridx[-c(1,12)]])
ymat = as.matrix(traingroup[,4])
NAidx = which(is.na(ymat)==TRUE)
xmat = xmat[-NAidx,]
ymat = ymat[-NAidx,]
NAidx = which(is.na(xmat)==TRUE,arr.ind = TRUE)
NAidxu = unique(NAidx[,1])
xmat = xmat[-NAidxu,]
ymat = ymat[-NAidxu]
fit <- lars(xmat,ymat , type="lasso")
#plot(fit)
best_step <- fit$df[which.min(fit$RSS)]
predictions <- predict(fit, xmat, s=best_step, type="fit")$fit
predictions = ifelse(predictions<0,0,predictions)
plot(ymat,type="l")
lines(predictions,col="blue")
legend("topright",legend=c("Observed","Modeled"),col=c("black","blue"),lwd=1)
plot(ymat[400:600],type="l")
lines(predictions[400:600],col="blue")
legend("topright",legend=c("Observed","Modeled"),col=c("black","blue"),lwd=1)
plot(predictions-ymat,type="l")
allRMSE = sqrt(mean((predictions-ymat)^2))
allcor = cor(ymat,predictions)
qqplot(ymat,predictions,ylim=range(c(predictions,ymat),na.rm=TRUE),xlim=range(c(predictions,ymat),na.rm=TRUE))
abline(coef=c(0,1),lty=2)
rmidx= which(ymat>=quantile(ymat,probs=0.99,na.rm=TRUE))
cor(ymat[-rmidx],predictions[-rmidx])
sqrt(mean((predictions[-rmidx]-ymat[-rmidx])^2))
logpred = log(predictions)
NAidx2=which(is.na(logpred)==TRUE | logpred == -Inf)
plot(density(log(ymat)),xlab="ln(streamflow)",main="streamflow pdfs")
lines(density(logpred[-NAidx2]),col="blue")
legend("topright",legend=c("Observed","Modeled"),col=c("black","blue"),lwd=1)
######
allnames = names(traingroup[,usevaridx])
varsusedall = list()
corsusedall = list()
RMSEsusedall = list()
for(c in 0:(length(allnames)-1)){
combos = combn(1:length(allnames),c)
varswithin = list()
corswithin = list()
RMSEswithin = list()
pdf(paste("/home/woot0002/streamflowregressiontests_5daymovingmean_",c,"varsout.pdf",sep=""),onefile=TRUE,width=5,height=5)
if(c==0){
endpoint=1
} else {
endpoint=ncol(combos)
}
for(i in 1:ncol(combos)){
if(c!=0){
idxout = c(combos[,i])
xmat = as.matrix(traingroup[,usevaridx])
xmat = xmat[,-idxout]
varswithin[[i]] = allnames[-c(combos[,i])]
} else {
xmat=as.matrix(traingroup[,usevaridx])
varswithin[[i]] = allnames
}
ymat = as.matrix(traingroup[,4])
NAidx = which(is.na(ymat)==TRUE)
if(length(NAidx)>0){
if(c<(length(allnames)-1)){
xmat = xmat[-NAidx,]
} else {
xmat = xmat[-NAidx]
}
ymat = ymat[-NAidx,]
}
NAidx = which(is.na(xmat)==TRUE,arr.ind = TRUE)
if(c<(length(allnames)-1)){
NAidxu = unique(NAidx[,1])
} else {
NAidxu = NAidx
}
if(c==(length(allnames)-1)){
xmat = as.matrix(xmat)
ymat = as.matrix(ymat)
}
if(length(NAidxu)>0){
xmat = xmat[-NAidxu,]
ymat = ymat[-NAidxu]
}
if(c==(length(allnames)-1)){
xmat = as.matrix(xmat)
}
ymat = as.matrix(ymat)
try(fit <- lars(xmat,ymat , type="lasso"))
#plot(fit)
best_step <- fit$df[which.min(fit$RSS)]
predictions <- predict(fit, xmat, s=best_step, type="fit")$fit
predictions = ifelse(predictions<0,0,predictions)
RMSEswithin[[i]] = sqrt(mean((predictions-ymat)^2))
corswithin[[i]] = cor(ymat,predictions)
logpred = log(predictions)
plot(density(log(ymat)),main=paste("Observed vs. Modeled Streamflow \n",c," vars left out, version ",i," / ",ncol(combos)),xlab="ln(streamflow)")
try(lines(density(logpred),col="red"))
text(-2,0.5,labels=paste("cor = ",round(corswithin[[i]],4),sep=""),cex=1,pos = 4)
text(-2,0.45,labels=paste("RMSE = ",round(RMSEswithin[[i]],4),sep=""),cex=1,pos = 4)
legend("topright",legend=c("Observed","Modeled"),col=c("black","red"),lty=1)
}
#save(list=c("varswithin","corswithin","RMSEswithin"),file=paste("/home/woot0002/streamflowtests_complexresults_",c,"varsleftout.Rdata",sep=""))
varsusedall[[(c+1)]] = varswithin
corsusedall[[(c+1)]] = corswithin
RMSEsusedall[[(c+1)]] = RMSEswithin
dev.off()
}
save(list=c("varsusedall","corsusedall","RMSEsusedall"),file="/home/woot0002/streamflowtests_5daymovingmean.Rdata")
|
/streamflowregtests_all_5daymean.R
|
no_license
|
amwootte/analysisscripts
|
R
| false
| false
| 28,714
|
r
|
#####
#
# streamflow testing - regression
library(optparse)
source("/data2/3to5/I35/scripts/analysisfunctions.R")
#source("/data2/3to5/I35/scripts/colorramp.R")
library(ncdf4)
library(maps)
library(fields)
library(sp)
library(raster)
library(rasterVis)
library(maptools)
library(ggplot2)
library(zoo)
library(lars)
library(mailR)
# email settings
emadd = "amwootte@ou.edu"
pswd = "xKFkcBZ6oN"
streamflow = read.table("/home/woot0002/streamflow_08146000",header=TRUE,sep="\t",fill=TRUE)
climate = read.table("/home/woot0002/2444385.csv",header=TRUE,sep=",")
names(streamflow) = c("agency","site","DATE","streamflow_mean","streamflow_mean_QC","streamflow_max","streamflow_max_QC","streamflow_min","streamflow_min_QC")
fulldata = merge(streamflow,climate,by="DATE")
fulldata$streamflow_mean=as.numeric(fulldata$streamflow_mean)
tmp = c(NA,NA,rollapply(fulldata$streamflow_mean,5,mean,na.rm=TRUE),NA,NA)
fulldata$streamflow_mean=tmp
fulldata$PRCP=as.numeric(fulldata$PRCP)
fulldata$TMAX=as.numeric(fulldata$TMAX)
fulldata$TMIN=as.numeric(fulldata$TMIN)
fulldata$TAVG=(as.numeric(fulldata$TMAX)+as.numeric(fulldata$TMIN))/2
fulldata$SNOW=as.numeric(fulldata$SNOW)
fulldata$DAPR=as.numeric(fulldata$DAPR)
fulldata$DASF=as.numeric(fulldata$DASF)
fulldata$MDPR=as.numeric(fulldata$MDPR)
fulldata$MDSF=as.numeric(fulldata$MDSF)
fulldata$SNWD=as.numeric(fulldata$SNWD)
fulldata$HOT1S = ifelse(fulldata$TMAX>mean(fulldata$TMAX,na.rm=TRUE)+sd(fulldata$TMAX,na.rm=TRUE),1,0) # hotdays 1 sd, 2 sd, 3 sd, and above 90F
fulldata$HOT2S = ifelse(fulldata$TMAX>mean(fulldata$TMAX,na.rm=TRUE)+2*sd(fulldata$TMAX,na.rm=TRUE),1,0)
fulldata$HOT3S = ifelse(fulldata$TMAX>mean(fulldata$TMAX,na.rm=TRUE)+3*sd(fulldata$TMAX,na.rm=TRUE),1,0)
fulldata$HOT90 = ifelse(fulldata$TMAX>90,1,0)
fulldata$COLD1S = ifelse(fulldata$TMIN<mean(fulldata$TMIN,na.rm=TRUE)+sd(fulldata$TMIN,na.rm=TRUE),1,0) # hotdays 1 sd, 2 sd, 3 sd, and above 90F
fulldata$COLD2S = ifelse(fulldata$TMIN<mean(fulldata$TMIN,na.rm=TRUE)+2*sd(fulldata$TMIN,na.rm=TRUE),1,0)
fulldata$COLD3S = ifelse(fulldata$TMIN<mean(fulldata$TMIN,na.rm=TRUE)+3*sd(fulldata$TMIN,na.rm=TRUE),1,0)
fulldata$COLD32 = ifelse(fulldata$TMIN<32,1,0)
fulldata$TAVG_3D = c(rep(NA,2),rollapply(fulldata$TAVG,width=3,FUN=mean,na.rm=TRUE))
fulldata$TAVG_1W = c(rep(NA,6),rollapply(fulldata$TAVG,width=7,FUN=mean,na.rm=TRUE))
fulldata$TAVG_2W = c(rep(NA,13),rollapply(fulldata$TAVG,width=14,FUN=mean,na.rm=TRUE))
fulldata$TAVG_3W = c(rep(NA,20),rollapply(fulldata$TAVG,width=21,FUN=mean,na.rm=TRUE))
fulldata$TAVG_4W = c(rep(NA,27),rollapply(fulldata$TAVG,width=28,FUN=mean,na.rm=TRUE))
fulldata$TAVG_1M = c(rep(NA,29),rollapply(fulldata$TAVG,width=30,FUN=mean,na.rm=TRUE))
fulldata$TAVG_2M = c(rep(NA,59),rollapply(fulldata$TAVG,width=60,FUN=mean,na.rm=TRUE))
fulldata$TAVG_3M = c(rep(NA,89),rollapply(fulldata$TAVG,width=90,FUN=mean,na.rm=TRUE))
fulldata$TAVG_4M = c(rep(NA,119),rollapply(fulldata$TAVG,width=120,FUN=mean,na.rm=TRUE))
fulldata$TAVG_5M = c(rep(NA,149),rollapply(fulldata$TAVG,width=150,FUN=mean,na.rm=TRUE))
fulldata$TAVG_6M = c(rep(NA,179),rollapply(fulldata$TAVG,width=180,FUN=mean,na.rm=TRUE))
fulldata$TAVG_12M = c(rep(NA,364),rollapply(fulldata$TAVG,width=365,FUN=mean,na.rm=TRUE))
fulldata$TAVG_24M = c(rep(NA,729),rollapply(fulldata$TAVG,width=730,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_3D = c(rep(NA,2),rollapply(fulldata$PRCP,width=3,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_1W = c(rep(NA,6),rollapply(fulldata$PRCP,width=7,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_2W = c(rep(NA,13),rollapply(fulldata$PRCP,width=14,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_3W = c(rep(NA,20),rollapply(fulldata$PRCP,width=21,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_4W = c(rep(NA,27),rollapply(fulldata$PRCP,width=28,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_1M = c(rep(NA,29),rollapply(fulldata$PRCP,width=30,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_2M = c(rep(NA,59),rollapply(fulldata$PRCP,width=60,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_3M = c(rep(NA,89),rollapply(fulldata$PRCP,width=90,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_4M = c(rep(NA,119),rollapply(fulldata$PRCP,width=120,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_5M = c(rep(NA,149),rollapply(fulldata$PRCP,width=150,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_6M = c(rep(NA,179),rollapply(fulldata$PRCP,width=180,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_12M = c(rep(NA,364),rollapply(fulldata$PRCP,width=365,FUN=mean,na.rm=TRUE))
fulldata$PRCPAVG_24M = c(rep(NA,729),rollapply(fulldata$PRCP,width=730,FUN=mean,na.rm=TRUE))
fulldata$PRCP_3D = c(rep(NA,2),rollapply(fulldata$PRCP,width=3,FUN=sum,na.rm=TRUE))
fulldata$PRCP_1W = c(rep(NA,6),rollapply(fulldata$PRCP,width=7,FUN=sum,na.rm=TRUE))
fulldata$PRCP_2W = c(rep(NA,13),rollapply(fulldata$PRCP,width=14,FUN=sum,na.rm=TRUE))
fulldata$PRCP_3W = c(rep(NA,20),rollapply(fulldata$PRCP,width=21,FUN=sum,na.rm=TRUE))
fulldata$PRCP_4W = c(rep(NA,27),rollapply(fulldata$PRCP,width=28,FUN=sum,na.rm=TRUE))
fulldata$PRCP_1M = c(rep(NA,29),rollapply(fulldata$PRCP,width=30,FUN=sum,na.rm=TRUE))
fulldata$PRCP_2M = c(rep(NA,59),rollapply(fulldata$PRCP,width=60,FUN=sum,na.rm=TRUE))
fulldata$PRCP_3M = c(rep(NA,89),rollapply(fulldata$PRCP,width=90,FUN=sum,na.rm=TRUE))
fulldata$PRCP_4M = c(rep(NA,119),rollapply(fulldata$PRCP,width=120,FUN=sum,na.rm=TRUE))
fulldata$PRCP_5M = c(rep(NA,149),rollapply(fulldata$PRCP,width=150,FUN=sum,na.rm=TRUE))
fulldata$PRCP_6M = c(rep(NA,179),rollapply(fulldata$PRCP,width=180,FUN=sum,na.rm=TRUE))
fulldata$PRCP_12M = c(rep(NA,364),rollapply(fulldata$PRCP,width=365,FUN=sum,na.rm=TRUE))
fulldata$PRCP_24M = c(rep(NA,729),rollapply(fulldata$PRCP,width=730,FUN=sum,na.rm=TRUE))
fulldata$MAXPRCP1W_2W = c(rep(NA,13),rollapply(fulldata$PRCP_1W,width=14,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_3W = c(rep(NA,20),rollapply(fulldata$PRCP_1W,width=21,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_4W = c(rep(NA,27),rollapply(fulldata$PRCP_1W,width=28,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_1M = c(rep(NA,29),rollapply(fulldata$PRCP_1W,width=30,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_2M = c(rep(NA,59),rollapply(fulldata$PRCP_1W,width=60,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_3M = c(rep(NA,89),rollapply(fulldata$PRCP_1W,width=90,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_4M = c(rep(NA,119),rollapply(fulldata$PRCP_1W,width=120,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_5M = c(rep(NA,149),rollapply(fulldata$PRCP_1W,width=150,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_6M = c(rep(NA,179),rollapply(fulldata$PRCP_1W,width=180,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_12M = c(rep(NA,364),rollapply(fulldata$PRCP_1W,width=365,FUN=max,na.rm=TRUE))
fulldata$MAXPRCP1W_24M = c(rep(NA,729),rollapply(fulldata$PRCP_1W,width=730,FUN=max,na.rm=TRUE))
fulldata$MDRN = ifelse(fulldata$PRCP<0.01,0,1)
fulldata$MDRN_1W = c(rep(NA,6),rollapply(fulldata$MDRN,width=7,FUN=sum,na.rm=TRUE))
fulldata$MDRN_2W = c(rep(NA,13),rollapply(fulldata$MDRN,width=14,FUN=sum,na.rm=TRUE))
fulldata$MDRN_3W = c(rep(NA,20),rollapply(fulldata$MDRN,width=21,FUN=sum,na.rm=TRUE))
fulldata$MDRN_4W = c(rep(NA,27),rollapply(fulldata$MDRN,width=28,FUN=sum,na.rm=TRUE))
fulldata$MDRN_1M = c(rep(NA,29),rollapply(fulldata$MDRN,width=30,FUN=sum,na.rm=TRUE))
fulldata$MDRN_2M = c(rep(NA,59),rollapply(fulldata$MDRN,width=60,FUN=sum,na.rm=TRUE))
fulldata$MDRN_3M = c(rep(NA,89),rollapply(fulldata$MDRN,width=90,FUN=sum,na.rm=TRUE))
fulldata$MDRN_4M = c(rep(NA,119),rollapply(fulldata$MDRN,width=120,FUN=sum,na.rm=TRUE))
fulldata$MDRN_5M = c(rep(NA,149),rollapply(fulldata$MDRN,width=150,FUN=sum,na.rm=TRUE))
fulldata$MDRN_6M = c(rep(NA,179),rollapply(fulldata$MDRN,width=180,FUN=sum,na.rm=TRUE))
fulldata$MDRN_12M = c(rep(NA,364),rollapply(fulldata$MDRN,width=365,FUN=sum,na.rm=TRUE))
fulldata$MDRN_24M = c(rep(NA,729),rollapply(fulldata$MDRN,width=730,FUN=sum,na.rm=TRUE))
fulldata$TMAXAVG_1W = c(rep(NA,6),rollapply(fulldata$TMAX,width=7,FUN=mean,na.rm=TRUE))
fulldata$MAXTMAX1W_2W = c(rep(NA,13),rollapply(fulldata$TMAXAVG_1W,width=14,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_3W = c(rep(NA,20),rollapply(fulldata$TMAXAVG_1W,width=21,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_4W = c(rep(NA,27),rollapply(fulldata$TMAXAVG_1W,width=28,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_1M = c(rep(NA,29),rollapply(fulldata$TMAXAVG_1W,width=30,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_2M = c(rep(NA,59),rollapply(fulldata$TMAXAVG_1W,width=60,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_3M = c(rep(NA,89),rollapply(fulldata$TMAXAVG_1W,width=90,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_4M = c(rep(NA,119),rollapply(fulldata$TMAXAVG_1W,width=120,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_5M = c(rep(NA,149),rollapply(fulldata$TMAXAVG_1W,width=150,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_6M = c(rep(NA,179),rollapply(fulldata$TMAXAVG_1W,width=180,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_12M = c(rep(NA,364),rollapply(fulldata$TMAXAVG_1W,width=365,FUN=max,na.rm=TRUE))
fulldata$MAXTMAX1W_24M = c(rep(NA,729),rollapply(fulldata$TMAXAVG_1W,width=730,FUN=max,na.rm=TRUE))
fulldata$TMINAVG_1W = c(rep(NA,6),rollapply(fulldata$TMAX,width=7,FUN=mean,na.rm=TRUE))
fulldata$MINTMIN1W_2W = c(rep(NA,13),rollapply(fulldata$TMINAVG_1W,width=14,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_3W = c(rep(NA,20),rollapply(fulldata$TMINAVG_1W,width=21,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_4W = c(rep(NA,27),rollapply(fulldata$TMINAVG_1W,width=28,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_1M = c(rep(NA,29),rollapply(fulldata$TMINAVG_1W,width=30,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_2M = c(rep(NA,59),rollapply(fulldata$TMINAVG_1W,width=60,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_3M = c(rep(NA,89),rollapply(fulldata$TMINAVG_1W,width=90,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_4M = c(rep(NA,119),rollapply(fulldata$TMINAVG_1W,width=120,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_5M = c(rep(NA,149),rollapply(fulldata$TMINAVG_1W,width=150,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_6M = c(rep(NA,179),rollapply(fulldata$TMINAVG_1W,width=180,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_12M = c(rep(NA,364),rollapply(fulldata$TMINAVG_1W,width=365,FUN=min,na.rm=TRUE))
fulldata$MINTMIN1W_24M = c(rep(NA,729),rollapply(fulldata$TMINAVG_1W,width=730,FUN=min,na.rm=TRUE))
fulldata$HOT1S_1W = c(rep(NA,6),rollapply(fulldata$HOT1S,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_2W = c(rep(NA,13),rollapply(fulldata$HOT1S,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_3W = c(rep(NA,20),rollapply(fulldata$HOT1S,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_4W = c(rep(NA,27),rollapply(fulldata$HOT1S,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_1M = c(rep(NA,29),rollapply(fulldata$HOT1S,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_2M = c(rep(NA,59),rollapply(fulldata$HOT1S,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_3M = c(rep(NA,89),rollapply(fulldata$HOT1S,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_4M = c(rep(NA,119),rollapply(fulldata$HOT1S,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_5M = c(rep(NA,149),rollapply(fulldata$HOT1S,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_6M = c(rep(NA,179),rollapply(fulldata$HOT1S,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_12M = c(rep(NA,364),rollapply(fulldata$HOT1S,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT1S_24M = c(rep(NA,729),rollapply(fulldata$HOT1S,width=730,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_1W = c(rep(NA,6),rollapply(fulldata$HOT2S,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_2W = c(rep(NA,13),rollapply(fulldata$HOT2S,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_3W = c(rep(NA,20),rollapply(fulldata$HOT2S,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_4W = c(rep(NA,27),rollapply(fulldata$HOT2S,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_1M = c(rep(NA,29),rollapply(fulldata$HOT2S,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_2M = c(rep(NA,59),rollapply(fulldata$HOT2S,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_3M = c(rep(NA,89),rollapply(fulldata$HOT2S,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_4M = c(rep(NA,119),rollapply(fulldata$HOT2S,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_5M = c(rep(NA,149),rollapply(fulldata$HOT2S,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_6M = c(rep(NA,179),rollapply(fulldata$HOT2S,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_12M = c(rep(NA,364),rollapply(fulldata$HOT2S,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT2S_24M = c(rep(NA,729),rollapply(fulldata$HOT2S,width=730,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_1W = c(rep(NA,6),rollapply(fulldata$HOT3S,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_2W = c(rep(NA,13),rollapply(fulldata$HOT3S,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_3W = c(rep(NA,20),rollapply(fulldata$HOT3S,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_4W = c(rep(NA,27),rollapply(fulldata$HOT3S,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_1M = c(rep(NA,29),rollapply(fulldata$HOT3S,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_2M = c(rep(NA,59),rollapply(fulldata$HOT3S,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_3M = c(rep(NA,89),rollapply(fulldata$HOT3S,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_4M = c(rep(NA,119),rollapply(fulldata$HOT3S,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_5M = c(rep(NA,149),rollapply(fulldata$HOT3S,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_6M = c(rep(NA,179),rollapply(fulldata$HOT3S,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_12M = c(rep(NA,364),rollapply(fulldata$HOT3S,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT3S_24M = c(rep(NA,729),rollapply(fulldata$HOT3S,width=730,FUN=sum,na.rm=TRUE))
fulldata$HOT90_1W = c(rep(NA,6),rollapply(fulldata$HOT90,width=7,FUN=sum,na.rm=TRUE))
fulldata$HOT90_2W = c(rep(NA,13),rollapply(fulldata$HOT90,width=14,FUN=sum,na.rm=TRUE))
fulldata$HOT90_3W = c(rep(NA,20),rollapply(fulldata$HOT90,width=21,FUN=sum,na.rm=TRUE))
fulldata$HOT90_4W = c(rep(NA,27),rollapply(fulldata$HOT90,width=28,FUN=sum,na.rm=TRUE))
fulldata$HOT90_1M = c(rep(NA,29),rollapply(fulldata$HOT90,width=30,FUN=sum,na.rm=TRUE))
fulldata$HOT90_2M = c(rep(NA,59),rollapply(fulldata$HOT90,width=60,FUN=sum,na.rm=TRUE))
fulldata$HOT90_3M = c(rep(NA,89),rollapply(fulldata$HOT90,width=90,FUN=sum,na.rm=TRUE))
fulldata$HOT90_4M = c(rep(NA,119),rollapply(fulldata$HOT90,width=120,FUN=sum,na.rm=TRUE))
fulldata$HOT90_5M = c(rep(NA,149),rollapply(fulldata$HOT90,width=150,FUN=sum,na.rm=TRUE))
fulldata$HOT90_6M = c(rep(NA,179),rollapply(fulldata$HOT90,width=180,FUN=sum,na.rm=TRUE))
fulldata$HOT90_12M = c(rep(NA,364),rollapply(fulldata$HOT90,width=365,FUN=sum,na.rm=TRUE))
fulldata$HOT90_24M = c(rep(NA,729),rollapply(fulldata$HOT90,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_1W = c(rep(NA,6),rollapply(fulldata$COLD1S,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_2W = c(rep(NA,13),rollapply(fulldata$COLD1S,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_3W = c(rep(NA,20),rollapply(fulldata$COLD1S,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_4W = c(rep(NA,27),rollapply(fulldata$COLD1S,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_1M = c(rep(NA,29),rollapply(fulldata$COLD1S,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_2M = c(rep(NA,59),rollapply(fulldata$COLD1S,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_3M = c(rep(NA,89),rollapply(fulldata$COLD1S,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_4M = c(rep(NA,119),rollapply(fulldata$COLD1S,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_5M = c(rep(NA,149),rollapply(fulldata$COLD1S,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_6M = c(rep(NA,179),rollapply(fulldata$COLD1S,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_12M = c(rep(NA,364),rollapply(fulldata$COLD1S,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD1S_24M = c(rep(NA,729),rollapply(fulldata$COLD1S,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_1W = c(rep(NA,6),rollapply(fulldata$COLD2S,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_2W = c(rep(NA,13),rollapply(fulldata$COLD2S,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_3W = c(rep(NA,20),rollapply(fulldata$COLD2S,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_4W = c(rep(NA,27),rollapply(fulldata$COLD2S,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_1M = c(rep(NA,29),rollapply(fulldata$COLD2S,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_2M = c(rep(NA,59),rollapply(fulldata$COLD2S,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_3M = c(rep(NA,89),rollapply(fulldata$COLD2S,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_4M = c(rep(NA,119),rollapply(fulldata$COLD2S,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_5M = c(rep(NA,149),rollapply(fulldata$COLD2S,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_6M = c(rep(NA,179),rollapply(fulldata$COLD2S,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_12M = c(rep(NA,364),rollapply(fulldata$COLD2S,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD2S_24M = c(rep(NA,729),rollapply(fulldata$COLD2S,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_1W = c(rep(NA,6),rollapply(fulldata$COLD3S,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_2W = c(rep(NA,13),rollapply(fulldata$COLD3S,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_3W = c(rep(NA,20),rollapply(fulldata$COLD3S,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_4W = c(rep(NA,27),rollapply(fulldata$COLD3S,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_1M = c(rep(NA,29),rollapply(fulldata$COLD3S,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_2M = c(rep(NA,59),rollapply(fulldata$COLD3S,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_3M = c(rep(NA,89),rollapply(fulldata$COLD3S,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_4M = c(rep(NA,119),rollapply(fulldata$COLD3S,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_5M = c(rep(NA,149),rollapply(fulldata$COLD3S,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_6M = c(rep(NA,179),rollapply(fulldata$COLD3S,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_12M = c(rep(NA,364),rollapply(fulldata$COLD3S,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD3S_24M = c(rep(NA,729),rollapply(fulldata$COLD3S,width=730,FUN=sum,na.rm=TRUE))
fulldata$COLD32_1W = c(rep(NA,6),rollapply(fulldata$COLD32,width=7,FUN=sum,na.rm=TRUE))
fulldata$COLD32_2W = c(rep(NA,13),rollapply(fulldata$COLD32,width=14,FUN=sum,na.rm=TRUE))
fulldata$COLD32_3W = c(rep(NA,20),rollapply(fulldata$COLD32,width=21,FUN=sum,na.rm=TRUE))
fulldata$COLD32_4W = c(rep(NA,27),rollapply(fulldata$COLD32,width=28,FUN=sum,na.rm=TRUE))
fulldata$COLD32_1M = c(rep(NA,29),rollapply(fulldata$COLD32,width=30,FUN=sum,na.rm=TRUE))
fulldata$COLD32_2M = c(rep(NA,59),rollapply(fulldata$COLD32,width=60,FUN=sum,na.rm=TRUE))
fulldata$COLD32_3M = c(rep(NA,89),rollapply(fulldata$COLD32,width=90,FUN=sum,na.rm=TRUE))
fulldata$COLD32_4M = c(rep(NA,119),rollapply(fulldata$COLD32,width=120,FUN=sum,na.rm=TRUE))
fulldata$COLD32_5M = c(rep(NA,149),rollapply(fulldata$COLD32,width=150,FUN=sum,na.rm=TRUE))
fulldata$COLD32_6M = c(rep(NA,179),rollapply(fulldata$COLD32,width=180,FUN=sum,na.rm=TRUE))
fulldata$COLD32_12M = c(rep(NA,364),rollapply(fulldata$COLD32,width=365,FUN=sum,na.rm=TRUE))
fulldata$COLD32_24M = c(rep(NA,729),rollapply(fulldata$COLD32,width=730,FUN=sum,na.rm=TRUE))
percentile_bottom = quantile(fulldata$PRCP_1M,probs=0.25,na.rm=TRUE)
percentile_top = quantile(fulldata$PRCP_1M,probs=0.75,na.rm=TRUE)
precip_hardcode = fulldata$PRCP_1M
precip_hardcode=ifelse(fulldata$PRCP_1M<=percentile_bottom | fulldata$PRCP_1M>=percentile_top,ifelse(fulldata$PRCP_1M<=percentile_bottom,0,2),1)
tmp = precip_hardcode[1:(length(fulldata$PRCP_1M)-10)]-precip_hardcode[11:length(fulldata$PRCP_1M)]
tmpdp = c(ifelse(tmp==-2,1,0),rep(NA,10))
tmppd = c(ifelse(tmp==2,1,0),rep(NA,10))
PDcount_PRCP = sum(tmppd,na.rm=TRUE)
DPcount_PRCP = sum(tmpdp,na.rm=TRUE)
fulldata$PRCP_DP = tmpdp
fulldata$PRCP_PD = tmppd
fulldata$PRCP_WP = c(tmp,rep(NA,10))
fulldata$SFM_1M = c(rep(NA,29),rollapply(fulldata$streamflow_mean,width=30,FUN=mean,na.rm=TRUE))
#fulldata$SFM_1M = c(rep(NA,29),rollapply(fulldata$streamflow_mean,width=30,FUN=sum,na.rm=TRUE))
percentile_bottom = quantile(fulldata$SFM_1M,probs=0.25,na.rm=TRUE)
percentile_top = quantile(fulldata$SFM_1M,probs=0.75,na.rm=TRUE)
precip_hardcode = fulldata$SFM_1M
precip_hardcode=ifelse(fulldata$SFM_1M<=percentile_bottom | fulldata$SFM_1M>=percentile_top,ifelse(fulldata$SFM_1M<=percentile_bottom,0,2),1)
tmp = precip_hardcode[1:(length(fulldata$SFM_1M)-10)]-precip_hardcode[11:length(fulldata$SFM_1M)]
tmpdp = c(ifelse(tmp==-2,1,0),rep(NA,10))
tmppd = c(ifelse(tmp==2,1,0),rep(NA,10))
PDcount_SFM = sum(tmppd,na.rm=TRUE)
DPcount_SFM = sum(tmpdp,na.rm=TRUE)
fulldata$SFM_DP = tmpdp
fulldata$SFM_PD = tmppd
fulldata$SFM_WP = c(tmp,rep(NA,10))
#####
# correlation table
fulldata$YEAR = as.numeric(substr(fulldata$DATE,1,4))
years = unique(fulldata$YEAR)
fulldata2 = fulldata[which(fulldata$YEAR>=1950 & fulldata$YEAR<=2015),]
years2 = unique(fulldata2$YEAR)
cortable = NULL
for(j in 16:ncol(fulldata2)){
J=j
varname = names(fulldata2)[j]
corval = cor(as.numeric(fulldata2$streamflow_mean),as.numeric(fulldata2[,j]),method="spearman",use="pairwise.complete.obs")
tmp=data.frame(J,varname,corval)
cortable=rbind(cortable,tmp)
}
cortable$abscor = abs(cortable$corval)
sortidx = order(cortable$abscor,decreasing=TRUE)
cortable= cortable[sortidx,]
TMAXGroup1 = c("TAVG","TMAX","TMIN","TOBS","TAVG_3D","HOT1S","HOT2S","HOT3S","HOT90","COLD1S","COLD2S","COLD3S","COLD32")
PRCPGroup1 = c("SNOW","SNWD","PRCP","PRCP_3D","MDRN","PRCPAVG_3D")
TMAXGroup2 = c("TAVG_1W","TAVG_2W","TAVG_3W","TAVG_4W","TMAXAVG_1W","MAXTMAX1W_2W","MAXTMAX1W_3W","MAXTMAX1W_4W","TMINAVG_1W","MINTMIN1W_2W","MINTMIN1W_3W","MINTMIN1W_4W"
,"HOT1S_1W","HOT1S_2W","HOT1S_3W","HOT1S_4W","HOT2S_1W","HOT2S_2W","HOT2S_3W","HOT2S_4W","HOT3S_1W","HOT3S_2W","HOT3S_3W","HOT3S_4W"
,"HOT90_1W","HOT90_2W","HOT90_3W","HOT90_4W","COLD1S_1W","COLD1S_2W","COLD1S_3W","COLD1S_4W","COLD2S_1W","COLD2S_2W","COLD2S_3W","COLD2S_4W"
,"COLD3S_1W","COLD3S_2W","COLD3S_3W","COLD3S_4W","COLD32_1W","COLD32_2W","COLD32_3W","COLD32_4W")
PRCPGroup2 = c("PRCPAVG_1W","PRCPAVG_2W","PRCPAVG_3W","PRCPAVG_4W","PRCP_1W","PRCP_2W","PRCP_3W","PRCP_4W"
,"MDRN_1W","MDRN_2W","MDRN_3W","MDRN_4W","MAXPRCP1W_2W","MAXPRCP1W_3W","MAXPRCP1W_4W")
TMAXGroup3 = c("TAVG_1M","TAVG_2M","TAVG_3M","TAVG_4M","TAVG_5M","TAVG_6M","MAXTMAX1W_1M","MAXTMAX1W_2M","MAXTMAX1W_3M"
,"MAXTMAX1W_4M","MAXTMAX1W_5M","MAXTMAX1W_6M","MINTMIN1W_1M","MINTMIN1W_2M","MINTMIN1W_3M","MINTMIN1W_4M"
,"MINTMIN1W_5M","MINTMIN1W_6M","HOT1S_1M","HOT1S_2M","HOT1S_3M","HOT1S_4M","HOT1S_5M","HOT1S_6M"
,"HOT2S_1M","HOT2S_2M","HOT2S_3M","HOT2S_4M","HOT2S_5M","HOT2S_6M"
,"HOT3S_1M","HOT3S_2M","HOT3S_3M","HOT3S_4M","HOT3S_5M","HOT3S_6M"
,"HOT90_1M","HOT90_2M","HOT90_3M","HOT90_4M","HOT90_5M","HOT90_6M"
,"COLD1S_1M","COLD1S_2M","COLD1S_3M","COLD1S_4M","COLD1S_5M","COLD1S_6M"
,"COLD2S_1M","COLD2S_2M","COLD2S_3M","COLD2S_4M","COLD2S_5M","COLD2S_6M"
,"COLD3S_1M","COLD3S_2M","COLD3S_3M","COLD3S_4M","COLD3S_5M","COLD3S_6M"
,"COLD32_1M","COLD32_2M","COLD32_3M","COLD32_4M","COLD32_5M","COLD32_6M")
PRCPGroup3 = c("PRCPAVG_1M","PRCPAVG_2M","PRCPAVG_3M","PRCPAVG_4M","PRCPAVG_5M","PRCPAVG_6M"
,"PRCP_1M","PRCP_2M","PRCP_3M","PRCP_4M","PRCP_5M","PRCP_6M"
,"MAXPRCP1W_1M","MAXPRCP1W_2M","MAXPRCP1W_3M","MAXPRCP1W_4M","MAXPRCP1W_5M","MAXPRCP1W_6M"
,"MDRN_1M","MDRN_2M","MDRN_3M","MDRN_4M","MDRN_5M","MDRN_6M")
TMAXGroup4 = c("TAVG_12M","TAVG_24M","MAXTMAX1W_12M","MAXTMAX1W_24M","MINTMIN1W_12M","MINTMIN1W_24M"
,"HOT1S_12M","HOT1S_24M","HOT2S_12M","HOT2S_24M","HOT3S_12M","HOT3S_24M","HOT90_12M","HOT90_24M"
,"COLD1S_12M","COLD1S_24M","COLD2S_12M","COLD2S_24M","COLD2S_12M","COLD2S_24M","COLD32_12M","COLD32_24M")
PRCPGroup4 = c("PRCPAVG_12M","PRCPAVG_24M","PRCP_12M","PRCP_24M","MAXPRCP1W_12M","MAXPRCP1W_24M"
,"MDRN_12M","MDRN_24M")
corTMAXgroup1 = cortable[which(cortable$varname %in% TMAXGroup1),]
corPRCPgroup1 = cortable[which(cortable$varname %in% PRCPGroup1),]
corTMAXgroup2 = cortable[which(cortable$varname %in% TMAXGroup2),]
corPRCPgroup2 = cortable[which(cortable$varname %in% PRCPGroup2),]
corTMAXgroup3 = cortable[which(cortable$varname %in% TMAXGroup3),]
corPRCPgroup3 = cortable[which(cortable$varname %in% PRCPGroup3),]
corTMAXgroup4 = cortable[which(cortable$varname %in% TMAXGroup4),]
corPRCPgroup4 = cortable[which(cortable$varname %in% PRCPGroup4),]
usevaridx = c(23,44,85,70,118,94,124,38,88,54,55,79,164,42)
#####
# Make regression models to test
is.odd <- function(x) x %% 2 != 0
oddix = which(is.odd(years2)==TRUE)
evenix = which(is.odd(years2)==FALSE)
traingroup = NULL
predgroup = NULL
for(i in 1:length(oddix)){
traingroup = rbind(traingroup,fulldata2[which(fulldata2$YEAR==years2[oddix[i]]),])
}
for(i in 1:length(evenix)){
predgroup = rbind(predgroup,fulldata2[which(fulldata2$YEAR==years2[evenix[i]]),])
}
######
xmat = as.matrix(traingroup[,usevaridx[-c(1,12)]])
ymat = as.matrix(traingroup[,4])
NAidx = which(is.na(ymat)==TRUE)
xmat = xmat[-NAidx,]
ymat = ymat[-NAidx,]
NAidx = which(is.na(xmat)==TRUE,arr.ind = TRUE)
NAidxu = unique(NAidx[,1])
xmat = xmat[-NAidxu,]
ymat = ymat[-NAidxu]
fit <- lars(xmat,ymat , type="lasso")
#plot(fit)
best_step <- fit$df[which.min(fit$RSS)]
predictions <- predict(fit, xmat, s=best_step, type="fit")$fit
predictions = ifelse(predictions<0,0,predictions)
plot(ymat,type="l")
lines(predictions,col="blue")
legend("topright",legend=c("Observed","Modeled"),col=c("black","blue"),lwd=1)
plot(ymat[400:600],type="l")
lines(predictions[400:600],col="blue")
legend("topright",legend=c("Observed","Modeled"),col=c("black","blue"),lwd=1)
plot(predictions-ymat,type="l")
allRMSE = sqrt(mean((predictions-ymat)^2))
allcor = cor(ymat,predictions)
qqplot(ymat,predictions,ylim=range(c(predictions,ymat),na.rm=TRUE),xlim=range(c(predictions,ymat),na.rm=TRUE))
abline(coef=c(0,1),lty=2)
rmidx= which(ymat>=quantile(ymat,probs=0.99,na.rm=TRUE))
cor(ymat[-rmidx],predictions[-rmidx])
sqrt(mean((predictions[-rmidx]-ymat[-rmidx])^2))
logpred = log(predictions)
NAidx2=which(is.na(logpred)==TRUE | logpred == -Inf)
plot(density(log(ymat)),xlab="ln(streamflow)",main="streamflow pdfs")
lines(density(logpred[-NAidx2]),col="blue")
legend("topright",legend=c("Observed","Modeled"),col=c("black","blue"),lwd=1)
######
allnames = names(traingroup[,usevaridx])
varsusedall = list()
corsusedall = list()
RMSEsusedall = list()
for(c in 0:(length(allnames)-1)){
combos = combn(1:length(allnames),c)
varswithin = list()
corswithin = list()
RMSEswithin = list()
pdf(paste("/home/woot0002/streamflowregressiontests_5daymovingmean_",c,"varsout.pdf",sep=""),onefile=TRUE,width=5,height=5)
if(c==0){
endpoint=1
} else {
endpoint=ncol(combos)
}
for(i in 1:ncol(combos)){
if(c!=0){
idxout = c(combos[,i])
xmat = as.matrix(traingroup[,usevaridx])
xmat = xmat[,-idxout]
varswithin[[i]] = allnames[-c(combos[,i])]
} else {
xmat=as.matrix(traingroup[,usevaridx])
varswithin[[i]] = allnames
}
ymat = as.matrix(traingroup[,4])
NAidx = which(is.na(ymat)==TRUE)
if(length(NAidx)>0){
if(c<(length(allnames)-1)){
xmat = xmat[-NAidx,]
} else {
xmat = xmat[-NAidx]
}
ymat = ymat[-NAidx,]
}
NAidx = which(is.na(xmat)==TRUE,arr.ind = TRUE)
if(c<(length(allnames)-1)){
NAidxu = unique(NAidx[,1])
} else {
NAidxu = NAidx
}
if(c==(length(allnames)-1)){
xmat = as.matrix(xmat)
ymat = as.matrix(ymat)
}
if(length(NAidxu)>0){
xmat = xmat[-NAidxu,]
ymat = ymat[-NAidxu]
}
if(c==(length(allnames)-1)){
xmat = as.matrix(xmat)
}
ymat = as.matrix(ymat)
try(fit <- lars(xmat,ymat , type="lasso"))
#plot(fit)
best_step <- fit$df[which.min(fit$RSS)]
predictions <- predict(fit, xmat, s=best_step, type="fit")$fit
predictions = ifelse(predictions<0,0,predictions)
RMSEswithin[[i]] = sqrt(mean((predictions-ymat)^2))
corswithin[[i]] = cor(ymat,predictions)
logpred = log(predictions)
plot(density(log(ymat)),main=paste("Observed vs. Modeled Streamflow \n",c," vars left out, version ",i," / ",ncol(combos)),xlab="ln(streamflow)")
try(lines(density(logpred),col="red"))
text(-2,0.5,labels=paste("cor = ",round(corswithin[[i]],4),sep=""),cex=1,pos = 4)
text(-2,0.45,labels=paste("RMSE = ",round(RMSEswithin[[i]],4),sep=""),cex=1,pos = 4)
legend("topright",legend=c("Observed","Modeled"),col=c("black","red"),lty=1)
}
#save(list=c("varswithin","corswithin","RMSEswithin"),file=paste("/home/woot0002/streamflowtests_complexresults_",c,"varsleftout.Rdata",sep=""))
varsusedall[[(c+1)]] = varswithin
corsusedall[[(c+1)]] = corswithin
RMSEsusedall[[(c+1)]] = RMSEswithin
dev.off()
}
save(list=c("varsusedall","corsusedall","RMSEsusedall"),file="/home/woot0002/streamflowtests_5daymovingmean.Rdata")
|
# read classes first to improve read performance total dataset
tab5rows <- read.table("household_power_consumption.txt", header = TRUE, sep=';', nrows = 5)
classes <- sapply(tab5rows, class)
# read total dataset
xf <- read.table("household_power_consumption.txt", header = TRUE, sep=';', na.string="?", colClasses = classes)
# convert date field tot Date format
dates <- xf$Date
dates <- as.Date(as.character(dates),"%d/%m/%Y")
xf$Date <- dates
# create subset for plot (1st 2 days of feb 2007)
xp <- subset(xf, Date == '2007-02-01' | Date == '2007-02-02')
# combine datetime variable
xp$DateTime <- as.POSIXct(paste(xp$Date, xp$Time), format="%Y-%m-%d %H:%M:%S")
# open device png
png("plot3.png")
#draw chart
plot(xp$DateTime,xp$Sub_metering_1, xlab="",ylab="Energy sub metering",type="l")
lines(xp$DateTime,xp$Sub_metering_2, col='red')
lines(xp$DateTime,xp$Sub_metering_3, col='blue')
legend("topright", c("Sub_metering_1", "Sub_metering_2","Sub_metering_3"), col = c("black", "red","blue"),lwd=1)
# close device
dev.off()
|
/project1/plot3.R
|
no_license
|
dwoltjer/ExData_Plotting1
|
R
| false
| false
| 1,036
|
r
|
# read classes first to improve read performance total dataset
tab5rows <- read.table("household_power_consumption.txt", header = TRUE, sep=';', nrows = 5)
classes <- sapply(tab5rows, class)
# read total dataset
xf <- read.table("household_power_consumption.txt", header = TRUE, sep=';', na.string="?", colClasses = classes)
# convert date field tot Date format
dates <- xf$Date
dates <- as.Date(as.character(dates),"%d/%m/%Y")
xf$Date <- dates
# create subset for plot (1st 2 days of feb 2007)
xp <- subset(xf, Date == '2007-02-01' | Date == '2007-02-02')
# combine datetime variable
xp$DateTime <- as.POSIXct(paste(xp$Date, xp$Time), format="%Y-%m-%d %H:%M:%S")
# open device png
png("plot3.png")
#draw chart
plot(xp$DateTime,xp$Sub_metering_1, xlab="",ylab="Energy sub metering",type="l")
lines(xp$DateTime,xp$Sub_metering_2, col='red')
lines(xp$DateTime,xp$Sub_metering_3, col='blue')
legend("topright", c("Sub_metering_1", "Sub_metering_2","Sub_metering_3"), col = c("black", "red","blue"),lwd=1)
# close device
dev.off()
|
#' fisher
#'
#' Performs a Fisher transformation on a number between -1 and 1. If input is
#' outside that range, returns 0.
#'
#' @param r Number between -1 and 1 to be transformed.
#'
#' @return If \code{-1 < r < 1}, Fisher transformed input. Else, 0.
#'
#' @export
fisher <- function(r){
# Set r=0 if outside range.
r <- r*(abs(r) < 1)
# Return fisher transform
return(.5*log((1+r)/(1-r)))
}
|
/DCM/R/fisher.R
|
no_license
|
oconnor-kevin/Differential-Correlation-Mining
|
R
| false
| false
| 401
|
r
|
#' fisher
#'
#' Performs a Fisher transformation on a number between -1 and 1. If input is
#' outside that range, returns 0.
#'
#' @param r Number between -1 and 1 to be transformed.
#'
#' @return If \code{-1 < r < 1}, Fisher transformed input. Else, 0.
#'
#' @export
fisher <- function(r){
# Set r=0 if outside range.
r <- r*(abs(r) < 1)
# Return fisher transform
return(.5*log((1+r)/(1-r)))
}
|
library("data.table")
dtime <- difftime(as.POSIXct("2007-02-03"), as.POSIXct("2007-02-01"),units="mins")
rowsToRead <- as.numeric(dtime)
DT <- fread("household_power_consumption.txt", skip="1/2/2007", nrows = rowsToRead, na.strings = c("?", ""))
DT$datetime <- as.POSIXct(paste(DT$V1,DT$V2), format="%d/%m/%Y %H:%M:%S")
png(file = "plot4.png", width = 480, height = 480)
par(mfrow = c(2,2))
with(DT,{
plot(DT$datetime,DT$V3, type = "l", col = "black",xlab = "",ylab = "Global Active Power(kilowatts)")})
plot(DT$datetime,DT$V5,type = "l", col = "black",xlab = "datetime",ylab = "Voltage")
plot(DT$datetime,DT$V7, type = "l", col = "black", xlab = "", ylab = "Energy sub metering" )
lines(DT$datetime, DT$V8, col = "red")
lines(DT$datetime, DT$V9, col = "blue")
legend("topright",lty = 1, col = c("black","red","blue"), legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), bty = "n")
plot(DT$datetime,DT$V4 ,type = "l", col = "black",xlab = "datetime",ylab = "Global_reactive_power")
dev.off()
|
/plot4.R
|
no_license
|
Inquisitive-Geek/ExData_Plotting1
|
R
| false
| false
| 1,077
|
r
|
library("data.table")
dtime <- difftime(as.POSIXct("2007-02-03"), as.POSIXct("2007-02-01"),units="mins")
rowsToRead <- as.numeric(dtime)
DT <- fread("household_power_consumption.txt", skip="1/2/2007", nrows = rowsToRead, na.strings = c("?", ""))
DT$datetime <- as.POSIXct(paste(DT$V1,DT$V2), format="%d/%m/%Y %H:%M:%S")
png(file = "plot4.png", width = 480, height = 480)
par(mfrow = c(2,2))
with(DT,{
plot(DT$datetime,DT$V3, type = "l", col = "black",xlab = "",ylab = "Global Active Power(kilowatts)")})
plot(DT$datetime,DT$V5,type = "l", col = "black",xlab = "datetime",ylab = "Voltage")
plot(DT$datetime,DT$V7, type = "l", col = "black", xlab = "", ylab = "Energy sub metering" )
lines(DT$datetime, DT$V8, col = "red")
lines(DT$datetime, DT$V9, col = "blue")
legend("topright",lty = 1, col = c("black","red","blue"), legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), bty = "n")
plot(DT$datetime,DT$V4 ,type = "l", col = "black",xlab = "datetime",ylab = "Global_reactive_power")
dev.off()
|
\name{predict.interflex}
\alias{predict.interflex}
\title{Plotting Marginal Effect Estimates}
\description{Plotting expected outcomes given fixed values of the treatment and moderator after either the linear, binning or the kernel estimator is applied.}
\usage{\method{predict}{interflex}(out, order = NULL, subtitles = NULL, show.subtitles = NULL,
Xdistr = "histogram", CI = NULL, pool = FALSE,main = NULL, Ylabel = NULL,
Xlabel = NULL, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL,
theme.bw = FALSE, show.grid = TRUE, cex.main = NULL, cex.sub = NULL,
cex.lab = NULL, cex.axis = NULL, color = NULL, file = NULL,interval = NULL,
legend.title = NULL, ncols = NULL)
}
\arguments{
\item{out}{an \bold{interflex} object (\bold{predict==TRUE}).}
\item{order}{a vector of strings that determines the order of treatment arms in the plot when visualizing expected values. It should contain all kinds of treatment arms.}
\item{subtitles}{a vector of strings that determines the subtitles of subplots when \bold{pool} is FALSE, or determines the label in the legend when \bold{pool} is TRUE. }
\item{show.subtitles}{a logical flag controlling whether to show subtitles. Default to TRUE when the number of treatment arms is larger than 2.}
\item{Xdistr}{a string indicating the way the distribution of the moderator will be plotted: "histogram" (or "hist"), "density", or "none". The default is "histogram".}
\item{CI}{a logical flag indicating whether the confidence intervals need to be shown.}
\item{pool}{a logical flag specifying whether to integrate expected values of Y for each treatment arm in one plot.}
\item{main}{a string that controls the title of the plot.}
\item{Ylabel}{a string that controls the label of the outcome variable Y in the plot.}
\item{Xlabel}{a string that controls the label of the moderating variable X in the plot.}
\item{xlab}{a string that specifies the label of the x-axis.}
\item{ylab}{a string that specifies the label of the y-axis.}
\item{xlim}{a two-element numeric vector that controls the range of the x-axis to be shown in the plot.}
\item{ylim}{a two-element numeric vector that controls the range of the y-axis to be shown in the plot (with small adjustments to improve aesthetics).}
\item{theme.bw}{a logical flag specifying whether to use a black-white theme.}
\item{show.grid}{a logical flag indicating whether to show grid in the plot.}
\item{cex.main}{a numeric value that controls the font size of the plot title.}
\item{cex.sub}{a numeric value that controls the font size of subtitles.}
\item{cex.lab}{a numeric value that controls the font size of the axis labels.}
\item{cex.axis}{a numeric value that controls the font size of the axis numbers.}
\item{color}{a vector of colors that determines the color of lines when \bold{pool} is TRUE.}
\item{file}{a string that specifies the filename in which the plot is saved.}
\item{interval}{draw two vertical lines to demonstrate the interval used in replicated papers.}
\item{legend.title}{a string that specifies the title of the legend when \bold{pool} is TRUE.}
\item{ncols}{a integral value that controls the number of columns in the plot if \bold{pool} is FALSE.}
}
\details{
\bold{predict.interflex} visualize expected outcomes given fixed values of the treatment and moderator after either the linear, binning or the kernel estimator is applied. It allows users to flexibly change the look of a plot without re-estimating the model, hence saving time.
}
\value{
\item{graph}{stores the graphic output, a \bold{ggplot2} object.}
}
\author{
Jens Hainmueller; Jonathan Mummolo; Yiqing Xu (Maintainer); Ziyi Liu
}
\references{
Jens Hainmueller; Jonathan Mummolo; Yiqing Xu. 2019. "How Much Should We Trust Estimates from Multiplicative Interaction Models? Simple Tools to Improve Empirical Practice." Political Analysis, Vol. 27, Iss. 2, April 2019, pp. 163--192. Available at: \url{http://bit.ly/HMX2019}.
}
\seealso{
\code{\link{interflex}} and \code{\link{plot.interflex}}
}
\examples{
library(interflex)
data(interflex)
out <- inter.binning(data = s1, Y = "Y", D = "D", X = "X", Z = "Z1",predict = TRUE)
predict(out)
}
\keyword{graphics}
|
/man/predict.interflex.Rd
|
no_license
|
Ganzeb/interflex
|
R
| false
| false
| 4,288
|
rd
|
\name{predict.interflex}
\alias{predict.interflex}
\title{Plotting Marginal Effect Estimates}
\description{Plotting expected outcomes given fixed values of the treatment and moderator after either the linear, binning or the kernel estimator is applied.}
\usage{\method{predict}{interflex}(out, order = NULL, subtitles = NULL, show.subtitles = NULL,
Xdistr = "histogram", CI = NULL, pool = FALSE,main = NULL, Ylabel = NULL,
Xlabel = NULL, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL,
theme.bw = FALSE, show.grid = TRUE, cex.main = NULL, cex.sub = NULL,
cex.lab = NULL, cex.axis = NULL, color = NULL, file = NULL,interval = NULL,
legend.title = NULL, ncols = NULL)
}
\arguments{
\item{out}{an \bold{interflex} object (\bold{predict==TRUE}).}
\item{order}{a vector of strings that determines the order of treatment arms in the plot when visualizing expected values. It should contain all kinds of treatment arms.}
\item{subtitles}{a vector of strings that determines the subtitles of subplots when \bold{pool} is FALSE, or determines the label in the legend when \bold{pool} is TRUE. }
\item{show.subtitles}{a logical flag controlling whether to show subtitles. Default to TRUE when the number of treatment arms is larger than 2.}
\item{Xdistr}{a string indicating the way the distribution of the moderator will be plotted: "histogram" (or "hist"), "density", or "none". The default is "histogram".}
\item{CI}{a logical flag indicating whether the confidence intervals need to be shown.}
\item{pool}{a logical flag specifying whether to integrate expected values of Y for each treatment arm in one plot.}
\item{main}{a string that controls the title of the plot.}
\item{Ylabel}{a string that controls the label of the outcome variable Y in the plot.}
\item{Xlabel}{a string that controls the label of the moderating variable X in the plot.}
\item{xlab}{a string that specifies the label of the x-axis.}
\item{ylab}{a string that specifies the label of the y-axis.}
\item{xlim}{a two-element numeric vector that controls the range of the x-axis to be shown in the plot.}
\item{ylim}{a two-element numeric vector that controls the range of the y-axis to be shown in the plot (with small adjustments to improve aesthetics).}
\item{theme.bw}{a logical flag specifying whether to use a black-white theme.}
\item{show.grid}{a logical flag indicating whether to show grid in the plot.}
\item{cex.main}{a numeric value that controls the font size of the plot title.}
\item{cex.sub}{a numeric value that controls the font size of subtitles.}
\item{cex.lab}{a numeric value that controls the font size of the axis labels.}
\item{cex.axis}{a numeric value that controls the font size of the axis numbers.}
\item{color}{a vector of colors that determines the color of lines when \bold{pool} is TRUE.}
\item{file}{a string that specifies the filename in which the plot is saved.}
\item{interval}{draw two vertical lines to demonstrate the interval used in replicated papers.}
\item{legend.title}{a string that specifies the title of the legend when \bold{pool} is TRUE.}
\item{ncols}{a integral value that controls the number of columns in the plot if \bold{pool} is FALSE.}
}
\details{
\bold{predict.interflex} visualize expected outcomes given fixed values of the treatment and moderator after either the linear, binning or the kernel estimator is applied. It allows users to flexibly change the look of a plot without re-estimating the model, hence saving time.
}
\value{
\item{graph}{stores the graphic output, a \bold{ggplot2} object.}
}
\author{
Jens Hainmueller; Jonathan Mummolo; Yiqing Xu (Maintainer); Ziyi Liu
}
\references{
Jens Hainmueller; Jonathan Mummolo; Yiqing Xu. 2019. "How Much Should We Trust Estimates from Multiplicative Interaction Models? Simple Tools to Improve Empirical Practice." Political Analysis, Vol. 27, Iss. 2, April 2019, pp. 163--192. Available at: \url{http://bit.ly/HMX2019}.
}
\seealso{
\code{\link{interflex}} and \code{\link{plot.interflex}}
}
\examples{
library(interflex)
data(interflex)
out <- inter.binning(data = s1, Y = "Y", D = "D", X = "X", Z = "Z1",predict = TRUE)
predict(out)
}
\keyword{graphics}
|
context("Just a test of test")
test_that("test", {
x <- 1L
y <- 2L
expect_identical(x, y-x)
})
|
/tests/testthat/test-test.R
|
no_license
|
cran/tribe
|
R
| false
| false
| 109
|
r
|
context("Just a test of test")
test_that("test", {
x <- 1L
y <- 2L
expect_identical(x, y-x)
})
|
#' Am example
setClass("employee",representation(
name = "character",
salary = "numeric",
union = "logical",
info = "data.frame"
)
)
setMethod("show","employee",
function(object){
inorout<-ifelse(object@union,"is","is not")
cat(object@name,"has a salary of", object@salary,
"and",inorout,"in the union","\n")
})
|
/R/employee-class.R
|
no_license
|
ritianjiang/MethyAge2
|
R
| false
| false
| 400
|
r
|
#' Am example
setClass("employee",representation(
name = "character",
salary = "numeric",
union = "logical",
info = "data.frame"
)
)
setMethod("show","employee",
function(object){
inorout<-ifelse(object@union,"is","is not")
cat(object@name,"has a salary of", object@salary,
"and",inorout,"in the union","\n")
})
|
# vim:textwidth=80:expandtab:shiftwidth=4:softtabstop=4
#' Class to Store AMSR-2 Satellite Data
#'
#' This class stores data from the AMSR-2 satellite.
#'
#' The Advanced Microwave Scanning Radiometer (AMSR-2) is in current operation on
#' the Japan Aerospace Exploration Agency (JAXA) GCOM-W1 space craft, launched in
#' May 2012. Data are processed by Remote Sensing Systems. The satellite
#' completes an ascending and descending pass during local daytime and nighttime
#' hours respectively. Each daily file contains 7 daytime and 7 nighttime
#' maps of variables named as follows within the `data`
#' slot of amsr objects: `timeDay`,
#' `SSTDay`, `LFwindDay` (wind at 10m sensed in
#' the 10.7GHz band), `MFwindDay` (wind at 10m sensed at 18.7GHz),
#' `vaporDay`, `cloudDay`, and `rainDay`, along with
#' similarly-named items that end in `Night`.
#' See reference 1 for additional information on the instrument, how
#' to cite the data source in a paper, etc.
#'
#' The bands are stored in [raw()] form, to save storage. The accessor
#' function \code{\link{[[,amsr-method}} can provide these values in `raw`
#' form or in physical units; [plot,amsr-method()], and
#' [summary,amsr-method()] work with physical units.
#'
#' @templateVar class amsr
#'
#' @templateVar dataExample {}
#'
#' @templateVar metadataExample Examples that are of common interest include `longitude` and `latitude`, which define the grid.
#'
#' @template slot_summary
#'
#' @template slot_put
#'
#' @template slot_get
#'
#' @author Dan Kelley and Chantelle Layton
#'
#' @references
#' 1. Information on the satellite, how to cite the data, etc. is
#' provided at `http://www.remss.com/missions/amsr/`.
#'
#' 2. A simple interface for viewing and downloading data is at
#' `http://images.remss.com/amsr/amsr2_data_daily.html`.
#'
#' @family classes holding satellite data
#' @family things related to amsr data
setClass("amsr", contains="satellite")
setMethod(f="initialize",
signature="amsr",
definition=function(.Object, filename, ...) {
.Object <- callNextMethod(.Object, ...)
if (!missing(filename))
.Object@metadata$filename <- filename
.Object@processingLog$time <- presentTime()
.Object@processingLog$value <- "create 'amsr' object"
return(.Object)
})
setMethod(f="show",
signature="amsr",
definition=function(object) {
cat("Data (physical units):\n")
dataNames <- names(object@data)
for (b in seq_along(dataNames)) {
dim <- if (is.list(object@data[[b]])) dim(object@data[[b]]$lsb) else dim(object@data[[b]])
cat(" \"", dataNames[b], "\" has dimension c(", dim[1], ",", dim[2], ")\n", sep="")
}
})
#' An amsr dataset for waters near Nova Scotia
#'
#' This is a composite satellite image combining views for
#' 2020 August 9, 10 and 11, trimmed from a world view to a view
#' spanning 30N to 60N and 80W to 40W; see \dQuote{Details}.
#'
#' The following code was used to create this dataset.
#'\preformatted{
#' library(oce)
#' data(coastlineWorldFine, package="ocedata")
#' d1 <- read.amsr(download.amsr(2020, 8, 9, "~/data/amsr"))
#' d2 <- read.amsr(download.amsr(2020, 8, 10, "~/data/amsr"))
#' d3 <- read.amsr(download.amsr(2020, 8, 11, "~/data/amsr"))
#' d <- composite(d1, d2, d3)
#' amsr <- subset(d, -80 < longitude & longitude < -40)
#' amsr <- subset(amsr, 30 < latitude & latitude < 60)
#'}
#'
#' @name amsr
#' @docType data
#'
#' @usage data(amsr)
#'
#' @examples
#' library(oce)
#' data(coastlineWorld)
#' data(amsr)
#' plot(amsr, "SST")
#' lines(coastlineWorld[["longitude"]], coastlineWorld[["latitude"]])
#'
#' @family satellite datasets provided with oce
#' @family datasets provided with oce
#' @family things related to amsr data
NULL
#' Summarize an amsr Object
#'
#' Although the data are stored in [raw()] form, the summary
#' presents results in physical units.
#'
#' @param object an [amsr-class] object.
#'
#' @param ... ignored.
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
setMethod(f="summary",
signature="amsr",
definition=function(object, ...) {
cat("Amsr Summary\n------------\n\n")
showMetadataItem(object, "filename", "Data file: ")
cat(sprintf("* Longitude range: %.4fE to %.4fE\n", object@metadata$longitude[1], tail(object@metadata$longitude, 1)))
cat(sprintf("* Latitude range: %.4fN to %.4fN\n", object@metadata$latitude[1], tail(object@metadata$latitude, 1)))
for (name in names(object@data))
object@data[[name]] <- object[[name]] # translate to science units
invisible(callNextMethod()) # summary
})
#' Extract Something From an amsr Object
#'
#' @param x an [amsr-class] object.
#'
#' @section Details of the Specialized Method:
#'
#' If `i` is `"?"`, then the return value is a list
#' containing four items, each of which is a character vector
#' holding the names of things that can be accessed with `[[`.
#' The `data` and `metadata` items hold the names of
#' entries in the object's data and metadata
#' slots, respectively. The `dataDerived`
#' and `metadataDerived` items are each NULL, because
#' no derived values are defined by [cm-class] objects.
#'
#' Data within the `data` slot may be found directly, e.g.
#' `i="SSTDay"` will yield sea-surface temperature in the daytime
#' satellite, and `i="SSTNight"` is used to access the nighttime data. In
#' addition, `i="SST"` yields a computed average of the night and day values
#' (using just one of these, if the other is missing). This scheme of
#' providing computed averages works for
#' all the data stored in `amsr` objects, namely:
#' `time`, `SST`, `LFwind`, `MFwind`,
#' `vapor`, `cloud` and `rain`. In each case, the default
#' is to calculate values in scientific units, unless `j="raw"`, in
#' which case the raw data are returned.
#'
#' The conversion from raw to scientific units is done with formulae
#' found at `http://www.remss.com/missions/amsre`, e.g. SST is
#' computed by converting the raw value to an integer (between 0 and 255),
#' multiplying by 0.15C, and subtracting 3C.
#'
#' The `"raw"` mode can be useful
#' in decoding the various types of missing value that are used by `amsr`
#' data, namely `as.raw(255)` for land, `as.raw(254)` for
#' a missing observation, `as.raw(253)` for a bad observation,
#' `as.raw(252)` for sea ice, or `as.raw(251)` for missing SST
#' due to rain or missing water vapour due to heavy rain. Note that
#' something special has to be done for e.g. `d[["SST","raw"]]`
#' because the idea is that this syntax (as opposed to specifying
#' `"SSTDay"`) is a request to try to find good
#' data by looking at both the Day and Night measurements. The scheme
#' employed is quite detailed. Denote by "A" the raw value of the desired field
#' in the daytime pass, and by "B" the corresponding value in the
#' nighttime pass. If either A or B is 255, the code for land, then the
#' result will be 255. If A is 254 (i.e. there is no observation),
#' then B is returned, and the reverse holds also. Similarly, if either
#' A or B equals 253 (bad observation), then the other is returned.
#' The same is done for code 252 (ice) and code 251 (rain).
#'
#' @return
#' In all cases, the returned value is a matrix with
#' with `NA` values inserted at locations where
#' the raw data equal `as.raw(251:255)`, as explained
#' in \dQuote{Details}.
#'
#' @examples
#' # Histogram of SST values
#' library(oce)
#' data(amsr)
#' hist(amsr[["SST"]])
#'
#' @template sub_subTemplate
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
setMethod(f="[[",
signature(x="amsr", i="ANY", j="ANY"),
definition=function(x, i, j, ...) {
debug <- getOption("oceDebug")
oceDebug(debug, "amsr [[ {\n", unindent=1)
if (missing(i))
stop("Must name a amsr item to retrieve, e.g. '[[\"panchromatic\"]]'", call.=FALSE)
i <- i[1] # drop extras if more than one given
if (!is.character(i))
stop("amsr item must be specified by name", call.=FALSE)
dataDerived <- c("cloud", "LFwind", "MFwind", "rain", "SST",
"time", "vapor")
if (i == "?") {
return(list(metadata=sort(names(x@metadata)),
metadataDerived=NULL,
data=sort(names(x@data)),
dataDerived=sort(dataDerived)))
}
if (is.character(i) && !is.na(pmatch(i, names(x@metadata)))) {
oceDebug(debug, "} # amsr [[\n", unindent=1)
return(x@metadata[[i]])
}
namesAllowed <- c(names(x@data), dataDerived)
if (!(i %in% namesAllowed)) {
stop("band '", i, "' is not available in this object; try one of: ",
paste(namesAllowed, collapse=" "))
}
# get numeric band, changing land, n-obs, bad-obs, sea-ice and windy to NA
getBand<-function(b) {
bad <- b == as.raw(0xff)| # land mass
b == as.raw(0xfe)| # no observations
b == as.raw(0xfd)| # bad observations
b == as.raw(0xfc)| # sea ice
b == as.raw(0xfb) # missing SST or wind due to rain, or missing water vapour due to heavy rain
b <- as.numeric(b)
b[bad] <- NA
b
}
dim <- c(length(x@metadata$longitude), length(x@metadata$latitude))
if (missing(j) || j != "raw") {
# Apply units; see http://www.remss.com/missions/amsre
# FIXME: the table at above link has two factors for time; I've no idea
# what that means, and am extracting what seems to be seconds in the day.
if (i == "timeDay") res <- 60*6*getBand(x@data[[i]]) # FIXME: guessing on amsr time units
else if (i == "timeNight") res <- 60*6*getBand(x@data[[i]]) # FIXME: guessing on amsr time units
else if (i == "time") res <- 60*6*getBand(do_amsr_average(x@data[["timeDay"]], x@data[["timeNight"]]))
else if (i == "SSTDay") res <- -3 + 0.15 * getBand(x@data[[i]])
else if (i == "SSTNight") res <- -3 + 0.15 * getBand(x@data[[i]])
else if (i == "SST") res <- -3 + 0.15 * getBand(do_amsr_average(x@data[["SSTDay"]], x@data[["SSTNight"]]))
else if (i == "LFwindDay") res <- 0.2 * getBand(x@data[[i]])
else if (i == "LFwindNight") res <- 0.2 * getBand(x@data[[i]])
else if (i == "LFwind") res <- 0.2 * getBand(do_amsr_average(x@data[["LFwindDay"]], x@data[["LFwindNight"]]))
else if (i == "MFwindDay") res <- 0.2 * getBand(x@data[[i]])
else if (i == "MFwindNight") res <- 0.2 * getBand(x@data[[i]])
else if (i == "MFwind") res <- 0.2 * getBand(do_amsr_average(x@data[["MFwindDay"]], x@data[["MFwindNight"]]))
else if (i == "vaporDay") res <- 0.3 * getBand(x@data[[i]])
else if (i == "vaporNight") res <- 0.3 * getBand(x@data[[i]])
else if (i == "vapor") res <- 0.3 * getBand(do_amsr_average(x@data[["vaporDay"]], x@data[["vaporNight"]]))
else if (i == "cloudDay") res <- -0.05 + 0.01 * getBand(x@data[[i]])
else if (i == "cloudNight") res <- -0.05 + 0.01 * getBand(x@data[[i]])
else if (i == "cloud") res <- -0.05 + 0.01 * getBand(do_amsr_average(x@data[["cloudDay"]], x@data[["cloudNight"]]))
else if (i == "rainDay") res <- 0.01 * getBand(x@data[[i]])
else if (i == "rainNight") res <- 0.01 * getBand(x@data[[i]])
else if (i == "rain") res <- 0.01 * getBand(do_amsr_average(x@data[["rainDay"]], x@data[["rainNight"]]))
else if (i == "data") return(x@data)
} else {
if (i == "timeDay") res <- x@data[[i]]
else if (i == "timeNight") res <- x@data[[i]]
else if (i == "time") res <- getBand(do_amsr_average(x@data[["timeDay"]], x@data[["timeNight"]]))
else if (i == "SSTDay") res <- x@data[[i]]
else if (i == "SSTNight") res <- x@data[[i]]
else if (i == "SST") res <- do_amsr_average(x@data[["SSTDay"]], x@data[["SSTNight"]])
else if (i == "LFwindDay") res <- x@data[[i]]
else if (i == "LFwindNight") res <- x@data[[i]]
else if (i == "LFwind") res <- do_amsr_average(x@data[["LFwindDay"]], x@data[["LFwindNight"]])
else if (i == "MFwindDay") res <- x@data[[i]]
else if (i == "MFwindNight") res <- x@data[[i]]
else if (i == "MFwind") res <- do_amsr_average(x@data[["MFwindDay"]], x@data[["MFwindNight"]])
else if (i == "vaporDay") res <- x@data[[i]]
else if (i == "vaporNight") res <- x@data[[i]]
else if (i == "vapor") res <- do_amsr_average(x@data[["vaporDay"]], x@data[["vaporNight"]])
else if (i == "cloudDay") res <- x@data[[i]]
else if (i == "cloudNight") res <- x@data[[i]]
else if (i == "cloud") res <- do_amsr_average(x@data[["cloudDay"]], x@data[["cloudNight"]])
else if (i == "rainDay") res <- x@data[[i]]
else if (i == "rainNight") res <- x@data[[i]]
else if (i == "rain") res <- do_amsr_average(x@data[["rainDay"]], x@data[["rainNight"]])
else if (i == "data") return(x@data)
}
dim(res) <- dim
res
})
#' Replace Parts of an amsr Object
#'
#' @param x an [amsr-class] object.
#'
#' @template sub_subsetTemplate
#'
#' @family things related to amsr data
setMethod(f="[[<-",
signature(x="amsr", i="ANY", j="ANY"),
definition=function(x, i, j, ..., value) {
callNextMethod(x=x, i=i, j=j, ...=..., value=value) # [[<-
})
#' Subset an amsr Object
#'
#' Return a subset of a [amsr-class] object.
#'
#' This function is used to subset data within an [amsr-class]
#' object by `longitude` or by `latitude`. These two methods cannot
#' be combined in a single call, so two calls are required, as shown
#' in the Example.
#'
#' @param x an [amsr-class] object.
#'
#' @param subset an expression indicating how to subset `x`.
#'
#' @param ... ignored.
#'
#' @return An [amsr-class] object.
#'
#' @examples
#' library(oce)
#' data(amsr) # see ?amsr for how to read and composite such objects
#' sub <- subset(amsr, -75 < longitude & longitude < -45)
#' sub <- subset(sub, 40 < latitude & latitude < 50)
#' plot(sub)
#' data(coastlineWorld)
#' lines(coastlineWorld[['longitude']], coastlineWorld[['latitude']])
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
#' @family functions that subset oce objects
setMethod(f="subset",
signature="amsr",
definition=function(x, subset, ...) {
dots <- list(...)
debug <- if ("debug" %in% names(dots)) dots$debug else 0
oceDebug(debug, "subset,amsr-method() {\n", style="bold", sep="", unindent=1)
res <- x
subsetString <- paste(deparse(substitute(expr=subset, env=environment())), collapse=" ")
if (length(grep("longitude", subsetString))) {
if (length(grep("latitude", subsetString)))
stop("the subset must not contain both longitude and latitude. Call this twice, to combine these")
keep <- eval(expr=substitute(expr=subset, env=environment()),
envir=data.frame(longitude=x@metadata$longitude), enclos=parent.frame(2))
oceDebug(debug, "keeping", sum(keep), "of", length(keep), "longitudes\n")
for (name in names(res@data)) {
oceDebug(debug, "processing", name, "\n")
res@data[[name]] <- res[[name, "raw"]][keep, ]
}
res@metadata$longitude <- x@metadata$longitude[keep]
} else if (length(grep("latitude", subsetString))) {
if (length(grep("longitude", subsetString)))
stop("the subset must not contain both longitude and latitude. Call this twice, to combine these")
keep <- eval(expr=substitute(expr=subset, env=environment()),
envir=data.frame(latitude=x@metadata$latitude), enclos=parent.frame(2))
oceDebug(debug, "keeping", sum(keep), "of", length(keep), "latitudes\n")
for (name in names(res@data)) {
oceDebug(debug, "processing", name, "\n")
res@data[[name]] <- x[[name, "raw"]][, keep]
}
res@metadata$latitude <- res@metadata$latitude[keep]
} else {
stop("may only subset by longitude or latitude")
}
res@processingLog <- processingLogAppend(res@processingLog, paste("subset(x, subset=", subsetString, ")", sep=""))
oceDebug(debug, "} # subset,amsr-method()\n", style="bold", sep="", unindent=1)
res
})
#' Plot an amsr Object
#'
#' Plot an image of a component of an [amsr-class] object.
#'
#' In addition to fields named directly in the object, such as `SSTDay` and
#' `SSTNight`, it is also possible to plot computed fields, such as `SST`,
#' which combines the day and night fields.
#'
#' @param x an [amsr-class] object.
#'
#' @param y character value indicating the name of the band to plot; if not provided,
#' `SST` is used; see the documentation for the [amsr-class] class for a list of bands.
#'
#' @param asp optional numerical value giving the aspect ratio for plot. The
#' default value, `NULL`, means to use an aspect ratio of 1 for world views,
#' and a value computed from `ylim`, if the latter is specified in the
#' `...` argument.
#'
#' @param breaks optional numeric vector of the z values for breaks in the color scheme.
#' If `colormap` is provided, it takes precedence over `breaks` and `col`.
#'
#' @param col optional argument, either a vector of colors corresponding to the breaks, of length
#' 1 less than the number of breaks, or a function specifying colors.
#' If neither `col` or `colormap` is provided, then `col` defaults to
#' [oceColorsTemperature()].
#' If `colormap` is provided, it takes precedence over `breaks` and `col`.
#'
#' @param colormap a specification of the colormap to use, as created
#' with [colormap()]. If `colormap` is NULL, which is the default, then
#' a colormap is created to cover the range of data values, using
#' [oceColorsTemperature] colour scheme.
#' If `colormap` is provided, it takes precedence over `breaks` and `col`.
#' See \dQuote{Examples} for an example of using the "turbo" colour scheme.
#'
#' @param zlim optional numeric vector of length 2, giving the limits
#' of the plotted quantity. A reasonable default is computed, if this
#' is not given.
#'
#' @param missingColor List of colors for problem cases. The names of the
#' elements in this list must be as in the default, but the colors may
#' be changed to any desired values. These default values work reasonably
#' well for SST images, which are the default image, and which employ a
#' blue-white-red blend of colors, no mixture of which matches the
#' default values in `missingColor`.
#'
#' @param debug A debugging flag, integer.
#'
#' @param ... extra arguments passed to [imagep()], e.g. to control
#' the view with `xlim` (for longitude) and `ylim` (for latitude).
#'
#' @examples
#' library(oce)
#' data(coastlineWorld)
#' data(amsr) # see ?amsr for how to read and composite such objects
#'
#' # Example 1: plot with default colour scheme, oceColorsTemperature()
#' plot(amsr, "SST")
#' lines(coastlineWorld[['longitude']], coastlineWorld[['latitude']])
#'
#' # Example 2: 'turbo' colour scheme
#' plot(amsr, "SST", col=oceColorsTurbo)
#' lines(coastlineWorld[['longitude']], coastlineWorld[['latitude']])
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
#' @family functions that plot oce data
#'
#' @aliases plot.amsr
setMethod(f="plot",
signature=signature("amsr"),
# FIXME: how to let it default on band??
definition=function(x, y, asp=NULL,
breaks, col, colormap, zlim,
missingColor=list(land="papayaWhip",
none="lightGray",
bad="gray",
rain="plum",
ice="mediumVioletRed"),
debug=getOption("oceDebug"), ...)
{
dots <- list(...)
oceDebug(debug, "plot.amsr(..., y=c(",
if (missing(y)) "(missing)" else y, ", ...) {\n", sep="", style="bold", unindent=1)
zlimGiven <- !missing(zlim)
if (missing(y))
y <- "SST"
lon <- x[["longitude"]]
lat <- x[["latitude"]]
# Examine ylim (if asp is not NULL) and also at both xlim and ylim to
# compute zrange.
xlim <- dots$xlim
ylim <- dots$ylim
if (is.null(asp)) {
if (!is.null(ylim)) {
asp <- 1 / cos(pi/180*abs(mean(ylim, na.rm=TRUE)))
oceDebug(debug, "inferred asp=", asp, " from ylim argument\n", sep="")
} else {
asp <- 1 / cos(pi/180*abs(mean(lat, na.rm=TRUE)))
oceDebug(debug, "inferred asp=", asp, " from ylim argument\n", sep="")
}
} else {
oceDebug(debug, "using supplied asp=", asp, "\n", sep="")
}
z <- x[[y]]
# Compute zrange for world data, or data narrowed to xlim and ylim.
if (!is.null(xlim)) {
if (!is.null(ylim)) {
oceDebug(debug, "computing range based on z trimmed by xlim and ylim\n")
zrange <- range(z[xlim[1] <= lon & lon <= xlim[2], ylim[1] <= lat & lat <= ylim[2]], na.rm=TRUE)
} else {
oceDebug(debug, "computing range based on z trimmed by xlim alone\n")
zrange <- range(z[xlim[1] <= lon & lon <= xlim[2], ], na.rm=TRUE)
}
} else {
if (!is.null(ylim)) {
oceDebug(debug, "computing range based on z trimmed by ylim alone\n")
zrange <- range(z[, ylim[1] <= lat & lat <= ylim[2]], na.rm=TRUE)
} else {
oceDebug(debug, "computing range based on whole-world data\n")
zrange <- range(z, na.rm=TRUE)
}
}
oceDebug(debug, "zrange: ", paste(zrange, collapse=" to "), "\n")
# Determine colormap, if not given as an argument.
if (missing(colormap)) {
oceDebug(debug, "case 1: 'colormap' not given, so will be computed here\n")
if (!missing(breaks)) {
oceDebug(debug, "case 1.1: 'breaks' was specified\n")
if (debug > 0) {
cat("FYI breaks are as follows:\n")
print(breaks)
}
if (!missing(col)) {
oceDebug(debug, "case 1.1.1: computing colormap from specified breaks and specified col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else range(breaks), col=col)
} else {
oceDebug(debug, "case 1.1.2: computing colormap from specified breaks and computed col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else range(breaks), col=oceColorsTemperature)
}
} else {
oceDebug(debug, "case 1.2: 'breaks' was not specified\n")
if (!missing(col)) {
oceDebug(debug, "case 1.2.1: computing colormap from and computed breaks and specified col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else zrange, col=col)
} else {
oceDebug(debug, "case 1.2.2: computing colormap from computed breaks and computed col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else zrange, col=oceColorsTemperature)
}
}
} else {
oceDebug(debug, "using specified colormap, ignoring breaks and col, whether they were supplied or not\n")
}
i <- if ("zlab" %in% names(dots)) {
oceDebug(debug, "calling imagep() with asp=", asp, ", and zlab=\"", dots$zlab, "\"\n", sep="")
imagep(lon, lat, z, colormap=colormap, asp=asp, debug=debug-1, ...)
} else {
oceDebug(debug, "calling imagep() with asp=", asp, ", and no zlab argument\n", sep="")
imagep(lon, lat, z, colormap=colormap, zlab=y, asp=asp, debug=debug-1, ...)
}
# Handle missing-data codes by redrawing the (decimate) image. Perhaps
# imagep() should be able to do this, but imagep() is a long function
# with a lot of interlocking arguments so I'll start by doing this
# manually here, and, if I like it, I'll extend imagep() later. Note
# that I added a new element of the return value of imagep(), to get the
# decimation factor.
missingColorLength <- length(missingColor)
if (5 != missingColorLength)
stop("must have 5 elements in the missingColor argument")
if (!all(sort(names(missingColor))==sort(c("land", "none", "bad", "ice", "rain"))))
stop("missingColor names must be: 'land', 'none', 'bad', 'ice' and 'rain'")
lonDecIndices <- seq(1L, length(lon), by=i$decimate[1])
latDecIndices <- seq(1L, length(lat), by=i$decimate[2])
lon <- lon[lonDecIndices]
lat <- lat[latDecIndices]
codes <- list(land=as.raw(255), # land
none=as.raw(254), # missing data
bad=as.raw(253), # bad observation
ice=as.raw(252), # sea ice
rain=as.raw(251)) # heavy rain
for (codeName in names(codes)) {
bad <- x[[y, "raw"]][lonDecIndices, latDecIndices] == as.raw(codes[[codeName]])
image(lon, lat, bad,
col=c("transparent", missingColor[[codeName]]), add=TRUE)
}
box()
oceDebug(debug, "} # plot.amsr()\n", sep="", style="bold", unindent=1)
})
#' Download and Cache an amsr File
#'
#' If the file is already present in `destdir`, then it is not
#' downloaded again. The default `destdir` is the present directory,
#' but it probably makes more sense to use something like `"~/data/amsr"`
#' to make it easy for scripts in other directories to use the cached data.
#' The file is downloaded with [download.file()].
#'
#' @param year,month,day Numerical values of the year, month, and day
#' of the desired dataset. Note that one file is archived per day,
#' so these three values uniquely identify a dataset.
#' If `day` and `month` are not provided but `day` is,
#' then the time is provided in a relative sense, based on the present
#' date, with `day` indicating the number of days in the past.
#' Owing to issues with timezones and the time when the data
#' are uploaded to the server, `day=3` may yield the
#' most recent available data. For this reason, there is a
#' third option, which is to leave `day` unspecified, which
#' works as though `day=3` had been given.
#'
#' @param destdir A string naming the directory in which to cache the downloaded file.
#' The default is to store in the present directory, but many users find it more
#' helpful to use something like `"~/data/amsr"` for this, to collect all
#' downloaded amsr files in one place.
#' @param server A string naming the server from which data
#' are to be acquired. See \dQuote{History}.
#'
#' @section History:
#' Until 25 March 2017, the default server was
#' `"ftp.ssmi.com/amsr2/bmaps_v07.2"`, but this was changed when the author
#' discovered that this FTP site had been changed to require users to create
#' accounts to register for downloads. The default was changed to
#' `"http://data.remss.com/amsr2/bmaps_v07.2"` on the named date.
#' This site was found by a web search, but it seems to provide proper data.
#' It is assumed that users will do some checking on the best source.
#'
#' On 23 January 2018, it was noticed that the server-url naming convention
#' had changed, e.g.
#' `http://data.remss.com/amsr2/bmaps_v07.2/y2017/m01/f34_20170114v7.2.gz`
#' becoming
#' `http://data.remss.com/amsr2/bmaps_v08/y2017/m01/f34_20170114v8.gz`
#'
#' @return A character value indicating the filename of the result; if
#' there is a problem of any kind, the result will be the empty
#' string.
#'
#' @examples
#'\dontrun{
#' # The download takes several seconds.
#' f <- download.amsr(2017, 1, 14) # Jan 14, 2017
#' d <- read.amsr(f)
#' plot(d)
#' mtext(d[["filename"]], side=3, line=0, adj=0)
#'}
#'
#' @family functions that download files
#' @family functions that plot oce data
#' @family things related to amsr data
#'
#' @references
#' `http://images.remss.com/amsr/amsr2_data_daily.html`
#' provides daily images going back to 2012. Three-day,
#' monthly, and monthly composites are also provided on that site.
download.amsr <- function(year, month, day, destdir=".", server="http://data.remss.com/amsr2/bmaps_v08")
{
# ftp ftp://ftp.ssmi.com/amsr2/bmaps_v07.2/y2016/m08/f34_20160804v7.2.gz
if (missing(year) && missing(month)) {
if (missing(day))
day <- 3
day <- abs(day)
today <- as.POSIXlt(Sys.Date() - day)
year <- 1900 + today$year
month <- 1 + today$mon
day <- today$mday
}
year <- as.integer(year)
month <- as.integer(month)
day <- as.integer(day)
destfile <- sprintf("f34_%4d%02d%02dv8.gz", year, month, day)
destpath <- paste(destdir, destfile, sep="/")
# example
# http://data.remss.com/amsr2/bmaps_v07.2/y2015/m11/f34_20151101v7.2.gz
if (tail(destpath, 1)=="/") { # remove trailing slash
destpath <- substr(destpath, 1, length(destpath)-1)
}
if (0 == length(list.files(path=destdir, pattern=paste("^", destfile, "$", sep="")))) {
source <- sprintf("%s/y%4d/m%02d/%s", server, year, month, destfile)
bad <- download.file(source, destfile)
if (!bad && destdir != ".")
system(paste("mv", destfile, destpath))
} else {
message("Not downloading ", destfile, " because it is already present in ", destdir)
}
if (destdir == ".") destfile else destpath
}
#' Read an amsr File
#'
#' Read a compressed amsr file, generating an [amsr-class] object.
#' Note that only compressed files are read in this version.
#'
#' AMSR files are provided at the FTP site, at
#' \code{ftp.ssmi.com/amsr2/bmaps_v07.2} as of April 2021.
#' To acquire such files,
#' log in as "guest",
#' then enter a year-based directory (e.g. `y2016` for the year 2016),
#' then enter a month-based directory (e.g. `m08` for August, the 8th
#' month), and then download a file for the present date, e.g.
#' `f34_20160803v7.2.gz` for August 3rd, 2016. Do not uncompress
#' this file, since `read.amsr` can only read the raw files from the server.
#' If `read.amsr` reports an error on the number of chunks, try
#' downloading a similarly-named file (e.g. in the present example,
#' `read.amsr("f34_20160803v7.2_d3d.gz")` will report an error
#' about inability to read a 6-chunk file, but
#' `read.amsr("f34_20160803v7.2.gz")` will work properly.
#'
#' @param file String indicating the name of a compressed file. See
#' \dQuote{File sources}.
#'
#' @template encodingIgnoredTemplate
#'
#' @param debug A debugging flag, integer.
#'
#' @seealso [plot,amsr-method()] for an example.
#'
#' @author Dan Kelley and Chantelle Layton
#'
#' @family things related to amsr data
read.amsr <- function(file, encoding=NA, debug=getOption("oceDebug"))
{
if (missing(file))
stop("must supply 'file'")
if (is.character(file)) {
if (!file.exists(file))
stop("cannot find file '", file, "'")
if (0L == file.info(file)$size)
stop("empty file '", file, "'")
}
oceDebug(debug, "read.amsr(file=\"", file, "\",",
#if (length(band) > 1) paste("band=c(\"", paste(band, collapse="\",\""), "\")", sep="") else
", debug=", debug, ") {\n", sep="", unindent=1)
res <- new("amsr")
filename <- file
res@metadata$filename <- filename
file <- if (length(grep(".*.gz$", filename))) gzfile(filename, "rb") else file(filename, "rb")
on.exit(close(file))
# we can hard-code a max size because the satellite data size is not variable
buf <- readBin(file, what="raw", n=50e6, endian="little")
nbuf <- length(buf)
dim <- c(1440, 720)
nchunks <- nbuf / prod(dim)
if (nchunks != round(nchunks))
stop("error: the data length ", nbuf, " is not an integral multiple of ", dim[1], "*", dim[2])
# From an amsr webpage --
# Each binary data file available from our ftp site consists of fourteen (daily) or
# six (averaged) 0.25 x 0.25 degree grid (1440,720) byte maps. For daily files,
# seven daytime, ascending maps in the following order, Time (UTC), Sea Surface
# Temperature (SST), 10 meter Surface Wind Speed (WSPD-LF), 10 meter Surface
# Wind Speed (WSPD-MF), Atmospheric Water Vapor (VAPOR), Cloud Liquid Water (CLOUD),
# and Rain Rate (RAIN), are followed by seven nighttime maps in the same order.
# Time-Averaged files contain just the geophysical layers in the same order
# [SST, WSPD-LF, WSPD-MF,VAPOR, CLOUD, RAIN].
select <- seq.int(1L, prod(dim))
if (nchunks == 14) {
oceDebug(debug, "14-chunk amsr file\n")
timeDay <- buf[select]
SSTDay <- buf[prod(dim) + select]
LFwindDay <- buf[2*prod(dim) + select]
MFwindDay <- buf[3*prod(dim) + select]
vaporDay <- buf[4*prod(dim) + select]
cloudDay <- buf[5*prod(dim) + select]
rainDay <- buf[6*prod(dim) + select]
dim(timeDay) <- dim
dim(SSTDay) <- dim
dim(LFwindDay) <- dim
dim(MFwindDay) <- dim
dim(vaporDay) <- dim
dim(cloudDay) <- dim
dim(rainDay) <- dim
timeNight <- buf[7*prod(dim) + select]
SSTNight <- buf[8*prod(dim) + select]
LFwindNight <- buf[9*prod(dim) + select]
MFwindNight <- buf[10*prod(dim) + select]
vaporNight <- buf[11*prod(dim) + select]
cloudNight <- buf[12*prod(dim) + select]
rainNight <- buf[13*prod(dim) + select]
dim(timeNight) <- dim
dim(SSTNight) <- dim
dim(LFwindNight) <- dim
dim(MFwindNight) <- dim
dim(vaporNight) <- dim
dim(cloudNight) <- dim
dim(rainNight) <- dim
res@metadata$units$SSTDay <- list(unit=expression(degree*C), scale="ITS-90")
res@metadata$units$SSTNight <- list(unit=expression(degree*C), scale="ITS-90")
res@metadata$units$LFwindDay <- list(unit=expression(m/s), scale="")
res@metadata$units$LFwindNight <- list(unit=expression(m/s), scale="")
res@metadata$units$MFwindDay <- list(unit=expression(m/s), scale="")
res@metadata$units$MFwindNight <- list(unit=expression(m/s), scale="")
res@metadata$units$rainDay <- list(unit=expression(mm/h), scale="")
res@metadata$units$rainNight <- list(unit=expression(mm/h), scale="")
res@data <- list(timeDay=timeDay,
SSTDay=SSTDay, LFwindDay=LFwindDay, MFwindDay=MFwindDay,
vaporDay=vaporDay, cloudDay=cloudDay, rainDay=rainDay,
timeNight=timeNight,
SSTNight=SSTNight, LFwindNight=LFwindNight, MFwindNight=MFwindNight,
vaporNight=vaporNight, cloudNight=cloudNight, rainNight=rainNight)
res@metadata$longitude <- 0.25 * 1:dim[1] - 0.125
res@metadata$latitude <- 0.25 * 1:dim[2] - 90.125
# rearrange matrices so that Greenwich is near the centre
for (name in names(res@data)) {
t <- matrixShiftLongitude(res@data[[name]], res@metadata$longitude)
res@data[[name]] <- t$m
}
res@metadata$longitude <- t$longitude
} else if (nchunks == 6) {
stop("Cannot (yet) read 6-chunk data. Please contact the developers if you need this file (and be sure to send the file to them).")
} else {
stop("Can only handle 14-chunk data; this file has ",
nchunks, " chunks. Please contact the developers if you need to read this file.")
}
res@metadata$spacecraft <- "amsr"
res@processingLog <- processingLogAppend(res@processingLog,
paste(deparse(match.call()), sep="", collapse=""))
oceDebug(debug, "} # read.amsr()\n", unindent=1)
res
}
#' Create a composite of amsr satellite data
#'
#' Form averages for each item in the `data` slot of the supplied objects,
#' taking into account the bad-data codes.
#'
#' If none of the objects has good
#' data at any particular pixel (i.e. particular latitude and longitude),
#' the resultant will have the bad-data code of the last item in the argument
#' list.
#' The metadata in the result are taken directly from the metadata of the
#' final argument, except that the filename is set to a comma-separated list
#' of the component filenames.
#'
#' @param object An [amsr-class] object.
#'
#' @param ... Other amsr objects.
#'
#' @family things related to amsr data
#'
#' @template compositeTemplate
setMethod("composite",
c(object="amsr"),
function(object, ...) {
dots <- list(...)
ndots <- length(dots)
if (ndots < 1)
stop("need more than one argument")
for (idot in 1:ndots) {
if (!inherits(dots[[idot]], "amsr"))
stop("argument ", 1+idot, " does not inherit from 'amsr'")
}
# inherit most of the metadata from the last argument
res <- dots[[ndots]]
filenames <- object[["filename"]]
for (idot in 1:ndots)
filenames <- paste(filenames, ",", dots[[idot]][["filename"]], sep="")
n <- 1 + ndots
dim <- c(dim(object@data[[1]]), n)
for (name in names(object@data)) {
a <- array(as.raw(0xff), dim=dim)
a[, , 1] <- object@data[[name]]
for (idot in 1:ndots)
a[, , 1+idot] <- dots[[idot]]@data[[name]]
A <- do_amsr_composite(a, dim(a))
res@data[[name]] <- A
}
res@metadata$filename <- filenames
res
})
|
/R/amsr.R
|
no_license
|
cran/oce
|
R
| false
| false
| 37,924
|
r
|
# vim:textwidth=80:expandtab:shiftwidth=4:softtabstop=4
#' Class to Store AMSR-2 Satellite Data
#'
#' This class stores data from the AMSR-2 satellite.
#'
#' The Advanced Microwave Scanning Radiometer (AMSR-2) is in current operation on
#' the Japan Aerospace Exploration Agency (JAXA) GCOM-W1 space craft, launched in
#' May 2012. Data are processed by Remote Sensing Systems. The satellite
#' completes an ascending and descending pass during local daytime and nighttime
#' hours respectively. Each daily file contains 7 daytime and 7 nighttime
#' maps of variables named as follows within the `data`
#' slot of amsr objects: `timeDay`,
#' `SSTDay`, `LFwindDay` (wind at 10m sensed in
#' the 10.7GHz band), `MFwindDay` (wind at 10m sensed at 18.7GHz),
#' `vaporDay`, `cloudDay`, and `rainDay`, along with
#' similarly-named items that end in `Night`.
#' See reference 1 for additional information on the instrument, how
#' to cite the data source in a paper, etc.
#'
#' The bands are stored in [raw()] form, to save storage. The accessor
#' function \code{\link{[[,amsr-method}} can provide these values in `raw`
#' form or in physical units; [plot,amsr-method()], and
#' [summary,amsr-method()] work with physical units.
#'
#' @templateVar class amsr
#'
#' @templateVar dataExample {}
#'
#' @templateVar metadataExample Examples that are of common interest include `longitude` and `latitude`, which define the grid.
#'
#' @template slot_summary
#'
#' @template slot_put
#'
#' @template slot_get
#'
#' @author Dan Kelley and Chantelle Layton
#'
#' @references
#' 1. Information on the satellite, how to cite the data, etc. is
#' provided at `http://www.remss.com/missions/amsr/`.
#'
#' 2. A simple interface for viewing and downloading data is at
#' `http://images.remss.com/amsr/amsr2_data_daily.html`.
#'
#' @family classes holding satellite data
#' @family things related to amsr data
setClass("amsr", contains="satellite")
setMethod(f="initialize",
signature="amsr",
definition=function(.Object, filename, ...) {
.Object <- callNextMethod(.Object, ...)
if (!missing(filename))
.Object@metadata$filename <- filename
.Object@processingLog$time <- presentTime()
.Object@processingLog$value <- "create 'amsr' object"
return(.Object)
})
setMethod(f="show",
signature="amsr",
definition=function(object) {
cat("Data (physical units):\n")
dataNames <- names(object@data)
for (b in seq_along(dataNames)) {
dim <- if (is.list(object@data[[b]])) dim(object@data[[b]]$lsb) else dim(object@data[[b]])
cat(" \"", dataNames[b], "\" has dimension c(", dim[1], ",", dim[2], ")\n", sep="")
}
})
#' An amsr dataset for waters near Nova Scotia
#'
#' This is a composite satellite image combining views for
#' 2020 August 9, 10 and 11, trimmed from a world view to a view
#' spanning 30N to 60N and 80W to 40W; see \dQuote{Details}.
#'
#' The following code was used to create this dataset.
#'\preformatted{
#' library(oce)
#' data(coastlineWorldFine, package="ocedata")
#' d1 <- read.amsr(download.amsr(2020, 8, 9, "~/data/amsr"))
#' d2 <- read.amsr(download.amsr(2020, 8, 10, "~/data/amsr"))
#' d3 <- read.amsr(download.amsr(2020, 8, 11, "~/data/amsr"))
#' d <- composite(d1, d2, d3)
#' amsr <- subset(d, -80 < longitude & longitude < -40)
#' amsr <- subset(amsr, 30 < latitude & latitude < 60)
#'}
#'
#' @name amsr
#' @docType data
#'
#' @usage data(amsr)
#'
#' @examples
#' library(oce)
#' data(coastlineWorld)
#' data(amsr)
#' plot(amsr, "SST")
#' lines(coastlineWorld[["longitude"]], coastlineWorld[["latitude"]])
#'
#' @family satellite datasets provided with oce
#' @family datasets provided with oce
#' @family things related to amsr data
NULL
#' Summarize an amsr Object
#'
#' Although the data are stored in [raw()] form, the summary
#' presents results in physical units.
#'
#' @param object an [amsr-class] object.
#'
#' @param ... ignored.
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
setMethod(f="summary",
signature="amsr",
definition=function(object, ...) {
cat("Amsr Summary\n------------\n\n")
showMetadataItem(object, "filename", "Data file: ")
cat(sprintf("* Longitude range: %.4fE to %.4fE\n", object@metadata$longitude[1], tail(object@metadata$longitude, 1)))
cat(sprintf("* Latitude range: %.4fN to %.4fN\n", object@metadata$latitude[1], tail(object@metadata$latitude, 1)))
for (name in names(object@data))
object@data[[name]] <- object[[name]] # translate to science units
invisible(callNextMethod()) # summary
})
#' Extract Something From an amsr Object
#'
#' @param x an [amsr-class] object.
#'
#' @section Details of the Specialized Method:
#'
#' If `i` is `"?"`, then the return value is a list
#' containing four items, each of which is a character vector
#' holding the names of things that can be accessed with `[[`.
#' The `data` and `metadata` items hold the names of
#' entries in the object's data and metadata
#' slots, respectively. The `dataDerived`
#' and `metadataDerived` items are each NULL, because
#' no derived values are defined by [cm-class] objects.
#'
#' Data within the `data` slot may be found directly, e.g.
#' `i="SSTDay"` will yield sea-surface temperature in the daytime
#' satellite, and `i="SSTNight"` is used to access the nighttime data. In
#' addition, `i="SST"` yields a computed average of the night and day values
#' (using just one of these, if the other is missing). This scheme of
#' providing computed averages works for
#' all the data stored in `amsr` objects, namely:
#' `time`, `SST`, `LFwind`, `MFwind`,
#' `vapor`, `cloud` and `rain`. In each case, the default
#' is to calculate values in scientific units, unless `j="raw"`, in
#' which case the raw data are returned.
#'
#' The conversion from raw to scientific units is done with formulae
#' found at `http://www.remss.com/missions/amsre`, e.g. SST is
#' computed by converting the raw value to an integer (between 0 and 255),
#' multiplying by 0.15C, and subtracting 3C.
#'
#' The `"raw"` mode can be useful
#' in decoding the various types of missing value that are used by `amsr`
#' data, namely `as.raw(255)` for land, `as.raw(254)` for
#' a missing observation, `as.raw(253)` for a bad observation,
#' `as.raw(252)` for sea ice, or `as.raw(251)` for missing SST
#' due to rain or missing water vapour due to heavy rain. Note that
#' something special has to be done for e.g. `d[["SST","raw"]]`
#' because the idea is that this syntax (as opposed to specifying
#' `"SSTDay"`) is a request to try to find good
#' data by looking at both the Day and Night measurements. The scheme
#' employed is quite detailed. Denote by "A" the raw value of the desired field
#' in the daytime pass, and by "B" the corresponding value in the
#' nighttime pass. If either A or B is 255, the code for land, then the
#' result will be 255. If A is 254 (i.e. there is no observation),
#' then B is returned, and the reverse holds also. Similarly, if either
#' A or B equals 253 (bad observation), then the other is returned.
#' The same is done for code 252 (ice) and code 251 (rain).
#'
#' @return
#' In all cases, the returned value is a matrix with
#' with `NA` values inserted at locations where
#' the raw data equal `as.raw(251:255)`, as explained
#' in \dQuote{Details}.
#'
#' @examples
#' # Histogram of SST values
#' library(oce)
#' data(amsr)
#' hist(amsr[["SST"]])
#'
#' @template sub_subTemplate
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
setMethod(f="[[",
signature(x="amsr", i="ANY", j="ANY"),
definition=function(x, i, j, ...) {
debug <- getOption("oceDebug")
oceDebug(debug, "amsr [[ {\n", unindent=1)
if (missing(i))
stop("Must name a amsr item to retrieve, e.g. '[[\"panchromatic\"]]'", call.=FALSE)
i <- i[1] # drop extras if more than one given
if (!is.character(i))
stop("amsr item must be specified by name", call.=FALSE)
dataDerived <- c("cloud", "LFwind", "MFwind", "rain", "SST",
"time", "vapor")
if (i == "?") {
return(list(metadata=sort(names(x@metadata)),
metadataDerived=NULL,
data=sort(names(x@data)),
dataDerived=sort(dataDerived)))
}
if (is.character(i) && !is.na(pmatch(i, names(x@metadata)))) {
oceDebug(debug, "} # amsr [[\n", unindent=1)
return(x@metadata[[i]])
}
namesAllowed <- c(names(x@data), dataDerived)
if (!(i %in% namesAllowed)) {
stop("band '", i, "' is not available in this object; try one of: ",
paste(namesAllowed, collapse=" "))
}
# get numeric band, changing land, n-obs, bad-obs, sea-ice and windy to NA
getBand<-function(b) {
bad <- b == as.raw(0xff)| # land mass
b == as.raw(0xfe)| # no observations
b == as.raw(0xfd)| # bad observations
b == as.raw(0xfc)| # sea ice
b == as.raw(0xfb) # missing SST or wind due to rain, or missing water vapour due to heavy rain
b <- as.numeric(b)
b[bad] <- NA
b
}
dim <- c(length(x@metadata$longitude), length(x@metadata$latitude))
if (missing(j) || j != "raw") {
# Apply units; see http://www.remss.com/missions/amsre
# FIXME: the table at above link has two factors for time; I've no idea
# what that means, and am extracting what seems to be seconds in the day.
if (i == "timeDay") res <- 60*6*getBand(x@data[[i]]) # FIXME: guessing on amsr time units
else if (i == "timeNight") res <- 60*6*getBand(x@data[[i]]) # FIXME: guessing on amsr time units
else if (i == "time") res <- 60*6*getBand(do_amsr_average(x@data[["timeDay"]], x@data[["timeNight"]]))
else if (i == "SSTDay") res <- -3 + 0.15 * getBand(x@data[[i]])
else if (i == "SSTNight") res <- -3 + 0.15 * getBand(x@data[[i]])
else if (i == "SST") res <- -3 + 0.15 * getBand(do_amsr_average(x@data[["SSTDay"]], x@data[["SSTNight"]]))
else if (i == "LFwindDay") res <- 0.2 * getBand(x@data[[i]])
else if (i == "LFwindNight") res <- 0.2 * getBand(x@data[[i]])
else if (i == "LFwind") res <- 0.2 * getBand(do_amsr_average(x@data[["LFwindDay"]], x@data[["LFwindNight"]]))
else if (i == "MFwindDay") res <- 0.2 * getBand(x@data[[i]])
else if (i == "MFwindNight") res <- 0.2 * getBand(x@data[[i]])
else if (i == "MFwind") res <- 0.2 * getBand(do_amsr_average(x@data[["MFwindDay"]], x@data[["MFwindNight"]]))
else if (i == "vaporDay") res <- 0.3 * getBand(x@data[[i]])
else if (i == "vaporNight") res <- 0.3 * getBand(x@data[[i]])
else if (i == "vapor") res <- 0.3 * getBand(do_amsr_average(x@data[["vaporDay"]], x@data[["vaporNight"]]))
else if (i == "cloudDay") res <- -0.05 + 0.01 * getBand(x@data[[i]])
else if (i == "cloudNight") res <- -0.05 + 0.01 * getBand(x@data[[i]])
else if (i == "cloud") res <- -0.05 + 0.01 * getBand(do_amsr_average(x@data[["cloudDay"]], x@data[["cloudNight"]]))
else if (i == "rainDay") res <- 0.01 * getBand(x@data[[i]])
else if (i == "rainNight") res <- 0.01 * getBand(x@data[[i]])
else if (i == "rain") res <- 0.01 * getBand(do_amsr_average(x@data[["rainDay"]], x@data[["rainNight"]]))
else if (i == "data") return(x@data)
} else {
if (i == "timeDay") res <- x@data[[i]]
else if (i == "timeNight") res <- x@data[[i]]
else if (i == "time") res <- getBand(do_amsr_average(x@data[["timeDay"]], x@data[["timeNight"]]))
else if (i == "SSTDay") res <- x@data[[i]]
else if (i == "SSTNight") res <- x@data[[i]]
else if (i == "SST") res <- do_amsr_average(x@data[["SSTDay"]], x@data[["SSTNight"]])
else if (i == "LFwindDay") res <- x@data[[i]]
else if (i == "LFwindNight") res <- x@data[[i]]
else if (i == "LFwind") res <- do_amsr_average(x@data[["LFwindDay"]], x@data[["LFwindNight"]])
else if (i == "MFwindDay") res <- x@data[[i]]
else if (i == "MFwindNight") res <- x@data[[i]]
else if (i == "MFwind") res <- do_amsr_average(x@data[["MFwindDay"]], x@data[["MFwindNight"]])
else if (i == "vaporDay") res <- x@data[[i]]
else if (i == "vaporNight") res <- x@data[[i]]
else if (i == "vapor") res <- do_amsr_average(x@data[["vaporDay"]], x@data[["vaporNight"]])
else if (i == "cloudDay") res <- x@data[[i]]
else if (i == "cloudNight") res <- x@data[[i]]
else if (i == "cloud") res <- do_amsr_average(x@data[["cloudDay"]], x@data[["cloudNight"]])
else if (i == "rainDay") res <- x@data[[i]]
else if (i == "rainNight") res <- x@data[[i]]
else if (i == "rain") res <- do_amsr_average(x@data[["rainDay"]], x@data[["rainNight"]])
else if (i == "data") return(x@data)
}
dim(res) <- dim
res
})
#' Replace Parts of an amsr Object
#'
#' @param x an [amsr-class] object.
#'
#' @template sub_subsetTemplate
#'
#' @family things related to amsr data
setMethod(f="[[<-",
signature(x="amsr", i="ANY", j="ANY"),
definition=function(x, i, j, ..., value) {
callNextMethod(x=x, i=i, j=j, ...=..., value=value) # [[<-
})
#' Subset an amsr Object
#'
#' Return a subset of a [amsr-class] object.
#'
#' This function is used to subset data within an [amsr-class]
#' object by `longitude` or by `latitude`. These two methods cannot
#' be combined in a single call, so two calls are required, as shown
#' in the Example.
#'
#' @param x an [amsr-class] object.
#'
#' @param subset an expression indicating how to subset `x`.
#'
#' @param ... ignored.
#'
#' @return An [amsr-class] object.
#'
#' @examples
#' library(oce)
#' data(amsr) # see ?amsr for how to read and composite such objects
#' sub <- subset(amsr, -75 < longitude & longitude < -45)
#' sub <- subset(sub, 40 < latitude & latitude < 50)
#' plot(sub)
#' data(coastlineWorld)
#' lines(coastlineWorld[['longitude']], coastlineWorld[['latitude']])
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
#' @family functions that subset oce objects
setMethod(f="subset",
signature="amsr",
definition=function(x, subset, ...) {
dots <- list(...)
debug <- if ("debug" %in% names(dots)) dots$debug else 0
oceDebug(debug, "subset,amsr-method() {\n", style="bold", sep="", unindent=1)
res <- x
subsetString <- paste(deparse(substitute(expr=subset, env=environment())), collapse=" ")
if (length(grep("longitude", subsetString))) {
if (length(grep("latitude", subsetString)))
stop("the subset must not contain both longitude and latitude. Call this twice, to combine these")
keep <- eval(expr=substitute(expr=subset, env=environment()),
envir=data.frame(longitude=x@metadata$longitude), enclos=parent.frame(2))
oceDebug(debug, "keeping", sum(keep), "of", length(keep), "longitudes\n")
for (name in names(res@data)) {
oceDebug(debug, "processing", name, "\n")
res@data[[name]] <- res[[name, "raw"]][keep, ]
}
res@metadata$longitude <- x@metadata$longitude[keep]
} else if (length(grep("latitude", subsetString))) {
if (length(grep("longitude", subsetString)))
stop("the subset must not contain both longitude and latitude. Call this twice, to combine these")
keep <- eval(expr=substitute(expr=subset, env=environment()),
envir=data.frame(latitude=x@metadata$latitude), enclos=parent.frame(2))
oceDebug(debug, "keeping", sum(keep), "of", length(keep), "latitudes\n")
for (name in names(res@data)) {
oceDebug(debug, "processing", name, "\n")
res@data[[name]] <- x[[name, "raw"]][, keep]
}
res@metadata$latitude <- res@metadata$latitude[keep]
} else {
stop("may only subset by longitude or latitude")
}
res@processingLog <- processingLogAppend(res@processingLog, paste("subset(x, subset=", subsetString, ")", sep=""))
oceDebug(debug, "} # subset,amsr-method()\n", style="bold", sep="", unindent=1)
res
})
#' Plot an amsr Object
#'
#' Plot an image of a component of an [amsr-class] object.
#'
#' In addition to fields named directly in the object, such as `SSTDay` and
#' `SSTNight`, it is also possible to plot computed fields, such as `SST`,
#' which combines the day and night fields.
#'
#' @param x an [amsr-class] object.
#'
#' @param y character value indicating the name of the band to plot; if not provided,
#' `SST` is used; see the documentation for the [amsr-class] class for a list of bands.
#'
#' @param asp optional numerical value giving the aspect ratio for plot. The
#' default value, `NULL`, means to use an aspect ratio of 1 for world views,
#' and a value computed from `ylim`, if the latter is specified in the
#' `...` argument.
#'
#' @param breaks optional numeric vector of the z values for breaks in the color scheme.
#' If `colormap` is provided, it takes precedence over `breaks` and `col`.
#'
#' @param col optional argument, either a vector of colors corresponding to the breaks, of length
#' 1 less than the number of breaks, or a function specifying colors.
#' If neither `col` or `colormap` is provided, then `col` defaults to
#' [oceColorsTemperature()].
#' If `colormap` is provided, it takes precedence over `breaks` and `col`.
#'
#' @param colormap a specification of the colormap to use, as created
#' with [colormap()]. If `colormap` is NULL, which is the default, then
#' a colormap is created to cover the range of data values, using
#' [oceColorsTemperature] colour scheme.
#' If `colormap` is provided, it takes precedence over `breaks` and `col`.
#' See \dQuote{Examples} for an example of using the "turbo" colour scheme.
#'
#' @param zlim optional numeric vector of length 2, giving the limits
#' of the plotted quantity. A reasonable default is computed, if this
#' is not given.
#'
#' @param missingColor List of colors for problem cases. The names of the
#' elements in this list must be as in the default, but the colors may
#' be changed to any desired values. These default values work reasonably
#' well for SST images, which are the default image, and which employ a
#' blue-white-red blend of colors, no mixture of which matches the
#' default values in `missingColor`.
#'
#' @param debug A debugging flag, integer.
#'
#' @param ... extra arguments passed to [imagep()], e.g. to control
#' the view with `xlim` (for longitude) and `ylim` (for latitude).
#'
#' @examples
#' library(oce)
#' data(coastlineWorld)
#' data(amsr) # see ?amsr for how to read and composite such objects
#'
#' # Example 1: plot with default colour scheme, oceColorsTemperature()
#' plot(amsr, "SST")
#' lines(coastlineWorld[['longitude']], coastlineWorld[['latitude']])
#'
#' # Example 2: 'turbo' colour scheme
#' plot(amsr, "SST", col=oceColorsTurbo)
#' lines(coastlineWorld[['longitude']], coastlineWorld[['latitude']])
#'
#' @author Dan Kelley
#'
#' @family things related to amsr data
#' @family functions that plot oce data
#'
#' @aliases plot.amsr
setMethod(f="plot",
signature=signature("amsr"),
# FIXME: how to let it default on band??
definition=function(x, y, asp=NULL,
breaks, col, colormap, zlim,
missingColor=list(land="papayaWhip",
none="lightGray",
bad="gray",
rain="plum",
ice="mediumVioletRed"),
debug=getOption("oceDebug"), ...)
{
dots <- list(...)
oceDebug(debug, "plot.amsr(..., y=c(",
if (missing(y)) "(missing)" else y, ", ...) {\n", sep="", style="bold", unindent=1)
zlimGiven <- !missing(zlim)
if (missing(y))
y <- "SST"
lon <- x[["longitude"]]
lat <- x[["latitude"]]
# Examine ylim (if asp is not NULL) and also at both xlim and ylim to
# compute zrange.
xlim <- dots$xlim
ylim <- dots$ylim
if (is.null(asp)) {
if (!is.null(ylim)) {
asp <- 1 / cos(pi/180*abs(mean(ylim, na.rm=TRUE)))
oceDebug(debug, "inferred asp=", asp, " from ylim argument\n", sep="")
} else {
asp <- 1 / cos(pi/180*abs(mean(lat, na.rm=TRUE)))
oceDebug(debug, "inferred asp=", asp, " from ylim argument\n", sep="")
}
} else {
oceDebug(debug, "using supplied asp=", asp, "\n", sep="")
}
z <- x[[y]]
# Compute zrange for world data, or data narrowed to xlim and ylim.
if (!is.null(xlim)) {
if (!is.null(ylim)) {
oceDebug(debug, "computing range based on z trimmed by xlim and ylim\n")
zrange <- range(z[xlim[1] <= lon & lon <= xlim[2], ylim[1] <= lat & lat <= ylim[2]], na.rm=TRUE)
} else {
oceDebug(debug, "computing range based on z trimmed by xlim alone\n")
zrange <- range(z[xlim[1] <= lon & lon <= xlim[2], ], na.rm=TRUE)
}
} else {
if (!is.null(ylim)) {
oceDebug(debug, "computing range based on z trimmed by ylim alone\n")
zrange <- range(z[, ylim[1] <= lat & lat <= ylim[2]], na.rm=TRUE)
} else {
oceDebug(debug, "computing range based on whole-world data\n")
zrange <- range(z, na.rm=TRUE)
}
}
oceDebug(debug, "zrange: ", paste(zrange, collapse=" to "), "\n")
# Determine colormap, if not given as an argument.
if (missing(colormap)) {
oceDebug(debug, "case 1: 'colormap' not given, so will be computed here\n")
if (!missing(breaks)) {
oceDebug(debug, "case 1.1: 'breaks' was specified\n")
if (debug > 0) {
cat("FYI breaks are as follows:\n")
print(breaks)
}
if (!missing(col)) {
oceDebug(debug, "case 1.1.1: computing colormap from specified breaks and specified col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else range(breaks), col=col)
} else {
oceDebug(debug, "case 1.1.2: computing colormap from specified breaks and computed col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else range(breaks), col=oceColorsTemperature)
}
} else {
oceDebug(debug, "case 1.2: 'breaks' was not specified\n")
if (!missing(col)) {
oceDebug(debug, "case 1.2.1: computing colormap from and computed breaks and specified col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else zrange, col=col)
} else {
oceDebug(debug, "case 1.2.2: computing colormap from computed breaks and computed col\n")
colormap <- oce::colormap(zlim=if (zlimGiven) zlim else zrange, col=oceColorsTemperature)
}
}
} else {
oceDebug(debug, "using specified colormap, ignoring breaks and col, whether they were supplied or not\n")
}
i <- if ("zlab" %in% names(dots)) {
oceDebug(debug, "calling imagep() with asp=", asp, ", and zlab=\"", dots$zlab, "\"\n", sep="")
imagep(lon, lat, z, colormap=colormap, asp=asp, debug=debug-1, ...)
} else {
oceDebug(debug, "calling imagep() with asp=", asp, ", and no zlab argument\n", sep="")
imagep(lon, lat, z, colormap=colormap, zlab=y, asp=asp, debug=debug-1, ...)
}
# Handle missing-data codes by redrawing the (decimate) image. Perhaps
# imagep() should be able to do this, but imagep() is a long function
# with a lot of interlocking arguments so I'll start by doing this
# manually here, and, if I like it, I'll extend imagep() later. Note
# that I added a new element of the return value of imagep(), to get the
# decimation factor.
missingColorLength <- length(missingColor)
if (5 != missingColorLength)
stop("must have 5 elements in the missingColor argument")
if (!all(sort(names(missingColor))==sort(c("land", "none", "bad", "ice", "rain"))))
stop("missingColor names must be: 'land', 'none', 'bad', 'ice' and 'rain'")
lonDecIndices <- seq(1L, length(lon), by=i$decimate[1])
latDecIndices <- seq(1L, length(lat), by=i$decimate[2])
lon <- lon[lonDecIndices]
lat <- lat[latDecIndices]
codes <- list(land=as.raw(255), # land
none=as.raw(254), # missing data
bad=as.raw(253), # bad observation
ice=as.raw(252), # sea ice
rain=as.raw(251)) # heavy rain
for (codeName in names(codes)) {
bad <- x[[y, "raw"]][lonDecIndices, latDecIndices] == as.raw(codes[[codeName]])
image(lon, lat, bad,
col=c("transparent", missingColor[[codeName]]), add=TRUE)
}
box()
oceDebug(debug, "} # plot.amsr()\n", sep="", style="bold", unindent=1)
})
#' Download and Cache an amsr File
#'
#' If the file is already present in `destdir`, then it is not
#' downloaded again. The default `destdir` is the present directory,
#' but it probably makes more sense to use something like `"~/data/amsr"`
#' to make it easy for scripts in other directories to use the cached data.
#' The file is downloaded with [download.file()].
#'
#' @param year,month,day Numerical values of the year, month, and day
#' of the desired dataset. Note that one file is archived per day,
#' so these three values uniquely identify a dataset.
#' If `day` and `month` are not provided but `day` is,
#' then the time is provided in a relative sense, based on the present
#' date, with `day` indicating the number of days in the past.
#' Owing to issues with timezones and the time when the data
#' are uploaded to the server, `day=3` may yield the
#' most recent available data. For this reason, there is a
#' third option, which is to leave `day` unspecified, which
#' works as though `day=3` had been given.
#'
#' @param destdir A string naming the directory in which to cache the downloaded file.
#' The default is to store in the present directory, but many users find it more
#' helpful to use something like `"~/data/amsr"` for this, to collect all
#' downloaded amsr files in one place.
#' @param server A string naming the server from which data
#' are to be acquired. See \dQuote{History}.
#'
#' @section History:
#' Until 25 March 2017, the default server was
#' `"ftp.ssmi.com/amsr2/bmaps_v07.2"`, but this was changed when the author
#' discovered that this FTP site had been changed to require users to create
#' accounts to register for downloads. The default was changed to
#' `"http://data.remss.com/amsr2/bmaps_v07.2"` on the named date.
#' This site was found by a web search, but it seems to provide proper data.
#' It is assumed that users will do some checking on the best source.
#'
#' On 23 January 2018, it was noticed that the server-url naming convention
#' had changed, e.g.
#' `http://data.remss.com/amsr2/bmaps_v07.2/y2017/m01/f34_20170114v7.2.gz`
#' becoming
#' `http://data.remss.com/amsr2/bmaps_v08/y2017/m01/f34_20170114v8.gz`
#'
#' @return A character value indicating the filename of the result; if
#' there is a problem of any kind, the result will be the empty
#' string.
#'
#' @examples
#'\dontrun{
#' # The download takes several seconds.
#' f <- download.amsr(2017, 1, 14) # Jan 14, 2017
#' d <- read.amsr(f)
#' plot(d)
#' mtext(d[["filename"]], side=3, line=0, adj=0)
#'}
#'
#' @family functions that download files
#' @family functions that plot oce data
#' @family things related to amsr data
#'
#' @references
#' `http://images.remss.com/amsr/amsr2_data_daily.html`
#' provides daily images going back to 2012. Three-day,
#' monthly, and monthly composites are also provided on that site.
download.amsr <- function(year, month, day, destdir=".", server="http://data.remss.com/amsr2/bmaps_v08")
{
# ftp ftp://ftp.ssmi.com/amsr2/bmaps_v07.2/y2016/m08/f34_20160804v7.2.gz
if (missing(year) && missing(month)) {
if (missing(day))
day <- 3
day <- abs(day)
today <- as.POSIXlt(Sys.Date() - day)
year <- 1900 + today$year
month <- 1 + today$mon
day <- today$mday
}
year <- as.integer(year)
month <- as.integer(month)
day <- as.integer(day)
destfile <- sprintf("f34_%4d%02d%02dv8.gz", year, month, day)
destpath <- paste(destdir, destfile, sep="/")
# example
# http://data.remss.com/amsr2/bmaps_v07.2/y2015/m11/f34_20151101v7.2.gz
if (tail(destpath, 1)=="/") { # remove trailing slash
destpath <- substr(destpath, 1, length(destpath)-1)
}
if (0 == length(list.files(path=destdir, pattern=paste("^", destfile, "$", sep="")))) {
source <- sprintf("%s/y%4d/m%02d/%s", server, year, month, destfile)
bad <- download.file(source, destfile)
if (!bad && destdir != ".")
system(paste("mv", destfile, destpath))
} else {
message("Not downloading ", destfile, " because it is already present in ", destdir)
}
if (destdir == ".") destfile else destpath
}
#' Read an amsr File
#'
#' Read a compressed amsr file, generating an [amsr-class] object.
#' Note that only compressed files are read in this version.
#'
#' AMSR files are provided at the FTP site, at
#' \code{ftp.ssmi.com/amsr2/bmaps_v07.2} as of April 2021.
#' To acquire such files,
#' log in as "guest",
#' then enter a year-based directory (e.g. `y2016` for the year 2016),
#' then enter a month-based directory (e.g. `m08` for August, the 8th
#' month), and then download a file for the present date, e.g.
#' `f34_20160803v7.2.gz` for August 3rd, 2016. Do not uncompress
#' this file, since `read.amsr` can only read the raw files from the server.
#' If `read.amsr` reports an error on the number of chunks, try
#' downloading a similarly-named file (e.g. in the present example,
#' `read.amsr("f34_20160803v7.2_d3d.gz")` will report an error
#' about inability to read a 6-chunk file, but
#' `read.amsr("f34_20160803v7.2.gz")` will work properly.
#'
#' @param file String indicating the name of a compressed file. See
#' \dQuote{File sources}.
#'
#' @template encodingIgnoredTemplate
#'
#' @param debug A debugging flag, integer.
#'
#' @seealso [plot,amsr-method()] for an example.
#'
#' @author Dan Kelley and Chantelle Layton
#'
#' @family things related to amsr data
read.amsr <- function(file, encoding=NA, debug=getOption("oceDebug"))
{
if (missing(file))
stop("must supply 'file'")
if (is.character(file)) {
if (!file.exists(file))
stop("cannot find file '", file, "'")
if (0L == file.info(file)$size)
stop("empty file '", file, "'")
}
oceDebug(debug, "read.amsr(file=\"", file, "\",",
#if (length(band) > 1) paste("band=c(\"", paste(band, collapse="\",\""), "\")", sep="") else
", debug=", debug, ") {\n", sep="", unindent=1)
res <- new("amsr")
filename <- file
res@metadata$filename <- filename
file <- if (length(grep(".*.gz$", filename))) gzfile(filename, "rb") else file(filename, "rb")
on.exit(close(file))
# we can hard-code a max size because the satellite data size is not variable
buf <- readBin(file, what="raw", n=50e6, endian="little")
nbuf <- length(buf)
dim <- c(1440, 720)
nchunks <- nbuf / prod(dim)
if (nchunks != round(nchunks))
stop("error: the data length ", nbuf, " is not an integral multiple of ", dim[1], "*", dim[2])
# From an amsr webpage --
# Each binary data file available from our ftp site consists of fourteen (daily) or
# six (averaged) 0.25 x 0.25 degree grid (1440,720) byte maps. For daily files,
# seven daytime, ascending maps in the following order, Time (UTC), Sea Surface
# Temperature (SST), 10 meter Surface Wind Speed (WSPD-LF), 10 meter Surface
# Wind Speed (WSPD-MF), Atmospheric Water Vapor (VAPOR), Cloud Liquid Water (CLOUD),
# and Rain Rate (RAIN), are followed by seven nighttime maps in the same order.
# Time-Averaged files contain just the geophysical layers in the same order
# [SST, WSPD-LF, WSPD-MF,VAPOR, CLOUD, RAIN].
select <- seq.int(1L, prod(dim))
if (nchunks == 14) {
oceDebug(debug, "14-chunk amsr file\n")
timeDay <- buf[select]
SSTDay <- buf[prod(dim) + select]
LFwindDay <- buf[2*prod(dim) + select]
MFwindDay <- buf[3*prod(dim) + select]
vaporDay <- buf[4*prod(dim) + select]
cloudDay <- buf[5*prod(dim) + select]
rainDay <- buf[6*prod(dim) + select]
dim(timeDay) <- dim
dim(SSTDay) <- dim
dim(LFwindDay) <- dim
dim(MFwindDay) <- dim
dim(vaporDay) <- dim
dim(cloudDay) <- dim
dim(rainDay) <- dim
timeNight <- buf[7*prod(dim) + select]
SSTNight <- buf[8*prod(dim) + select]
LFwindNight <- buf[9*prod(dim) + select]
MFwindNight <- buf[10*prod(dim) + select]
vaporNight <- buf[11*prod(dim) + select]
cloudNight <- buf[12*prod(dim) + select]
rainNight <- buf[13*prod(dim) + select]
dim(timeNight) <- dim
dim(SSTNight) <- dim
dim(LFwindNight) <- dim
dim(MFwindNight) <- dim
dim(vaporNight) <- dim
dim(cloudNight) <- dim
dim(rainNight) <- dim
res@metadata$units$SSTDay <- list(unit=expression(degree*C), scale="ITS-90")
res@metadata$units$SSTNight <- list(unit=expression(degree*C), scale="ITS-90")
res@metadata$units$LFwindDay <- list(unit=expression(m/s), scale="")
res@metadata$units$LFwindNight <- list(unit=expression(m/s), scale="")
res@metadata$units$MFwindDay <- list(unit=expression(m/s), scale="")
res@metadata$units$MFwindNight <- list(unit=expression(m/s), scale="")
res@metadata$units$rainDay <- list(unit=expression(mm/h), scale="")
res@metadata$units$rainNight <- list(unit=expression(mm/h), scale="")
res@data <- list(timeDay=timeDay,
SSTDay=SSTDay, LFwindDay=LFwindDay, MFwindDay=MFwindDay,
vaporDay=vaporDay, cloudDay=cloudDay, rainDay=rainDay,
timeNight=timeNight,
SSTNight=SSTNight, LFwindNight=LFwindNight, MFwindNight=MFwindNight,
vaporNight=vaporNight, cloudNight=cloudNight, rainNight=rainNight)
res@metadata$longitude <- 0.25 * 1:dim[1] - 0.125
res@metadata$latitude <- 0.25 * 1:dim[2] - 90.125
# rearrange matrices so that Greenwich is near the centre
for (name in names(res@data)) {
t <- matrixShiftLongitude(res@data[[name]], res@metadata$longitude)
res@data[[name]] <- t$m
}
res@metadata$longitude <- t$longitude
} else if (nchunks == 6) {
stop("Cannot (yet) read 6-chunk data. Please contact the developers if you need this file (and be sure to send the file to them).")
} else {
stop("Can only handle 14-chunk data; this file has ",
nchunks, " chunks. Please contact the developers if you need to read this file.")
}
res@metadata$spacecraft <- "amsr"
res@processingLog <- processingLogAppend(res@processingLog,
paste(deparse(match.call()), sep="", collapse=""))
oceDebug(debug, "} # read.amsr()\n", unindent=1)
res
}
#' Create a composite of amsr satellite data
#'
#' Form averages for each item in the `data` slot of the supplied objects,
#' taking into account the bad-data codes.
#'
#' If none of the objects has good
#' data at any particular pixel (i.e. particular latitude and longitude),
#' the resultant will have the bad-data code of the last item in the argument
#' list.
#' The metadata in the result are taken directly from the metadata of the
#' final argument, except that the filename is set to a comma-separated list
#' of the component filenames.
#'
#' @param object An [amsr-class] object.
#'
#' @param ... Other amsr objects.
#'
#' @family things related to amsr data
#'
#' @template compositeTemplate
setMethod("composite",
c(object="amsr"),
function(object, ...) {
dots <- list(...)
ndots <- length(dots)
if (ndots < 1)
stop("need more than one argument")
for (idot in 1:ndots) {
if (!inherits(dots[[idot]], "amsr"))
stop("argument ", 1+idot, " does not inherit from 'amsr'")
}
# inherit most of the metadata from the last argument
res <- dots[[ndots]]
filenames <- object[["filename"]]
for (idot in 1:ndots)
filenames <- paste(filenames, ",", dots[[idot]][["filename"]], sep="")
n <- 1 + ndots
dim <- c(dim(object@data[[1]]), n)
for (name in names(object@data)) {
a <- array(as.raw(0xff), dim=dim)
a[, , 1] <- object@data[[name]]
for (idot in 1:ndots)
a[, , 1+idot] <- dots[[idot]]@data[[name]]
A <- do_amsr_composite(a, dim(a))
res@data[[name]] <- A
}
res@metadata$filename <- filenames
res
})
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Functions.R
\name{spp692}
\alias{spp692}
\title{species function}
\usage{
spp692(a, b, c, d, e)
}
\arguments{
\item{a}{environmental parameter}
\item{b}{environmental parameter}
\item{c}{environmental parameter}
\item{d}{environmental parameter}
\item{e}{environmental parameter}
}
\description{
species function
}
\examples{
spp692()
}
\keyword{function}
\keyword{species}
|
/man/spp692.Rd
|
permissive
|
Djeppschmidt/Model.Microbiome
|
R
| false
| true
| 456
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Functions.R
\name{spp692}
\alias{spp692}
\title{species function}
\usage{
spp692(a, b, c, d, e)
}
\arguments{
\item{a}{environmental parameter}
\item{b}{environmental parameter}
\item{c}{environmental parameter}
\item{d}{environmental parameter}
\item{e}{environmental parameter}
}
\description{
species function
}
\examples{
spp692()
}
\keyword{function}
\keyword{species}
|
######
#Author: Nashipae Waweru
#Date: 28/MARCH/2020
#Title: Building a function
# Write a function that flips a coin 100 times.
# Solution
flip <- function(){
coin <- c("Head", "Tail")
result <- sample(coin, size = 100, replace = TRUE, prob = c(0.3, 0.7) )
print(result)
}
flip()
?sample()
# Hint: create a coin object that stores the values "heads" and "tails".
# Make the coin unfair so that 70% of the time it comes up tails.
|
/Day 12/Exercise5.R
|
no_license
|
Nashie-R/100DaysOfCodingR.
|
R
| false
| false
| 467
|
r
|
######
#Author: Nashipae Waweru
#Date: 28/MARCH/2020
#Title: Building a function
# Write a function that flips a coin 100 times.
# Solution
flip <- function(){
coin <- c("Head", "Tail")
result <- sample(coin, size = 100, replace = TRUE, prob = c(0.3, 0.7) )
print(result)
}
flip()
?sample()
# Hint: create a coin object that stores the values "heads" and "tails".
# Make the coin unfair so that 70% of the time it comes up tails.
|
"batons2" <-
function(..., waist = FALSE){
bstats <- boxplot(..., plot=FALSE)
n <- ncol(bstats$stats)
max.range <- range(unlist(bstats[c(1,3:4)]))
# start plot
cl <- match.call()
if(is.na(match("xlim", names(cl)))){xl <- c(0, n+1)}
else{xl <- cl$xlim}
if(is.na(match("ylim", names(cl)))){yl <- max.range + diff(max.range)*c(-0.1, 0.1)}
else{yl <- cl$ylim}
plot.default(x = seq(n), y = max.range, type="n", xlim=xl, ylim=yl, ...)
# draw extremes
segments(seq(n), bstats$stats[1,], seq(n), bstats$stats[5,])
}
|
/simba/R/batons2.R
|
no_license
|
ingted/R-Examples
|
R
| false
| false
| 520
|
r
|
"batons2" <-
function(..., waist = FALSE){
bstats <- boxplot(..., plot=FALSE)
n <- ncol(bstats$stats)
max.range <- range(unlist(bstats[c(1,3:4)]))
# start plot
cl <- match.call()
if(is.na(match("xlim", names(cl)))){xl <- c(0, n+1)}
else{xl <- cl$xlim}
if(is.na(match("ylim", names(cl)))){yl <- max.range + diff(max.range)*c(-0.1, 0.1)}
else{yl <- cl$ylim}
plot.default(x = seq(n), y = max.range, type="n", xlim=xl, ylim=yl, ...)
# draw extremes
segments(seq(n), bstats$stats[1,], seq(n), bstats$stats[5,])
}
|
mydata <- read.table('/Users/apple/Downloads/household_power_consumption.txt', sep = ';', header = TRUE)
mydata$Date <- strptime(mydata$Date, format = "%d/%m/%Y")
mydata$Date <- as.Date(mydata$Date)
new_data <- mydata[mydata$Date >= as.Date(strptime("1/2/07", "%d/%m/%y")) & mydata$Date <= as.Date(strptime("2/2/07", "%d/%m/%y")), ]
new_data$Global_active_power = as.numeric(new_data$Global_active_power)
new_data$full_date = as.POSIXct(paste(new_data$Date, new_data$Time), format="%Y-%m-%d %H:%M:%S")
library(ggplot2)
# qplot(mydata$Global_active_power/1000, geom = "histogram",
# xlab = "Global Active Power (kilowatt)",
# ylab = "Frequency",
# main = "Global Active Power",
# fill=I("red"),
# col=I("black"),
# binwidth=0.5,
# xlim = c(0, 6))
png(filename = "/Users/apple/Desktop/exploratory-data-analysis-course/ExData_Plotting1/plot1.png",
width = 480, height = 480)
hist(x = new_data$Global_active_power/1000, col = 'red', xlab = 'Global Active Power (kilowatt)',
main = "Global Active Power", xlim = c(0, 6))
dev.off()
|
/plot1.R
|
no_license
|
marmohamed/ExData_Plotting1
|
R
| false
| false
| 1,090
|
r
|
mydata <- read.table('/Users/apple/Downloads/household_power_consumption.txt', sep = ';', header = TRUE)
mydata$Date <- strptime(mydata$Date, format = "%d/%m/%Y")
mydata$Date <- as.Date(mydata$Date)
new_data <- mydata[mydata$Date >= as.Date(strptime("1/2/07", "%d/%m/%y")) & mydata$Date <= as.Date(strptime("2/2/07", "%d/%m/%y")), ]
new_data$Global_active_power = as.numeric(new_data$Global_active_power)
new_data$full_date = as.POSIXct(paste(new_data$Date, new_data$Time), format="%Y-%m-%d %H:%M:%S")
library(ggplot2)
# qplot(mydata$Global_active_power/1000, geom = "histogram",
# xlab = "Global Active Power (kilowatt)",
# ylab = "Frequency",
# main = "Global Active Power",
# fill=I("red"),
# col=I("black"),
# binwidth=0.5,
# xlim = c(0, 6))
png(filename = "/Users/apple/Desktop/exploratory-data-analysis-course/ExData_Plotting1/plot1.png",
width = 480, height = 480)
hist(x = new_data$Global_active_power/1000, col = 'red', xlab = 'Global Active Power (kilowatt)',
main = "Global Active Power", xlim = c(0, 6))
dev.off()
|
#' @title
#' Devide a matrix or a data.frame into two subsets.
#'
#' @description
#' Similar function as dplyr::sample_frac but return both sampled and remained subset.
#'
#' @param tbl [a matrix] or [a data.frame] to be split.
#' @param size [a mumeric] Sampling ratio. Must be between 0 and 1.
#'
#' @examples
#' sep_iris <- splitFrac(iris, 0.8)
#' str(sep_iris)
#'
#' @return a list
#' @export
splitFrac <- function(tbl, size=1)
{
stopifnot(NROW(tbl)>1, size<=1, size>0)
pos <- sample(NROW(tbl), size*NROW(tbl), replace=FALSE)
list(sample = tbl[pos,],
remain = tbl[-pos,])
}
|
/R/split_frac.R
|
no_license
|
katokohaku/SKmisc
|
R
| false
| false
| 607
|
r
|
#' @title
#' Devide a matrix or a data.frame into two subsets.
#'
#' @description
#' Similar function as dplyr::sample_frac but return both sampled and remained subset.
#'
#' @param tbl [a matrix] or [a data.frame] to be split.
#' @param size [a mumeric] Sampling ratio. Must be between 0 and 1.
#'
#' @examples
#' sep_iris <- splitFrac(iris, 0.8)
#' str(sep_iris)
#'
#' @return a list
#' @export
splitFrac <- function(tbl, size=1)
{
stopifnot(NROW(tbl)>1, size<=1, size>0)
pos <- sample(NROW(tbl), size*NROW(tbl), replace=FALSE)
list(sample = tbl[pos,],
remain = tbl[-pos,])
}
|
library(ggplot2)
library(dplyr)
# load in misc functions to sort data and find best
source("./validation/soil_moisture/R/misc_functions.R")
# correlation matrix data
list.files("~/drought_indicators_data/correlation_matrix/",pattern = ".RData", full.names = T)%>%
lapply(., load, .GlobalEnv)
# set up storage lists for best cors
best_times_list = list()
best_cor_list = list()
best_times_mesonet_list = list()
best_cor_mesonet_list = list()
for(i in 1:8){
if(i < 5){
best_times_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 6))
colnames(best_times_list[[i]]) = c("2in","4in", "8in", "20in", "40in", "mean")
best_cor_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 6))
colnames(best_cor_list[[i]]) = c("2in","4in", "8in", "20in", "40in", "mean")
best_times_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 6))
colnames(best_times_mesonet_list[[i]]) = c("0in", "4in", "8in", "20in", "36in", "mean")
best_cor_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 6))
colnames(best_cor_mesonet_list[[i]]) = c("0in", "4in", "8in", "20in", "36in", "mean")
}
else{
best_times_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 12))
colnames(best_times_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("2in","4in", "8in", "20in", "40in", "mean"))
best_cor_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 12))
colnames(best_cor_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("2in","4in", "8in", "20in", "40in", "mean"))
best_times_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 12))
colnames(best_times_mesonet_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("0in", "4in", "8in", "20in", "36in", "mean"))
best_cor_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 12))
colnames(best_cor_mesonet_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("0in", "4in", "8in", "20in", "36in", "mean"))
}
}
names(best_times_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
names(best_cor_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
names(best_times_mesonet_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
names(best_cor_mesonet_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
#copy empty list for summer time corelation matrix
best_times_list_summer = best_times_list[(c(1:4))]
best_cor_list_summer = best_cor_list[(c(1:4))]
best_times_mesonet_list_summer = best_times_mesonet_list[(c(1:4))]
best_cor_mesonet_list_summer = best_cor_mesonet_list[(c(1:4))]
# find best correlations and times for snotel
for(i in 1:length(correlation_matrix_spi)){
tryCatch({
best_times_list$spi[i,] = find_best(correlation_matrix_spi[[i]])
best_times_list$spei[i,] = find_best(correlation_matrix_spei[[i]])
best_times_list$eddi[i,] = find_best_neg(correlation_matrix_snotel_eddi[[i]])
best_times_list$sedi[i,] = find_best_neg(correlation_matrix_snotel_sedi[[i]])
best_cor_list$spi[i,] = find_best_cor(correlation_matrix_spi[[i]])
best_cor_list$spei[i,] = find_best_cor(correlation_matrix_spei[[i]])
best_cor_list$eddi[i,] = find_best_cor_neg(correlation_matrix_snotel_eddi[[i]])
best_cor_list$sedi[i,] = find_best_cor_neg(correlation_matrix_snotel_sedi[[i]])
#repreat for summer
best_times_list_summer$spi[i,] = find_best(correlation_matrix_summer_snotel_spi[[i]])
best_times_list_summer$spei[i,] = find_best(correlation_matrix_summer_snotel_spei[[i]])
best_times_list_summer$eddi[i,] = find_best_neg(correlation_matrix_summer_snotel_eddi[[i]])
best_times_list_summer$sedi[i,] = find_best_neg(correlation_matrix_summer_snotel_sedi[[i]])
best_cor_list_summer$spi[i,] = find_best_cor(correlation_matrix_summer_snotel_spi[[i]])
best_cor_list_summer$spei[i,] = find_best_cor(correlation_matrix_summer_snotel_spei[[i]])
best_cor_list_summer$eddi[i,] = find_best_cor_neg(correlation_matrix_summer_snotel_eddi[[i]])
best_cor_list_summer$sedi[i,] = find_best_cor_neg(correlation_matrix_summer_snotel_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA))
})
}
# find best correlations and times for mesonet
for(i in 1:length(correlation_matrix_mesonet_spi)){
tryCatch({
best_times_mesonet_list$spi[i,] = find_best_mesonet(correlation_matrix_mesonet_spi[[i]])
best_times_mesonet_list$spei[i,] = find_best_mesonet(correlation_matrix_mesonet_spei[[i]])
best_times_mesonet_list$eddi[i,] = find_best_mesonet_neg(correlation_matrix_mesonet_eddi[[i]])
best_times_mesonet_list$sedi[i,] = find_best_mesonet_neg(correlation_matrix_mesonet_sedi[[i]])
best_cor_mesonet_list$spi[i,] = find_best_mesonet_cor(correlation_matrix_mesonet_spi[[i]])
best_cor_mesonet_list$spei[i,] = find_best_mesonet_cor(correlation_matrix_mesonet_spei[[i]])
best_cor_mesonet_list$eddi[i,] = find_best_mesonet_cor_neg(correlation_matrix_mesonet_eddi[[i]])
best_cor_mesonet_list$sedi[i,] = find_best_mesonet_cor_neg(correlation_matrix_mesonet_sedi[[i]])
#repeat for summer
best_times_mesonet_list_summer$spi[i,] = find_best_mesonet(correlation_matrix_summer_mesonet_spi[[i]])
best_times_mesonet_list_summer$spei[i,] = find_best_mesonet(correlation_matrix_summer_mesonet_spei[[i]])
best_times_mesonet_list_summer$eddi[i,] = find_best_mesonet_neg(correlation_matrix_summer_mesonet_eddi[[i]])
best_times_mesonet_list_summer$sedi[i,] = find_best_mesonet_neg(correlation_matrix_summer_mesonet_sedi[[i]])
best_cor_mesonet_list_summer$spi[i,] = find_best_mesonet_cor(correlation_matrix_summer_mesonet_spi[[i]])
best_cor_mesonet_list_summer$spei[i,] = find_best_mesonet_cor(correlation_matrix_summer_mesonet_spei[[i]])
best_cor_mesonet_list_summer$eddi[i,] = find_best_mesonet_cor_neg(correlation_matrix_summer_mesonet_eddi[[i]])
best_cor_mesonet_list_summer$sedi[i,] = find_best_mesonet_cor_neg(correlation_matrix_summer_mesonet_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA))
})
}
## playing with wet dry data
for(i in 1:length(wet_dry_correlation_matrix_snotel_spi)){
tryCatch({
best_times_list$spi_wet_dry[i,] = find_best_wet_dry(wet_dry_correlation_matrix_snotel_spi[[i]])
best_times_list$spei_wet_dry[i,] = find_best_wet_dry(wet_dry_correlation_matrix_snotel_spei[[i]])
best_times_list$eddi_wet_dry[i,] = find_best_wet_dry_neg(wet_dry_correlation_matrix_snotel_eddi[[i]])
best_times_list$sedi_wet_dry[i,] = find_best_wet_dry_neg(wet_dry_correlation_matrix_snotel_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
})
}
for(i in 1:length(wet_dry_correlation_matrix_mesonet_spi)){
tryCatch({
best_times_mesonet_list$spi_wet_dry[i,] = find_best_wet_dry_mesonet(wet_dry_correlation_matrix_mesonet_spi[[i]])
best_times_mesonet_list$spei_wet_dry[i,] = find_best_wet_dry_mesonet(wet_dry_correlation_matrix_mesonet_spei[[i]])
best_times_mesonet_list$eddi_wet_dry[i,] = find_best_wet_dry_mesonet_neg(wet_dry_correlation_matrix_mesonet_eddi[[i]])
best_times_mesonet_list$sedi_wet_dry[i,] = find_best_wet_dry_mesonet_neg(wet_dry_correlation_matrix_mesonet_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
})
}
# aggregate based on generalized depths
best_times_combined = list()
best_cor_combined = list()
best_times_combined_summer = list()
best_cor_combined_summer = list()
best_times_combined_wet_dry = list()
for(i in 1:4){
best_times_combined[[i]] = data.frame(shallow = c(best_times_list[[i]]$`2in`, best_times_list[[i]]$`4in`,
best_times_mesonet_list[[i]]$`0in`, best_times_mesonet_list[[i]]$`4in`),
middle = c(best_times_list[[i]]$`8in`, best_times_list[[i]]$`20in`,
best_times_mesonet_list[[i]]$`8in`, best_times_mesonet_list[[i]]$`20in`),
deep = c(best_times_list[[i]]$`40in`, best_times_mesonet_list[[i]]$`36in`),
mean = c(best_times_list[[i]]$mean, best_times_mesonet_list[[i]]$mean))
best_cor_combined[[i]] = data.frame(shallow = c(best_cor_list[[i]]$`2in`, best_cor_list[[i]]$`4in`,
best_cor_mesonet_list[[i]]$`0in`, best_cor_mesonet_list[[i]]$`4in`),
middle = c(best_cor_list[[i]]$`8in`, best_cor_list[[i]]$`20in`,
best_cor_mesonet_list[[i]]$`8in`, best_cor_mesonet_list[[i]]$`20in`),
deep = c(best_cor_list[[i]]$`40in`, best_cor_mesonet_list[[i]]$`36in`),
mean = c(best_cor_list[[i]]$mean, best_cor_mesonet_list[[i]]$mean))
# repeat for summer
best_times_combined_summer[[i]] = data.frame(shallow = c(best_times_list_summer[[i]]$`2in`, best_times_list_summer[[i]]$`4in`,
best_times_mesonet_list_summer[[i]]$`0in`, best_times_mesonet_list_summer[[i]]$`4in`),
middle = c(best_times_list_summer[[i]]$`8in`, best_times_list_summer[[i]]$`20in`,
best_times_mesonet_list_summer[[i]]$`8in`, best_times_mesonet_list_summer[[i]]$`20in`),
deep = c(best_times_list_summer[[i]]$`40in`, best_times_mesonet_list_summer[[i]]$`36in`),
mean = c(best_times_list_summer[[i]]$mean, best_times_mesonet_list_summer[[i]]$mean))
best_cor_combined_summer[[i]] = data.frame(shallow = c(best_cor_list_summer[[i]]$`2in`, best_cor_list_summer[[i]]$`4in`,
best_cor_mesonet_list_summer[[i]]$`0in`, best_cor_mesonet_list_summer[[i]]$`4in`),
middle = c(best_cor_list_summer[[i]]$`8in`, best_cor_list_summer[[i]]$`20in`,
best_cor_mesonet_list_summer[[i]]$`8in`, best_cor_mesonet_list_summer[[i]]$`20in`),
deep = c(best_cor_list_summer[[i]]$`40in`, best_cor_mesonet_list_summer[[i]]$`36in`),
mean = c(best_cor_list_summer[[i]]$mean, best_cor_mesonet_list_summer[[i]]$mean))
}
for(i in 5:8){
best_times_combined_wet_dry[[i]] = data.frame(
#wet
shallow_wet = c(best_times_list[[i]]$`wet_2in`, best_times_list[[i]]$`wet_4in`,
best_times_mesonet_list[[i]]$`wet_0in`, best_times_mesonet_list[[i]]$`wet_4in`),
middle_wet = c(best_times_list[[i]]$`wet_8in`, best_times_list[[i]]$`wet_20in`,
best_times_mesonet_list[[i]]$`wet_8in`, best_times_mesonet_list[[i]]$`wet_20in`),
deep_wet = c(best_times_list[[i]]$`wet_40in`, best_times_mesonet_list[[i]]$`wet_36in`),
mean_wet = c(best_times_list[[i]]$wet_mean, best_times_mesonet_list[[i]]$wet_mean),
#dry
shallow_dry = c(best_times_list[[i]]$`dry_2in`, best_times_list[[i]]$`dry_4in`,
best_times_mesonet_list[[i]]$`dry_0in`, best_times_mesonet_list[[i]]$`dry_4in`),
middle_dry = c(best_times_list[[i]]$`dry_8in`, best_times_list[[i]]$`dry_20in`,
best_times_mesonet_list[[i]]$`dry_8in`, best_times_mesonet_list[[i]]$`dry_20in`),
deep_dry = c(best_times_list[[i]]$`dry_40in`, best_times_mesonet_list[[i]]$`dry_36in`),
mean_dry = c(best_times_list[[i]]$dry_mean, best_times_mesonet_list[[i]]$dry_mean))
}
for(i in c(1,1,1,1)){
best_times_combined_wet_dry[[i]] = NULL
}
# rename and organize
names(best_times_combined) = c("spi","spei","eddi","sedi")
names(best_cor_combined) = c("spi","spei","eddi","sedi")
names(best_times_combined_wet_dry) = c("spi","spei","eddi","sedi")
depths = c("2 - 4in","8 - 20in", "36 - 40in", "Mean")
# plot density graphs by depth
plot = list()
for(i in 1:4){
best_cor_ggplot = c(round(median(best_cor_combined$spi[,i], na.rm = T),2),
round(median(best_cor_combined$spei[,i], na.rm = T),2),
round(median(best_cor_combined$eddi[,i], na.rm = T),2),
round(median(best_cor_combined$sedi[,i], na.rm = T),2))
names = c("SPI: r = ","SPEI: r = ","EDDI: r = ","SEDI: r = ")
names_short = c("SPI","SPEI","EDDI","SEDI")
data = rbind(extract_density(best_times_combined$spi[,i], "SPI"),
extract_density(best_times_combined$spei[,i], "SPEI"),
extract_density(best_times_combined$eddi[,i], "EDDI"),
extract_density(best_times_combined$sedi[,i], "SEDI"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
plot[[i]] = ggplot(data = data, aes(x = x, y=y, color = name))+
geom_line()+
ggtitle(paste0("Soil Moisture Depth = ", depths[i]))+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 14)+
xlim(0,600)+
theme(legend.position = c(0.75, 0.75))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = names_short,
values = c("blue", "black", "orange", "red"),
labels = paste0(names, best_cor_ggplot),
name = "Drought Metric")
}
plot_grid = cowplot::plot_grid(plot[[4]],plot[[1]],plot[[2]],plot[[3]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/correlation_density_unfrozen.png",
plot_grid, width = 10, height = 9, units = "in", dpi = 400)
# plot density graphs by metric
depth_plot = list()
names_short = c("SPI","SPEI","EDDI","SEDI")
for(i in 1:length(names_short)){
best_cor_ggplot = c(round(median(best_cor_combined[[i]]$mean, na.rm = T),2),
round(median(best_cor_combined[[i]]$shallow, na.rm = T),2),
round(median(best_cor_combined[[i]]$middle, na.rm = T),2),
round(median(best_cor_combined[[i]]$deep, na.rm = T),2))
data = rbind(extract_density(best_times_combined[[i]]$mean, "Mean"),
extract_density(best_times_combined[[i]]$shallow, "Shallow"),
extract_density(best_times_combined[[i]]$middle, "Middle"),
extract_density(best_times_combined[[i]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
depth_plot[[i]] = ggplot(data = data, aes(x = x, y = y, color = name))+
geom_line()+
ggtitle(names_short[i])+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 14)+
xlim(0,730)+
theme(legend.position = c(0.75, 0.75))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = c("Mean", "Shallow", "Middle", "Deep"),
values = c("black", "forestgreen", "blue", "purple"),
labels = paste0(c("Mean: r = ", "Shallow: r = ", "Middle: r = ", "Deep: r = "),
best_cor_ggplot),
name = "Probe Depth")
}
plot_grid_depth = cowplot::plot_grid(depth_plot[[1]],depth_plot[[2]],depth_plot[[3]],depth_plot[[4]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/depth_density_unfrozen.png",
plot_grid_depth, width = 10, height = 9, units = "in", dpi = 400)
### repeat for summer
# plot density graphs by metric
depth_plot_summer = list()
names_short = c("SPI","SPEI","EDDI","SEDI")
for(i in 1:length(names_short)){
best_cor_ggplot = c(round(median(best_cor_combined_summer[[i]]$mean, na.rm = T),2),
round(median(best_cor_combined_summer[[i]]$shallow, na.rm = T),2),
round(median(best_cor_combined_summer[[i]]$middle, na.rm = T),2),
round(median(best_cor_combined_summer[[i]]$deep, na.rm = T),2))
data = rbind(extract_density(best_times_combined_summer[[i]]$mean, "Mean"),
extract_density(best_times_combined_summer[[i]]$shallow, "Shallow"),
extract_density(best_times_combined_summer[[i]]$middle, "Middle"),
extract_density(best_times_combined_summer[[i]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
depth_plot_summer[[i]] = ggplot(data = data, aes(x = x, y = y, color = name))+
geom_line()+
ggtitle(paste0(names_short[i], " (May - October)"))+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 14)+
xlim(0,730)+
theme(legend.position = c(0.75, 0.75))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = c("Mean", "Shallow", "Middle", "Deep"),
values = c("black", "forestgreen", "blue", "purple"),
labels = paste0(c("Mean: r = ", "Shallow: r = ", "Middle: r = ", "Deep: r = "),
best_cor_ggplot),
name = "Probe Depth")
}
plot_grid_depth = cowplot::plot_grid(depth_plot_summer[[1]],depth_plot_summer[[2]],depth_plot_summer[[3]],depth_plot_summer[[4]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/depth_density_summer_unfrozen.png",
plot_grid_depth, width = 10, height = 9, units = "in", dpi = 400)
################# wet dry plot ##########################################
wet_dry_plot = list()
# plot density graphs by metric
names_short = c("SPI","SPEI","EDDI","SEDI")
for(i in 1:length(names_short)){
# best_cor_ggplot = c(round(median(best_cor_combined[[i]]$mean, na.rm = T),2),
# round(median(best_cor_combined[[i]]$shallow, na.rm = T),2),
# round(median(best_cor_combined[[i]]$middle, na.rm = T),2),
# round(median(best_cor_combined[[i]]$deep, na.rm = T),2))
data = rbind(extract_density_linetype(best_times_combined_wet_dry[[i]]$mean_wet, "Mean", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$shallow_wet, "Shallow", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$middle_wet, "Middle", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$deep_wet, "Deep", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$mean_dry, "Mean", "Drying"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$shallow_dry, "Shallow", "Drying"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$middle_dry, "Middle", "Drying"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$deep_dry, "Deep", "Drying"))
best_density = data %>%
group_by(name, linetype) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
wet_dry_plot[[i]] = ggplot(data = data, aes(x = x, y = y, color = name, linetype = linetype))+
geom_line()+
ggtitle(names_short[i])+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 12)+
xlim(0,600)+
theme(legend.position = c(0.85, 0.65))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = c("Mean", "Shallow", "Middle", "Deep"),
values = c("black", "forestgreen", "blue", "purple"))+
labs(color="Depth", linetype=NULL)
}
plot_grid_wet_dry = cowplot::plot_grid(wet_dry_plot[[1]],wet_dry_plot[[2]],wet_dry_plot[[3]],wet_dry_plot[[4]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/wet_dry_depth_plot.png",
plot_grid_wet_dry, width = 10, height = 9, units = "in", dpi = 400)
################# Monthly Post Processing and plots ########################
library(ggplot2)
library(scales)
index_names = c("SPI","SPEI","EDDI","SEDI")
monthly_data_snotel = list(monthly_correlation_matrix_snotel_spi, monthly_correlation_matrix_snotel_spei,
monthly_correlation_matrix_snotel_eddi, monthly_correlation_matrix_snotel_sedi)
monthly_data_mesonet = list(monthly_correlation_matrix_mesonet_spi, monthly_correlation_matrix_mesonet_spei,
monthly_correlation_matrix_mesonet_eddi, monthly_correlation_matrix_mesonet_sedi)
for(d in 1:length(monthly_data_snotel)){
#for(d in 1){
data = rbind(extract_density(best_times_combined[[d]]$mean, "Mean"),
extract_density(best_times_combined[[d]]$shallow, "Shallow"),
extract_density(best_times_combined[[d]]$middle, "Middle"),
extract_density(best_times_combined[[d]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)%>%
mutate(x = mround(x,5))
index = vector()
for(i in 1:4){
index[i] = which(best_times$x[i] == c(seq(5,730,5)))
}
#extract snotel
for(i in 1:length(monthly_data_snotel[[d]])){
mean_temp = monthly_data_snotel[[d]][[i]][[index[1]]]$mean_soil_moisture
shallow_temp = rowMeans(data.frame(in_2 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..2in..pct..Start.of.Day.Values,
in_4 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..4in..pct..Start.of.Day.Values),
na.rm = TRUE)
middle_temp = rowMeans(data.frame(in_8 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..8in..pct..Start.of.Day.Values,
in_20 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..20in..pct..Start.of.Day.Values),
na.rm = TRUE)
deep_temp = monthly_data_snotel[[d]][[i]][[index[4]]]$Soil.Moisture.Percent..40in..pct..Start.of.Day.Values
if(i == 1){
mean_full = data.frame(mean_temp)
shallow_full = data.frame(shallow_temp)
middle_full = data.frame(middle_temp)
deep_full = data.frame(deep_temp)
}
else{
mean_full = cbind(mean_full, mean_temp)
shallow_full = cbind(shallow_full, shallow_temp)
middle_full = cbind(middle_full, middle_temp)
deep_full = cbind(deep_full, deep_temp)
}
}
# extract mesonet
for(i in 1:length(monthly_data_mesonet[[d]])){
mean_temp = monthly_data_mesonet[[d]][[i]][[index[1]]]$mean_soil_moisture
mean_full = cbind(mean_full, mean_temp)
#shallow
shallow_temp = rowMeans(data.frame(in_0 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc00,
in_4 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc04),na.rm = TRUE)
shallow_full = cbind(shallow_full, shallow_temp)
#middle
middle_temp = rowMeans(data.frame(in_8 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc08,
in_20 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc20),na.rm = TRUE)
middle_full = cbind(middle_full, middle_temp)
#deep
deep_temp = monthly_data_mesonet[[d]][[i]][[index[4]]]$soilwc36
deep_full = cbind(deep_full, deep_temp)
}
summary = data.frame(median = apply(mean_full, 1, median, na.rm=TRUE),
upper = apply(mean_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(mean_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_shallow = data.frame(median = apply(shallow_full, 1, median, na.rm=TRUE),
upper = apply(shallow_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(shallow_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_middle = data.frame(median = apply(middle_full, 1, median, na.rm=TRUE),
upper = apply(middle_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(middle_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_deep = data.frame(median = apply(deep_full, 1, median, na.rm=TRUE),
upper = apply(deep_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(deep_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
find_summer_stat = function(x){
median = x %>%
mutate(month = c(1:12)) %>%
dplyr::filter(month > 4 & month < 11)%>%
summarise(median(median))
median = median$`median(median)`
return(median)
}
summary_list = list(summary, summary_shallow, summary_middle, summary_deep)
plot_monthly = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)*.7, height = 0.05, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)*.5, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plot_monthly_eddi = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)+0.1, height = 0.03, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)+0.15, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plots = list()
datasets = list(summary, summary_shallow, summary_middle, summary_deep)
colors = c("black", "forestgreen", "blue", "purple")
depths = c("Mean", "Shallow", "Middle", "Deep")
time_scale = c(seq(5,730,5)[index])
for(i in 1:4){
plots[[i]] = plot_monthly(datasets[[i]], colors[i], depths[i], time_scale[i], index_names[d], summary_list[[i]])
}
plot_grid_monthly = cowplot::plot_grid(plots[[1]],plots[[2]],plots[[3]],plots[[4]], nrow = 2)
plot_final = cowplot::plot_grid(depth_plot[[d]], plot_grid_monthly , nrow = 1)
ggsave(paste0("./validation/soil_moisture/plots/summary/plot_grid_monthly_",index_names[d],".png"),
plot_final, width = 12, height = 5, units = "in", dpi = 400)
}
#repeate for summer
library(ggplot2)
library(scales)
library(matrixStats)
index_names = c("SPI","SPEI","EDDI","SEDI")
monthly_data_snotel = list(monthly_correlation_matrix_snotel_spi, monthly_correlation_matrix_snotel_spei,
monthly_correlation_matrix_snotel_eddi, monthly_correlation_matrix_snotel_sedi)
monthly_data_mesonet = list(monthly_correlation_matrix_mesonet_spi, monthly_correlation_matrix_mesonet_spei,
monthly_correlation_matrix_mesonet_eddi, monthly_correlation_matrix_mesonet_sedi)
for(d in 1:length(monthly_data_snotel)){
#for(d in 1){
data = rbind(extract_density(best_times_combined_summer[[d]]$mean, "Mean"),
extract_density(best_times_combined_summer[[d]]$shallow, "Shallow"),
extract_density(best_times_combined_summer[[d]]$middle, "Middle"),
extract_density(best_times_combined_summer[[d]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)%>%
mutate(x = mround(x,5))
index = vector()
for(i in 1:4){
index[i] = which(best_times$x[i] == c(seq(5,730,5)))
}
#extract snotel
for(i in 1:length(monthly_data_snotel[[d]])){
mean_temp = monthly_data_snotel[[d]][[i]][[index[1]]]$mean_soil_moisture
shallow_temp = tryCatch({rowMedians(as.matrix(data.frame(in_2 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..2in..pct..Start.of.Day.Values,
in_4 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..4in..pct..Start.of.Day.Values)), na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
middle_temp = tryCatch({
rowMedians(as.matrix(data.frame(in_8 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..8in..pct..Start.of.Day.Values,
in_20 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..20in..pct..Start.of.Day.Values)), na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
deep_temp = monthly_data_snotel[[d]][[i]][[index[4]]]$Soil.Moisture.Percent..40in..pct..Start.of.Day.Values
if(i == 1){
mean_full = data.frame(mean_temp)
shallow_full = data.frame(shallow_temp)
middle_full = data.frame(middle_temp)
deep_full = data.frame(deep_temp)
}
else{
mean_full = cbind(mean_full, mean_temp)
shallow_full = cbind(shallow_full, shallow_temp)
middle_full = cbind(middle_full, middle_temp)
deep_full = cbind(deep_full, deep_temp)
}
}
# extract mesonet
for(i in 1:length(monthly_data_mesonet[[d]])){
mean_temp = monthly_data_mesonet[[d]][[i]][[index[1]]]$mean_soil_moisture
mean_full = cbind(mean_full, mean_temp)
#shallow
shallow_temp = tryCatch({rowMedians(as.matrix(data.frame(in_0 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc00,
in_4 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc04)),na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
shallow_full = cbind(shallow_full, shallow_temp)
#middle
middle_temp = tryCatch({rowMedians(as.matrix(data.frame(in_8 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc08,
in_20 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc20)),na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
middle_full = cbind(middle_full, middle_temp)
#deep
deep_temp = monthly_data_mesonet[[d]][[i]][[index[4]]]$soilwc36
deep_full = cbind(deep_full, deep_temp)
}
summary = data.frame(median = apply(mean_full, 1, median, na.rm=TRUE),
upper = apply(mean_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(mean_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_shallow = data.frame(median = apply(shallow_full, 1, median, na.rm=TRUE),
upper = apply(shallow_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(shallow_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_middle = data.frame(median = apply(middle_full, 1, median, na.rm=TRUE),
upper = apply(middle_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(middle_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_deep = data.frame(median = apply(deep_full, 1, median, na.rm=TRUE),
upper = apply(deep_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(deep_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
find_summer_stat = function(x){
median = x %>%
mutate(month = c(1:12)) %>%
dplyr::filter(month > 4 & month < 11)%>%
summarise(median(median))
median = median$`median(median)`
return(median)
}
summary_list = list(summary, summary_shallow, summary_middle, summary_deep)
plot_monthly = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)*.7, height = 0.05, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)*.5, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plot_monthly_eddi = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)+0.1, height = 0.03, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)+0.15, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plots = list()
datasets = list(summary, summary_shallow, summary_middle, summary_deep)
colors = c("black", "forestgreen", "blue", "purple")
depths = c("Mean", "Shallow", "Middle", "Deep")
time_scale = c(seq(5,730,5)[index])
for(i in 1:4){
plots[[i]] = plot_monthly(datasets[[i]], colors[i], depths[i], time_scale[i], index_names[d], summary_list[[i]])
}
plot_grid_monthly = cowplot::plot_grid(plots[[1]],plots[[2]],plots[[3]],plots[[4]], nrow = 2)
plot_final = cowplot::plot_grid(depth_plot_summer[[d]], plot_grid_monthly , nrow = 1)
ggsave(paste0("./validation/soil_moisture/plots/summary/plot_grid_monthly_summer_",index_names[d],".png"),
plot_final, width = 12, height = 5, units = "in", dpi = 400)
}
################### site map #######################
library(dplyr)
#read in geospatial data
station_data = read.csv("~/drought_indicators_data/mesonet/station_data_clean.csv")
station_data$X = NULL
snotel = read.csv("./validation/soil_moisture/snotel_data/nrcs_soil_moisture.csv")
snotel_cropped = snotel %>%
dplyr::select(site_name, latitude, longitude) %>%
rename(station_key = site_name)
snotel_cropped$network = "NRCS"
master_list = rbind(snotel_cropped,station_data)
master_times = cbind(master_list,
mean_time_spi = c(best_times_list$spi$mean, best_times_mesonet_list$spi$mean),
mean_time_spei = c(best_times_list$spei$mean, best_times_mesonet_list$spei$mean),
mean_time_eddi = c(best_times_list$eddi$mean, best_times_mesonet_list$eddi$mean),
mean_time_sedi = c(best_times_list$sedi$mean, best_times_mesonet_list$sedi$mean),
mean_cor_spi = c(best_cor_list$spi$mean, best_cor_mesonet_list$spi$mean),
mean_cor_spei = c(best_cor_list$spei$mean, best_cor_mesonet_list$spei$mean),
mean_cor_eddi = c(best_cor_list$eddi$mean, best_cor_mesonet_list$eddi$mean),
mean_cor_sedi = c(best_cor_list$sedi$mean, best_cor_mesonet_list$sedi$mean))
master_times_summer = cbind(master_list,
mean_time_spi = c(best_times_list_summer$spi$mean, best_times_mesonet_list_summer$spi$mean),
mean_time_spei = c(best_times_list_summer$spei$mean, best_times_mesonet_list_summer$spei$mean),
mean_time_eddi = c(best_times_list_summer$eddi$mean, best_times_mesonet_list_summer$eddi$mean),
mean_time_sedi = c(best_times_list_summer$sedi$mean, best_times_mesonet_list_summer$sedi$mean),
mean_cor_spi = c(best_cor_list_summer$spi$mean, best_cor_mesonet_list_summer$spi$mean),
mean_cor_spei = c(best_cor_list_summer$spei$mean, best_cor_mesonet_list_summer$spei$mean),
mean_cor_eddi = c(best_cor_list_summer$eddi$mean, best_cor_mesonet_list_summer$eddi$mean),
mean_cor_sedi = c(best_cor_list_summer$sedi$mean, best_cor_mesonet_list_summer$sedi$mean))
#write.csv(master_times, "./validation/soil_moisture/summary_data/geospatial_with_best.csv")
states = sf::st_read("/home/zhoylman/drought_indicators/shp_kml/states.shp") %>%
dplyr::filter(STATE_NAME != "Alaska" & STATE_NAME != "Hawaii")
states_union = sf::st_read("/home/zhoylman/drought_indicators/shp_kml/states.shp") %>%
dplyr::filter(STATE_NAME != "Alaska" & STATE_NAME != "Hawaii") %>%
st_union()
static_map = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_point(data = master_times, aes(x = longitude, y = latitude), fill = "blue",
color = "black", shape = 21, alpha = 0.5, size = 2)+
xlab("")+
ylab("")
static_map
ggsave(paste0("./validation/soil_moisture/plots/summary/site_map.png"),
static_map, width = 10, height = 5, units = "in", dpi = 400)
## example spei map
spei_map = raster::raster("/home/zhoylman/drought_indicators_data/spei_20190901_60_day.tif") %>%
rasterToPoints()%>%
as.data.frame() %>%
rename(spei = 3)
color_ramp = c("#8b0000", "#ff0000", "#ffffff", "#0000ff", "#00008b")
static_spei_map = ggplot() +
geom_sf(data = states_union, fill = "transparent", size = 1.5)+
geom_tile(data = spei_map, aes(x, y, fill = spei)) +
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
scale_fill_gradientn("SPEI", colours = color_ramp, limits = c(-3,3))+
ggtitle(paste0("Standardized Precipitation Evapotranspiration Index\n 9-1-2019 (60 Day Timescale)"))+
xlab("")+
ylab("")+
theme(plot.title = element_text(hjust = 0.5))
static_spei_map
ggsave(paste0("./validation/soil_moisture/plots/summary/spei_map.png"),
static_spei_map, width = 10, height = 5, units = "in", dpi = 420)
rbPal <- (colorRampPalette(c("darkblue", "blue", "lightblue", "yellow", "orange", "red", "darkred")))
index_names_lower = c("spi", "spei", "eddi", "sedi")
library(cowplot)
#best times saptial
for(i in 1:4){
data_select = master_times %>%
dplyr::select(longitude, latitude, paste0("mean_time_",index_names_lower[i]))%>%
na.omit()
static_map_metric = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))+
geom_point(data = data_select , aes(x = longitude, y = latitude,
fill = get(paste0("mean_time_",index_names_lower[i]))),
color = "black", shape = 21, alpha = 1, size = 2)+
xlab("")+
ylab("")+
ggtitle(paste0("Optimal Timescale (", index_names[i], ")"))+
scale_fill_gradientn("",colours=(rbPal(100)), guide = F)
#function to draw manual ramp
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
dummy_plot = ggplot(data = data_select) +
geom_tile(aes(y=latitude, x=longitude, fill = get(paste0("mean_time_",index_names_lower[i]))), alpha = 1)+
scale_fill_gradientn("Days",colours=(rbPal(100)))
#draw ramp
legend <- g_legend(dummy_plot)
#plot final plot
static_map_metric_inset =
ggdraw() +
draw_plot(static_map_metric) +
draw_plot(legend, x = .8, y = .2, width = .35, height = .35)
ggsave(paste0("./validation/soil_moisture/plots/summary/spatial_",index_names_lower[i],"_map.png"),
static_map_metric_inset, width = 10, height = 5, units = "in", dpi = 400)
}
#best times saptial (Summer)
for(i in 1:4){
data_select = master_times_summer %>%
dplyr::select(longitude, latitude, paste0("mean_time_",index_names_lower[i]))%>%
na.omit()
static_map_metric = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))+
geom_point(data = data_select , aes(x = longitude, y = latitude,
fill = get(paste0("mean_time_",index_names_lower[i]))),
color = "black", shape = 21, alpha = 1, size = 2)+
xlab("")+
ylab("")+
ggtitle(paste0("May - October Optimal Timescale (", index_names[i], ")"))+
scale_fill_gradientn("",colours=(rbPal(100)), guide = F)
#function to draw manual ramp
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
dummy_plot = ggplot(data = data_select) +
geom_tile(aes(y=latitude, x=longitude, fill = get(paste0("mean_time_",index_names_lower[i]))), alpha = 1)+
scale_fill_gradientn("Days",colours=(rbPal(100)))
#draw ramp
legend <- g_legend(dummy_plot)
#plot final plot
static_map_metric_inset =
ggdraw() +
draw_plot(static_map_metric) +
draw_plot(legend, x = .8, y = .2, width = .35, height = .35)
ggsave(paste0("./validation/soil_moisture/plots/summary/spatial_",index_names_lower[i],"_map_summer.png"),
static_map_metric_inset, width = 10, height = 5, units = "in", dpi = 400)
}
## montly all timescales
library(ggplot2)
library(scales)
library(matrixStats)
index_names = c("SPI","SPEI","EDDI","SEDI")
monthly_data_snotel = list(monthly_correlation_matrix_snotel_spi, monthly_correlation_matrix_snotel_spei,
monthly_correlation_matrix_snotel_eddi, monthly_correlation_matrix_snotel_sedi)
monthly_data_mesonet = list(monthly_correlation_matrix_mesonet_spi, monthly_correlation_matrix_mesonet_spei,
monthly_correlation_matrix_mesonet_eddi, monthly_correlation_matrix_mesonet_sedi)
# d for metrcs
#for(d in 1:length(monthly_data_snotel)){
plot_monthy = function(d){
timescale_line_plot = list()
monthly_ls = list()
# i for sites
for(t in 1:146){
for(i in 1:length(monthly_data_snotel[[d]])){
# t for timescales
mean_temp = monthly_data_snotel[[d]][[i]][[t]]$mean_soil_moisture
if(i == 1){
mean_full = data.frame(mean_temp)
}
else{
mean_full = cbind(mean_full, mean_temp)
}
}
for(i in 1:length(monthly_data_mesonet[[d]])){
# t for timescales
mean_temp_mesonet = monthly_data_mesonet[[d]][[i]][[t]]$mean_soil_moisture
if(i == 1){
mean_full_mesonet = data.frame(mean_temp_mesonet)
}
else{
mean_full_mesonet = cbind(mean_full_mesonet, mean_temp)
}
}
full = cbind(mean_full, mean_full_mesonet)
summary = data.frame(rowMedians(as.matrix(full), na.rm = T))
colnames(summary) = "median"
monthly_ls[[t]] = summary
}
monthly_df = as.data.frame(lapply(monthly_ls, cbind))
best_monthly_time = function(x, direction){
if(direction == "max"){
return(c(
seq(5,730,5)[which(monthly_df[x,] == max(monthly_df[x,]))],
max(monthly_df[x,])
))
}
if(direction == "min"){
return(c(
seq(5,730,5)[which(monthly_df[x,] == min(monthly_df[x,]))],
min(monthly_df[x,])
))
}
}
best_times = data.frame()
if(d < 3){
for(i in 1:12){best_times[i,1:2] = best_monthly_time(i, "max")}
}
if(d >= 3){
for(i in 1:12){best_times[i,1:2] = best_monthly_time(i, "min")}
}
best_times$time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M")
#plot results
colfunc <- colorRampPalette(c("darkblue", "blue", "lightblue", "yellow", "orange", "red", "darkred"))
cols = colfunc(146)
#y lim definitions
if(d == 1){
ylim_vals = c(-0.1,0.8)
yjust = 0.05
}
if(d == 2){
ylim_vals = c(-0.1,0.8)
yjust = 0.05
}
if(d == 3){
ylim_vals = c(-0.8,0.1)
yjust = -0.05
}
if(d == 4){
ylim_vals = c(-0.8,0.1)
yjust = -0.05
}
timescale_line_plot = ggplot()+
geom_line(data = NULL, aes(x = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"), y = monthly_df[,1]), color = cols[1]) +
theme_bw(base_size = 20) +
ylab("Correlation (r)")+
xlab("Month")+
ggtitle(index_names[d])+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
ylim(ylim_vals)+
theme(plot.title = element_text(hjust = 0.5))+
geom_text(data = best_times, aes(x = time, y = V2+yjust, label = V1))
for(g in 2:length(monthly_ls)){
temp_data = data.frame(x = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"),
y = monthly_df[,g])
timescale_line_plot = timescale_line_plot +
geom_line(data = temp_data, aes(x = x, y = y), color = cols[g])
}
return(timescale_line_plot)
}
colfunc <- colorRampPalette(c("darkblue", "blue", "lightblue", "yellow", "orange", "red", "darkred"))
#function to draw manual ramp
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
dummy_plot = ggplot(data = data.frame(x = seq(1:146), y = seq(1:146), z = seq(5,730, 5))) +
geom_tile(aes(y=y, x=x, fill = z), alpha = 1)+
scale_fill_gradientn("Days",colours=(colfunc(100)))
#draw ramp
legend <- g_legend(dummy_plot)
plot_grid_timescales = cowplot::plot_grid(plot_monthy(1),plot_monthy(2), NULL,
plot_monthy(3),plot_monthy(4), NULL,
nrow = 2, rel_widths = c(1, 1, 0.1,
1, 1, 0.1))
library(cowplot)
plot_grid_timescales_inset =
ggdraw() +
draw_plot(plot_grid_timescales) +
draw_plot(legend, x = .95, y = -0.05, width = .4, height = .4)
ggsave(paste0("./validation/soil_moisture/plots/summary/timescale_lines.png"),
plot_grid_timescales_inset, width = 14, height = 10, units = "in", dpi = 300)
# observed vs modeled
load('/home/zhoylman/drought_indicators_data/correlation_matrix/observed_modeled_cor.RData')
load("/home/zhoylman/drought_indicators_data/correlation_matrix/observed_modeled_cpc_cor.RData")
data = observed_vs_modeled %>%
dplyr::select(sm_gamma)%>%
tidyr::drop_na()
data2 = observed_vs_modeled_cpc %>%
dplyr::select(sm_gamma)%>%
tidyr::drop_na()
data_density = density(data$sm_gamma)
data_density$name = "Topofire"
data_density_2 = density(data2$sm_gamma)
data_density_2$name = "CPC"
master_times_summer_no_na = master_times_summer %>%
tidyr::drop_na()
density_list = list()
drought_names = c("SPI", "SPEI", 'EDDI', "SEDI")
for(i in 1:4){
density_list[[i]] = density(master_times_summer_no_na[,i+8])
density_list[[i]]$name = drought_names[i]
}
density_data = data.frame(x = c(data_density$x, data_density_2$x, density_list[[1]]$x,
density_list[[2]]$x, density_list[[3]]$x, density_list[[4]]$x),
y = c(data_density$y, data_density_2$y, density_list[[1]]$y,
density_list[[2]]$y, density_list[[3]]$y, density_list[[4]]$y),
name = c(rep("Topofire", 512), rep("CPC", 512), rep(density_list[[1]]$name, 512),
rep(density_list[[2]]$name, 512), rep(density_list[[3]]$name, 512), rep(density_list[[4]]$name, 512)))
plot = ggplot(data = density_data, aes(x = x, y=y, color = name))+
geom_line()+
ggtitle("Soil Moisture Correlations")+
xlab("Correlation (r)")+
ylab("Density")+
theme_bw(base_size = 12)+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
xlim(-1, 1)+
scale_color_manual(values=c("red", "purple", "green", "blue", "#E69F00", "black"),
limits = c(drought_names, "CPC", "Topofire"), name = "Predictor")
plot
ggsave(paste0("./validation/soil_moisture/plots/summary/correlation_distrobution_all.png"),
plot, width = 8, height = 5, units = "in", dpi = 300)
master_list_modeled_observed = rbind(station_data, snotel_cropped)
master_list_modeled_observed$r = observed_vs_modeled$sm_gamma
master_list_modeled_observed = master_list_modeled_observed %>%
tidyr::drop_na()
observed_vs_modeled_spatial = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_point(data = master_list_modeled_observed, aes(x = longitude, y = latitude, fill = r),
color = 'black', shape = 21, alpha = 0.8, size = 2)+
xlab("")+
ylab("")+
scale_fill_gradientn("",colours=rev(rbPal(100)))+
ggtitle(paste0("Observed ~ Modeled Soil Moisture Correlation (r)"))+
theme(plot.title = element_text(hjust = 0.5),
legend.position = c(0.92,0.35))
observed_vs_modeled_spatial
ggsave(paste0("./validation/soil_moisture/plots/summary/observed_vs_modeled_spatial.png"),
observed_vs_modeled_spatial, width = 10, height = 5, units = "in", dpi = 400)
|
/validation/soil_moisture/R/post_processing_correlations.R
|
no_license
|
LMXB/drought_indicators
|
R
| false
| false
| 55,404
|
r
|
library(ggplot2)
library(dplyr)
# load in misc functions to sort data and find best
source("./validation/soil_moisture/R/misc_functions.R")
# correlation matrix data
list.files("~/drought_indicators_data/correlation_matrix/",pattern = ".RData", full.names = T)%>%
lapply(., load, .GlobalEnv)
# set up storage lists for best cors
best_times_list = list()
best_cor_list = list()
best_times_mesonet_list = list()
best_cor_mesonet_list = list()
for(i in 1:8){
if(i < 5){
best_times_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 6))
colnames(best_times_list[[i]]) = c("2in","4in", "8in", "20in", "40in", "mean")
best_cor_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 6))
colnames(best_cor_list[[i]]) = c("2in","4in", "8in", "20in", "40in", "mean")
best_times_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 6))
colnames(best_times_mesonet_list[[i]]) = c("0in", "4in", "8in", "20in", "36in", "mean")
best_cor_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 6))
colnames(best_cor_mesonet_list[[i]]) = c("0in", "4in", "8in", "20in", "36in", "mean")
}
else{
best_times_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 12))
colnames(best_times_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("2in","4in", "8in", "20in", "40in", "mean"))
best_cor_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_spi), ncol = 12))
colnames(best_cor_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("2in","4in", "8in", "20in", "40in", "mean"))
best_times_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 12))
colnames(best_times_mesonet_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("0in", "4in", "8in", "20in", "36in", "mean"))
best_cor_mesonet_list[[i]] = data.frame(matrix(nrow = length(correlation_matrix_mesonet_spi), ncol = 12))
colnames(best_cor_mesonet_list[[i]]) = paste0(c(rep("wet_",6), rep("dry_",6)), c("0in", "4in", "8in", "20in", "36in", "mean"))
}
}
names(best_times_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
names(best_cor_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
names(best_times_mesonet_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
names(best_cor_mesonet_list) = c("spi","spei","eddi","sedi","spi_wet_dry","spei_wet_dry","eddi_wet_dry","sedi_wet_dry")
#copy empty list for summer time corelation matrix
best_times_list_summer = best_times_list[(c(1:4))]
best_cor_list_summer = best_cor_list[(c(1:4))]
best_times_mesonet_list_summer = best_times_mesonet_list[(c(1:4))]
best_cor_mesonet_list_summer = best_cor_mesonet_list[(c(1:4))]
# find best correlations and times for snotel
for(i in 1:length(correlation_matrix_spi)){
tryCatch({
best_times_list$spi[i,] = find_best(correlation_matrix_spi[[i]])
best_times_list$spei[i,] = find_best(correlation_matrix_spei[[i]])
best_times_list$eddi[i,] = find_best_neg(correlation_matrix_snotel_eddi[[i]])
best_times_list$sedi[i,] = find_best_neg(correlation_matrix_snotel_sedi[[i]])
best_cor_list$spi[i,] = find_best_cor(correlation_matrix_spi[[i]])
best_cor_list$spei[i,] = find_best_cor(correlation_matrix_spei[[i]])
best_cor_list$eddi[i,] = find_best_cor_neg(correlation_matrix_snotel_eddi[[i]])
best_cor_list$sedi[i,] = find_best_cor_neg(correlation_matrix_snotel_sedi[[i]])
#repreat for summer
best_times_list_summer$spi[i,] = find_best(correlation_matrix_summer_snotel_spi[[i]])
best_times_list_summer$spei[i,] = find_best(correlation_matrix_summer_snotel_spei[[i]])
best_times_list_summer$eddi[i,] = find_best_neg(correlation_matrix_summer_snotel_eddi[[i]])
best_times_list_summer$sedi[i,] = find_best_neg(correlation_matrix_summer_snotel_sedi[[i]])
best_cor_list_summer$spi[i,] = find_best_cor(correlation_matrix_summer_snotel_spi[[i]])
best_cor_list_summer$spei[i,] = find_best_cor(correlation_matrix_summer_snotel_spei[[i]])
best_cor_list_summer$eddi[i,] = find_best_cor_neg(correlation_matrix_summer_snotel_eddi[[i]])
best_cor_list_summer$sedi[i,] = find_best_cor_neg(correlation_matrix_summer_snotel_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA))
})
}
# find best correlations and times for mesonet
for(i in 1:length(correlation_matrix_mesonet_spi)){
tryCatch({
best_times_mesonet_list$spi[i,] = find_best_mesonet(correlation_matrix_mesonet_spi[[i]])
best_times_mesonet_list$spei[i,] = find_best_mesonet(correlation_matrix_mesonet_spei[[i]])
best_times_mesonet_list$eddi[i,] = find_best_mesonet_neg(correlation_matrix_mesonet_eddi[[i]])
best_times_mesonet_list$sedi[i,] = find_best_mesonet_neg(correlation_matrix_mesonet_sedi[[i]])
best_cor_mesonet_list$spi[i,] = find_best_mesonet_cor(correlation_matrix_mesonet_spi[[i]])
best_cor_mesonet_list$spei[i,] = find_best_mesonet_cor(correlation_matrix_mesonet_spei[[i]])
best_cor_mesonet_list$eddi[i,] = find_best_mesonet_cor_neg(correlation_matrix_mesonet_eddi[[i]])
best_cor_mesonet_list$sedi[i,] = find_best_mesonet_cor_neg(correlation_matrix_mesonet_sedi[[i]])
#repeat for summer
best_times_mesonet_list_summer$spi[i,] = find_best_mesonet(correlation_matrix_summer_mesonet_spi[[i]])
best_times_mesonet_list_summer$spei[i,] = find_best_mesonet(correlation_matrix_summer_mesonet_spei[[i]])
best_times_mesonet_list_summer$eddi[i,] = find_best_mesonet_neg(correlation_matrix_summer_mesonet_eddi[[i]])
best_times_mesonet_list_summer$sedi[i,] = find_best_mesonet_neg(correlation_matrix_summer_mesonet_sedi[[i]])
best_cor_mesonet_list_summer$spi[i,] = find_best_mesonet_cor(correlation_matrix_summer_mesonet_spi[[i]])
best_cor_mesonet_list_summer$spei[i,] = find_best_mesonet_cor(correlation_matrix_summer_mesonet_spei[[i]])
best_cor_mesonet_list_summer$eddi[i,] = find_best_mesonet_cor_neg(correlation_matrix_summer_mesonet_eddi[[i]])
best_cor_mesonet_list_summer$sedi[i,] = find_best_mesonet_cor_neg(correlation_matrix_summer_mesonet_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA))
})
}
## playing with wet dry data
for(i in 1:length(wet_dry_correlation_matrix_snotel_spi)){
tryCatch({
best_times_list$spi_wet_dry[i,] = find_best_wet_dry(wet_dry_correlation_matrix_snotel_spi[[i]])
best_times_list$spei_wet_dry[i,] = find_best_wet_dry(wet_dry_correlation_matrix_snotel_spei[[i]])
best_times_list$eddi_wet_dry[i,] = find_best_wet_dry_neg(wet_dry_correlation_matrix_snotel_eddi[[i]])
best_times_list$sedi_wet_dry[i,] = find_best_wet_dry_neg(wet_dry_correlation_matrix_snotel_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
})
}
for(i in 1:length(wet_dry_correlation_matrix_mesonet_spi)){
tryCatch({
best_times_mesonet_list$spi_wet_dry[i,] = find_best_wet_dry_mesonet(wet_dry_correlation_matrix_mesonet_spi[[i]])
best_times_mesonet_list$spei_wet_dry[i,] = find_best_wet_dry_mesonet(wet_dry_correlation_matrix_mesonet_spei[[i]])
best_times_mesonet_list$eddi_wet_dry[i,] = find_best_wet_dry_mesonet_neg(wet_dry_correlation_matrix_mesonet_eddi[[i]])
best_times_mesonet_list$sedi_wet_dry[i,] = find_best_wet_dry_mesonet_neg(wet_dry_correlation_matrix_mesonet_sedi[[i]])
},
error = function(e){
return(c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
})
}
# aggregate based on generalized depths
best_times_combined = list()
best_cor_combined = list()
best_times_combined_summer = list()
best_cor_combined_summer = list()
best_times_combined_wet_dry = list()
for(i in 1:4){
best_times_combined[[i]] = data.frame(shallow = c(best_times_list[[i]]$`2in`, best_times_list[[i]]$`4in`,
best_times_mesonet_list[[i]]$`0in`, best_times_mesonet_list[[i]]$`4in`),
middle = c(best_times_list[[i]]$`8in`, best_times_list[[i]]$`20in`,
best_times_mesonet_list[[i]]$`8in`, best_times_mesonet_list[[i]]$`20in`),
deep = c(best_times_list[[i]]$`40in`, best_times_mesonet_list[[i]]$`36in`),
mean = c(best_times_list[[i]]$mean, best_times_mesonet_list[[i]]$mean))
best_cor_combined[[i]] = data.frame(shallow = c(best_cor_list[[i]]$`2in`, best_cor_list[[i]]$`4in`,
best_cor_mesonet_list[[i]]$`0in`, best_cor_mesonet_list[[i]]$`4in`),
middle = c(best_cor_list[[i]]$`8in`, best_cor_list[[i]]$`20in`,
best_cor_mesonet_list[[i]]$`8in`, best_cor_mesonet_list[[i]]$`20in`),
deep = c(best_cor_list[[i]]$`40in`, best_cor_mesonet_list[[i]]$`36in`),
mean = c(best_cor_list[[i]]$mean, best_cor_mesonet_list[[i]]$mean))
# repeat for summer
best_times_combined_summer[[i]] = data.frame(shallow = c(best_times_list_summer[[i]]$`2in`, best_times_list_summer[[i]]$`4in`,
best_times_mesonet_list_summer[[i]]$`0in`, best_times_mesonet_list_summer[[i]]$`4in`),
middle = c(best_times_list_summer[[i]]$`8in`, best_times_list_summer[[i]]$`20in`,
best_times_mesonet_list_summer[[i]]$`8in`, best_times_mesonet_list_summer[[i]]$`20in`),
deep = c(best_times_list_summer[[i]]$`40in`, best_times_mesonet_list_summer[[i]]$`36in`),
mean = c(best_times_list_summer[[i]]$mean, best_times_mesonet_list_summer[[i]]$mean))
best_cor_combined_summer[[i]] = data.frame(shallow = c(best_cor_list_summer[[i]]$`2in`, best_cor_list_summer[[i]]$`4in`,
best_cor_mesonet_list_summer[[i]]$`0in`, best_cor_mesonet_list_summer[[i]]$`4in`),
middle = c(best_cor_list_summer[[i]]$`8in`, best_cor_list_summer[[i]]$`20in`,
best_cor_mesonet_list_summer[[i]]$`8in`, best_cor_mesonet_list_summer[[i]]$`20in`),
deep = c(best_cor_list_summer[[i]]$`40in`, best_cor_mesonet_list_summer[[i]]$`36in`),
mean = c(best_cor_list_summer[[i]]$mean, best_cor_mesonet_list_summer[[i]]$mean))
}
for(i in 5:8){
best_times_combined_wet_dry[[i]] = data.frame(
#wet
shallow_wet = c(best_times_list[[i]]$`wet_2in`, best_times_list[[i]]$`wet_4in`,
best_times_mesonet_list[[i]]$`wet_0in`, best_times_mesonet_list[[i]]$`wet_4in`),
middle_wet = c(best_times_list[[i]]$`wet_8in`, best_times_list[[i]]$`wet_20in`,
best_times_mesonet_list[[i]]$`wet_8in`, best_times_mesonet_list[[i]]$`wet_20in`),
deep_wet = c(best_times_list[[i]]$`wet_40in`, best_times_mesonet_list[[i]]$`wet_36in`),
mean_wet = c(best_times_list[[i]]$wet_mean, best_times_mesonet_list[[i]]$wet_mean),
#dry
shallow_dry = c(best_times_list[[i]]$`dry_2in`, best_times_list[[i]]$`dry_4in`,
best_times_mesonet_list[[i]]$`dry_0in`, best_times_mesonet_list[[i]]$`dry_4in`),
middle_dry = c(best_times_list[[i]]$`dry_8in`, best_times_list[[i]]$`dry_20in`,
best_times_mesonet_list[[i]]$`dry_8in`, best_times_mesonet_list[[i]]$`dry_20in`),
deep_dry = c(best_times_list[[i]]$`dry_40in`, best_times_mesonet_list[[i]]$`dry_36in`),
mean_dry = c(best_times_list[[i]]$dry_mean, best_times_mesonet_list[[i]]$dry_mean))
}
for(i in c(1,1,1,1)){
best_times_combined_wet_dry[[i]] = NULL
}
# rename and organize
names(best_times_combined) = c("spi","spei","eddi","sedi")
names(best_cor_combined) = c("spi","spei","eddi","sedi")
names(best_times_combined_wet_dry) = c("spi","spei","eddi","sedi")
depths = c("2 - 4in","8 - 20in", "36 - 40in", "Mean")
# plot density graphs by depth
plot = list()
for(i in 1:4){
best_cor_ggplot = c(round(median(best_cor_combined$spi[,i], na.rm = T),2),
round(median(best_cor_combined$spei[,i], na.rm = T),2),
round(median(best_cor_combined$eddi[,i], na.rm = T),2),
round(median(best_cor_combined$sedi[,i], na.rm = T),2))
names = c("SPI: r = ","SPEI: r = ","EDDI: r = ","SEDI: r = ")
names_short = c("SPI","SPEI","EDDI","SEDI")
data = rbind(extract_density(best_times_combined$spi[,i], "SPI"),
extract_density(best_times_combined$spei[,i], "SPEI"),
extract_density(best_times_combined$eddi[,i], "EDDI"),
extract_density(best_times_combined$sedi[,i], "SEDI"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
plot[[i]] = ggplot(data = data, aes(x = x, y=y, color = name))+
geom_line()+
ggtitle(paste0("Soil Moisture Depth = ", depths[i]))+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 14)+
xlim(0,600)+
theme(legend.position = c(0.75, 0.75))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = names_short,
values = c("blue", "black", "orange", "red"),
labels = paste0(names, best_cor_ggplot),
name = "Drought Metric")
}
plot_grid = cowplot::plot_grid(plot[[4]],plot[[1]],plot[[2]],plot[[3]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/correlation_density_unfrozen.png",
plot_grid, width = 10, height = 9, units = "in", dpi = 400)
# plot density graphs by metric
depth_plot = list()
names_short = c("SPI","SPEI","EDDI","SEDI")
for(i in 1:length(names_short)){
best_cor_ggplot = c(round(median(best_cor_combined[[i]]$mean, na.rm = T),2),
round(median(best_cor_combined[[i]]$shallow, na.rm = T),2),
round(median(best_cor_combined[[i]]$middle, na.rm = T),2),
round(median(best_cor_combined[[i]]$deep, na.rm = T),2))
data = rbind(extract_density(best_times_combined[[i]]$mean, "Mean"),
extract_density(best_times_combined[[i]]$shallow, "Shallow"),
extract_density(best_times_combined[[i]]$middle, "Middle"),
extract_density(best_times_combined[[i]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
depth_plot[[i]] = ggplot(data = data, aes(x = x, y = y, color = name))+
geom_line()+
ggtitle(names_short[i])+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 14)+
xlim(0,730)+
theme(legend.position = c(0.75, 0.75))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = c("Mean", "Shallow", "Middle", "Deep"),
values = c("black", "forestgreen", "blue", "purple"),
labels = paste0(c("Mean: r = ", "Shallow: r = ", "Middle: r = ", "Deep: r = "),
best_cor_ggplot),
name = "Probe Depth")
}
plot_grid_depth = cowplot::plot_grid(depth_plot[[1]],depth_plot[[2]],depth_plot[[3]],depth_plot[[4]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/depth_density_unfrozen.png",
plot_grid_depth, width = 10, height = 9, units = "in", dpi = 400)
### repeat for summer
# plot density graphs by metric
depth_plot_summer = list()
names_short = c("SPI","SPEI","EDDI","SEDI")
for(i in 1:length(names_short)){
best_cor_ggplot = c(round(median(best_cor_combined_summer[[i]]$mean, na.rm = T),2),
round(median(best_cor_combined_summer[[i]]$shallow, na.rm = T),2),
round(median(best_cor_combined_summer[[i]]$middle, na.rm = T),2),
round(median(best_cor_combined_summer[[i]]$deep, na.rm = T),2))
data = rbind(extract_density(best_times_combined_summer[[i]]$mean, "Mean"),
extract_density(best_times_combined_summer[[i]]$shallow, "Shallow"),
extract_density(best_times_combined_summer[[i]]$middle, "Middle"),
extract_density(best_times_combined_summer[[i]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
depth_plot_summer[[i]] = ggplot(data = data, aes(x = x, y = y, color = name))+
geom_line()+
ggtitle(paste0(names_short[i], " (May - October)"))+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 14)+
xlim(0,730)+
theme(legend.position = c(0.75, 0.75))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = c("Mean", "Shallow", "Middle", "Deep"),
values = c("black", "forestgreen", "blue", "purple"),
labels = paste0(c("Mean: r = ", "Shallow: r = ", "Middle: r = ", "Deep: r = "),
best_cor_ggplot),
name = "Probe Depth")
}
plot_grid_depth = cowplot::plot_grid(depth_plot_summer[[1]],depth_plot_summer[[2]],depth_plot_summer[[3]],depth_plot_summer[[4]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/depth_density_summer_unfrozen.png",
plot_grid_depth, width = 10, height = 9, units = "in", dpi = 400)
################# wet dry plot ##########################################
wet_dry_plot = list()
# plot density graphs by metric
names_short = c("SPI","SPEI","EDDI","SEDI")
for(i in 1:length(names_short)){
# best_cor_ggplot = c(round(median(best_cor_combined[[i]]$mean, na.rm = T),2),
# round(median(best_cor_combined[[i]]$shallow, na.rm = T),2),
# round(median(best_cor_combined[[i]]$middle, na.rm = T),2),
# round(median(best_cor_combined[[i]]$deep, na.rm = T),2))
data = rbind(extract_density_linetype(best_times_combined_wet_dry[[i]]$mean_wet, "Mean", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$shallow_wet, "Shallow", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$middle_wet, "Middle", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$deep_wet, "Deep", "Wetting"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$mean_dry, "Mean", "Drying"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$shallow_dry, "Shallow", "Drying"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$middle_dry, "Middle", "Drying"),
extract_density_linetype(best_times_combined_wet_dry[[i]]$deep_dry, "Deep", "Drying"))
best_density = data %>%
group_by(name, linetype) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)
wet_dry_plot[[i]] = ggplot(data = data, aes(x = x, y = y, color = name, linetype = linetype))+
geom_line()+
ggtitle(names_short[i])+
xlab("Timescale (Days)")+
ylab("Density")+
theme_bw(base_size = 12)+
xlim(0,600)+
theme(legend.position = c(0.85, 0.65))+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
ggrepel::geom_text_repel(data = best_times, aes(x = x, y=y, color = name, label = mround(x, 5)))+
geom_point(data = best_times, aes(x = x, y=y, color = name))+
scale_color_manual(breaks = c("Mean", "Shallow", "Middle", "Deep"),
values = c("black", "forestgreen", "blue", "purple"))+
labs(color="Depth", linetype=NULL)
}
plot_grid_wet_dry = cowplot::plot_grid(wet_dry_plot[[1]],wet_dry_plot[[2]],wet_dry_plot[[3]],wet_dry_plot[[4]], nrow = 2)
ggsave("./validation/soil_moisture/plots/summary/wet_dry_depth_plot.png",
plot_grid_wet_dry, width = 10, height = 9, units = "in", dpi = 400)
################# Monthly Post Processing and plots ########################
library(ggplot2)
library(scales)
index_names = c("SPI","SPEI","EDDI","SEDI")
monthly_data_snotel = list(monthly_correlation_matrix_snotel_spi, monthly_correlation_matrix_snotel_spei,
monthly_correlation_matrix_snotel_eddi, monthly_correlation_matrix_snotel_sedi)
monthly_data_mesonet = list(monthly_correlation_matrix_mesonet_spi, monthly_correlation_matrix_mesonet_spei,
monthly_correlation_matrix_mesonet_eddi, monthly_correlation_matrix_mesonet_sedi)
for(d in 1:length(monthly_data_snotel)){
#for(d in 1){
data = rbind(extract_density(best_times_combined[[d]]$mean, "Mean"),
extract_density(best_times_combined[[d]]$shallow, "Shallow"),
extract_density(best_times_combined[[d]]$middle, "Middle"),
extract_density(best_times_combined[[d]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)%>%
mutate(x = mround(x,5))
index = vector()
for(i in 1:4){
index[i] = which(best_times$x[i] == c(seq(5,730,5)))
}
#extract snotel
for(i in 1:length(monthly_data_snotel[[d]])){
mean_temp = monthly_data_snotel[[d]][[i]][[index[1]]]$mean_soil_moisture
shallow_temp = rowMeans(data.frame(in_2 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..2in..pct..Start.of.Day.Values,
in_4 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..4in..pct..Start.of.Day.Values),
na.rm = TRUE)
middle_temp = rowMeans(data.frame(in_8 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..8in..pct..Start.of.Day.Values,
in_20 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..20in..pct..Start.of.Day.Values),
na.rm = TRUE)
deep_temp = monthly_data_snotel[[d]][[i]][[index[4]]]$Soil.Moisture.Percent..40in..pct..Start.of.Day.Values
if(i == 1){
mean_full = data.frame(mean_temp)
shallow_full = data.frame(shallow_temp)
middle_full = data.frame(middle_temp)
deep_full = data.frame(deep_temp)
}
else{
mean_full = cbind(mean_full, mean_temp)
shallow_full = cbind(shallow_full, shallow_temp)
middle_full = cbind(middle_full, middle_temp)
deep_full = cbind(deep_full, deep_temp)
}
}
# extract mesonet
for(i in 1:length(monthly_data_mesonet[[d]])){
mean_temp = monthly_data_mesonet[[d]][[i]][[index[1]]]$mean_soil_moisture
mean_full = cbind(mean_full, mean_temp)
#shallow
shallow_temp = rowMeans(data.frame(in_0 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc00,
in_4 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc04),na.rm = TRUE)
shallow_full = cbind(shallow_full, shallow_temp)
#middle
middle_temp = rowMeans(data.frame(in_8 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc08,
in_20 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc20),na.rm = TRUE)
middle_full = cbind(middle_full, middle_temp)
#deep
deep_temp = monthly_data_mesonet[[d]][[i]][[index[4]]]$soilwc36
deep_full = cbind(deep_full, deep_temp)
}
summary = data.frame(median = apply(mean_full, 1, median, na.rm=TRUE),
upper = apply(mean_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(mean_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_shallow = data.frame(median = apply(shallow_full, 1, median, na.rm=TRUE),
upper = apply(shallow_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(shallow_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_middle = data.frame(median = apply(middle_full, 1, median, na.rm=TRUE),
upper = apply(middle_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(middle_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_deep = data.frame(median = apply(deep_full, 1, median, na.rm=TRUE),
upper = apply(deep_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(deep_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
find_summer_stat = function(x){
median = x %>%
mutate(month = c(1:12)) %>%
dplyr::filter(month > 4 & month < 11)%>%
summarise(median(median))
median = median$`median(median)`
return(median)
}
summary_list = list(summary, summary_shallow, summary_middle, summary_deep)
plot_monthly = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)*.7, height = 0.05, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)*.5, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plot_monthly_eddi = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)+0.1, height = 0.03, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)+0.15, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plots = list()
datasets = list(summary, summary_shallow, summary_middle, summary_deep)
colors = c("black", "forestgreen", "blue", "purple")
depths = c("Mean", "Shallow", "Middle", "Deep")
time_scale = c(seq(5,730,5)[index])
for(i in 1:4){
plots[[i]] = plot_monthly(datasets[[i]], colors[i], depths[i], time_scale[i], index_names[d], summary_list[[i]])
}
plot_grid_monthly = cowplot::plot_grid(plots[[1]],plots[[2]],plots[[3]],plots[[4]], nrow = 2)
plot_final = cowplot::plot_grid(depth_plot[[d]], plot_grid_monthly , nrow = 1)
ggsave(paste0("./validation/soil_moisture/plots/summary/plot_grid_monthly_",index_names[d],".png"),
plot_final, width = 12, height = 5, units = "in", dpi = 400)
}
#repeate for summer
library(ggplot2)
library(scales)
library(matrixStats)
index_names = c("SPI","SPEI","EDDI","SEDI")
monthly_data_snotel = list(monthly_correlation_matrix_snotel_spi, monthly_correlation_matrix_snotel_spei,
monthly_correlation_matrix_snotel_eddi, monthly_correlation_matrix_snotel_sedi)
monthly_data_mesonet = list(monthly_correlation_matrix_mesonet_spi, monthly_correlation_matrix_mesonet_spei,
monthly_correlation_matrix_mesonet_eddi, monthly_correlation_matrix_mesonet_sedi)
for(d in 1:length(monthly_data_snotel)){
#for(d in 1){
data = rbind(extract_density(best_times_combined_summer[[d]]$mean, "Mean"),
extract_density(best_times_combined_summer[[d]]$shallow, "Shallow"),
extract_density(best_times_combined_summer[[d]]$middle, "Middle"),
extract_density(best_times_combined_summer[[d]]$deep, "Deep"))
best_density = data %>%
group_by(name) %>%
select(y, name) %>%
summarise_each(max)
best_times = data %>%
dplyr::filter(y %in% best_density$y)%>%
mutate(x = mround(x,5))
index = vector()
for(i in 1:4){
index[i] = which(best_times$x[i] == c(seq(5,730,5)))
}
#extract snotel
for(i in 1:length(monthly_data_snotel[[d]])){
mean_temp = monthly_data_snotel[[d]][[i]][[index[1]]]$mean_soil_moisture
shallow_temp = tryCatch({rowMedians(as.matrix(data.frame(in_2 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..2in..pct..Start.of.Day.Values,
in_4 = monthly_data_snotel[[d]][[i]][[index[2]]]$Soil.Moisture.Percent..4in..pct..Start.of.Day.Values)), na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
middle_temp = tryCatch({
rowMedians(as.matrix(data.frame(in_8 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..8in..pct..Start.of.Day.Values,
in_20 = monthly_data_snotel[[d]][[i]][[index[3]]]$Soil.Moisture.Percent..20in..pct..Start.of.Day.Values)), na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
deep_temp = monthly_data_snotel[[d]][[i]][[index[4]]]$Soil.Moisture.Percent..40in..pct..Start.of.Day.Values
if(i == 1){
mean_full = data.frame(mean_temp)
shallow_full = data.frame(shallow_temp)
middle_full = data.frame(middle_temp)
deep_full = data.frame(deep_temp)
}
else{
mean_full = cbind(mean_full, mean_temp)
shallow_full = cbind(shallow_full, shallow_temp)
middle_full = cbind(middle_full, middle_temp)
deep_full = cbind(deep_full, deep_temp)
}
}
# extract mesonet
for(i in 1:length(monthly_data_mesonet[[d]])){
mean_temp = monthly_data_mesonet[[d]][[i]][[index[1]]]$mean_soil_moisture
mean_full = cbind(mean_full, mean_temp)
#shallow
shallow_temp = tryCatch({rowMedians(as.matrix(data.frame(in_0 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc00,
in_4 = monthly_data_mesonet[[d]][[i]][[index[2]]]$soilwc04)),na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
shallow_full = cbind(shallow_full, shallow_temp)
#middle
middle_temp = tryCatch({rowMedians(as.matrix(data.frame(in_8 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc08,
in_20 = monthly_data_mesonet[[d]][[i]][[index[3]]]$soilwc20)),na.rm = TRUE)
}, error=function(e) {
return(rep(NA, 12))
})
middle_full = cbind(middle_full, middle_temp)
#deep
deep_temp = monthly_data_mesonet[[d]][[i]][[index[4]]]$soilwc36
deep_full = cbind(deep_full, deep_temp)
}
summary = data.frame(median = apply(mean_full, 1, median, na.rm=TRUE),
upper = apply(mean_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(mean_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_shallow = data.frame(median = apply(shallow_full, 1, median, na.rm=TRUE),
upper = apply(shallow_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(shallow_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_middle = data.frame(median = apply(middle_full, 1, median, na.rm=TRUE),
upper = apply(middle_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(middle_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
summary_deep = data.frame(median = apply(deep_full, 1, median, na.rm=TRUE),
upper = apply(deep_full, 1, quantile, 0.75, na.rm=TRUE),
lower = apply(deep_full, 1, quantile, 0.25, na.rm=TRUE),
time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"))
find_summer_stat = function(x){
median = x %>%
mutate(month = c(1:12)) %>%
dplyr::filter(month > 4 & month < 11)%>%
summarise(median(median))
median = median$`median(median)`
return(median)
}
summary_list = list(summary, summary_shallow, summary_middle, summary_deep)
plot_monthly = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)*.7, height = 0.05, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)*.5, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plot_monthly_eddi = function(data1, color1, depth, time_scale, name, summary){
plot = ggplot() +
geom_ribbon(data = data1, aes(x = time, ymin = lower, ymax = upper), alpha = 0.2, fill = color1)+
geom_line(data = data1, aes(x = time, y = median), color = color1)+
theme_bw(base_size = 12)+
theme(plot.title = element_text(hjust = 0.5))+
ylab("Correlation (r)")+
ggtitle(paste0(name," [",time_scale," day] ~ Soil Moisture ", "[", depth, "] "))+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
theme(axis.title.x=element_blank(),
plot.title = element_text(size = 10, face = "bold")) +
geom_errorbarh(data = summary, aes(xmin = time[5], xmax = time[10],
y = find_summer_stat(summary)+0.1, height = 0.03, x = NULL))+
annotate(geom = "text", y = find_summer_stat(summary)+0.15, x = as.POSIXct("2018-07-15 00:00",
format = "%Y-%m-%d %H:%M"),
label = paste0("r = ", round(find_summer_stat(summary),2)))
return(plot)
}
plots = list()
datasets = list(summary, summary_shallow, summary_middle, summary_deep)
colors = c("black", "forestgreen", "blue", "purple")
depths = c("Mean", "Shallow", "Middle", "Deep")
time_scale = c(seq(5,730,5)[index])
for(i in 1:4){
plots[[i]] = plot_monthly(datasets[[i]], colors[i], depths[i], time_scale[i], index_names[d], summary_list[[i]])
}
plot_grid_monthly = cowplot::plot_grid(plots[[1]],plots[[2]],plots[[3]],plots[[4]], nrow = 2)
plot_final = cowplot::plot_grid(depth_plot_summer[[d]], plot_grid_monthly , nrow = 1)
ggsave(paste0("./validation/soil_moisture/plots/summary/plot_grid_monthly_summer_",index_names[d],".png"),
plot_final, width = 12, height = 5, units = "in", dpi = 400)
}
################### site map #######################
library(dplyr)
#read in geospatial data
station_data = read.csv("~/drought_indicators_data/mesonet/station_data_clean.csv")
station_data$X = NULL
snotel = read.csv("./validation/soil_moisture/snotel_data/nrcs_soil_moisture.csv")
snotel_cropped = snotel %>%
dplyr::select(site_name, latitude, longitude) %>%
rename(station_key = site_name)
snotel_cropped$network = "NRCS"
master_list = rbind(snotel_cropped,station_data)
master_times = cbind(master_list,
mean_time_spi = c(best_times_list$spi$mean, best_times_mesonet_list$spi$mean),
mean_time_spei = c(best_times_list$spei$mean, best_times_mesonet_list$spei$mean),
mean_time_eddi = c(best_times_list$eddi$mean, best_times_mesonet_list$eddi$mean),
mean_time_sedi = c(best_times_list$sedi$mean, best_times_mesonet_list$sedi$mean),
mean_cor_spi = c(best_cor_list$spi$mean, best_cor_mesonet_list$spi$mean),
mean_cor_spei = c(best_cor_list$spei$mean, best_cor_mesonet_list$spei$mean),
mean_cor_eddi = c(best_cor_list$eddi$mean, best_cor_mesonet_list$eddi$mean),
mean_cor_sedi = c(best_cor_list$sedi$mean, best_cor_mesonet_list$sedi$mean))
master_times_summer = cbind(master_list,
mean_time_spi = c(best_times_list_summer$spi$mean, best_times_mesonet_list_summer$spi$mean),
mean_time_spei = c(best_times_list_summer$spei$mean, best_times_mesonet_list_summer$spei$mean),
mean_time_eddi = c(best_times_list_summer$eddi$mean, best_times_mesonet_list_summer$eddi$mean),
mean_time_sedi = c(best_times_list_summer$sedi$mean, best_times_mesonet_list_summer$sedi$mean),
mean_cor_spi = c(best_cor_list_summer$spi$mean, best_cor_mesonet_list_summer$spi$mean),
mean_cor_spei = c(best_cor_list_summer$spei$mean, best_cor_mesonet_list_summer$spei$mean),
mean_cor_eddi = c(best_cor_list_summer$eddi$mean, best_cor_mesonet_list_summer$eddi$mean),
mean_cor_sedi = c(best_cor_list_summer$sedi$mean, best_cor_mesonet_list_summer$sedi$mean))
#write.csv(master_times, "./validation/soil_moisture/summary_data/geospatial_with_best.csv")
states = sf::st_read("/home/zhoylman/drought_indicators/shp_kml/states.shp") %>%
dplyr::filter(STATE_NAME != "Alaska" & STATE_NAME != "Hawaii")
states_union = sf::st_read("/home/zhoylman/drought_indicators/shp_kml/states.shp") %>%
dplyr::filter(STATE_NAME != "Alaska" & STATE_NAME != "Hawaii") %>%
st_union()
static_map = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_point(data = master_times, aes(x = longitude, y = latitude), fill = "blue",
color = "black", shape = 21, alpha = 0.5, size = 2)+
xlab("")+
ylab("")
static_map
ggsave(paste0("./validation/soil_moisture/plots/summary/site_map.png"),
static_map, width = 10, height = 5, units = "in", dpi = 400)
## example spei map
spei_map = raster::raster("/home/zhoylman/drought_indicators_data/spei_20190901_60_day.tif") %>%
rasterToPoints()%>%
as.data.frame() %>%
rename(spei = 3)
color_ramp = c("#8b0000", "#ff0000", "#ffffff", "#0000ff", "#00008b")
static_spei_map = ggplot() +
geom_sf(data = states_union, fill = "transparent", size = 1.5)+
geom_tile(data = spei_map, aes(x, y, fill = spei)) +
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
scale_fill_gradientn("SPEI", colours = color_ramp, limits = c(-3,3))+
ggtitle(paste0("Standardized Precipitation Evapotranspiration Index\n 9-1-2019 (60 Day Timescale)"))+
xlab("")+
ylab("")+
theme(plot.title = element_text(hjust = 0.5))
static_spei_map
ggsave(paste0("./validation/soil_moisture/plots/summary/spei_map.png"),
static_spei_map, width = 10, height = 5, units = "in", dpi = 420)
rbPal <- (colorRampPalette(c("darkblue", "blue", "lightblue", "yellow", "orange", "red", "darkred")))
index_names_lower = c("spi", "spei", "eddi", "sedi")
library(cowplot)
#best times saptial
for(i in 1:4){
data_select = master_times %>%
dplyr::select(longitude, latitude, paste0("mean_time_",index_names_lower[i]))%>%
na.omit()
static_map_metric = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))+
geom_point(data = data_select , aes(x = longitude, y = latitude,
fill = get(paste0("mean_time_",index_names_lower[i]))),
color = "black", shape = 21, alpha = 1, size = 2)+
xlab("")+
ylab("")+
ggtitle(paste0("Optimal Timescale (", index_names[i], ")"))+
scale_fill_gradientn("",colours=(rbPal(100)), guide = F)
#function to draw manual ramp
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
dummy_plot = ggplot(data = data_select) +
geom_tile(aes(y=latitude, x=longitude, fill = get(paste0("mean_time_",index_names_lower[i]))), alpha = 1)+
scale_fill_gradientn("Days",colours=(rbPal(100)))
#draw ramp
legend <- g_legend(dummy_plot)
#plot final plot
static_map_metric_inset =
ggdraw() +
draw_plot(static_map_metric) +
draw_plot(legend, x = .8, y = .2, width = .35, height = .35)
ggsave(paste0("./validation/soil_moisture/plots/summary/spatial_",index_names_lower[i],"_map.png"),
static_map_metric_inset, width = 10, height = 5, units = "in", dpi = 400)
}
#best times saptial (Summer)
for(i in 1:4){
data_select = master_times_summer %>%
dplyr::select(longitude, latitude, paste0("mean_time_",index_names_lower[i]))%>%
na.omit()
static_map_metric = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
plot.title = element_text(hjust = 0.5))+
geom_point(data = data_select , aes(x = longitude, y = latitude,
fill = get(paste0("mean_time_",index_names_lower[i]))),
color = "black", shape = 21, alpha = 1, size = 2)+
xlab("")+
ylab("")+
ggtitle(paste0("May - October Optimal Timescale (", index_names[i], ")"))+
scale_fill_gradientn("",colours=(rbPal(100)), guide = F)
#function to draw manual ramp
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
dummy_plot = ggplot(data = data_select) +
geom_tile(aes(y=latitude, x=longitude, fill = get(paste0("mean_time_",index_names_lower[i]))), alpha = 1)+
scale_fill_gradientn("Days",colours=(rbPal(100)))
#draw ramp
legend <- g_legend(dummy_plot)
#plot final plot
static_map_metric_inset =
ggdraw() +
draw_plot(static_map_metric) +
draw_plot(legend, x = .8, y = .2, width = .35, height = .35)
ggsave(paste0("./validation/soil_moisture/plots/summary/spatial_",index_names_lower[i],"_map_summer.png"),
static_map_metric_inset, width = 10, height = 5, units = "in", dpi = 400)
}
## montly all timescales
library(ggplot2)
library(scales)
library(matrixStats)
index_names = c("SPI","SPEI","EDDI","SEDI")
monthly_data_snotel = list(monthly_correlation_matrix_snotel_spi, monthly_correlation_matrix_snotel_spei,
monthly_correlation_matrix_snotel_eddi, monthly_correlation_matrix_snotel_sedi)
monthly_data_mesonet = list(monthly_correlation_matrix_mesonet_spi, monthly_correlation_matrix_mesonet_spei,
monthly_correlation_matrix_mesonet_eddi, monthly_correlation_matrix_mesonet_sedi)
# d for metrcs
#for(d in 1:length(monthly_data_snotel)){
plot_monthy = function(d){
timescale_line_plot = list()
monthly_ls = list()
# i for sites
for(t in 1:146){
for(i in 1:length(monthly_data_snotel[[d]])){
# t for timescales
mean_temp = monthly_data_snotel[[d]][[i]][[t]]$mean_soil_moisture
if(i == 1){
mean_full = data.frame(mean_temp)
}
else{
mean_full = cbind(mean_full, mean_temp)
}
}
for(i in 1:length(monthly_data_mesonet[[d]])){
# t for timescales
mean_temp_mesonet = monthly_data_mesonet[[d]][[i]][[t]]$mean_soil_moisture
if(i == 1){
mean_full_mesonet = data.frame(mean_temp_mesonet)
}
else{
mean_full_mesonet = cbind(mean_full_mesonet, mean_temp)
}
}
full = cbind(mean_full, mean_full_mesonet)
summary = data.frame(rowMedians(as.matrix(full), na.rm = T))
colnames(summary) = "median"
monthly_ls[[t]] = summary
}
monthly_df = as.data.frame(lapply(monthly_ls, cbind))
best_monthly_time = function(x, direction){
if(direction == "max"){
return(c(
seq(5,730,5)[which(monthly_df[x,] == max(monthly_df[x,]))],
max(monthly_df[x,])
))
}
if(direction == "min"){
return(c(
seq(5,730,5)[which(monthly_df[x,] == min(monthly_df[x,]))],
min(monthly_df[x,])
))
}
}
best_times = data.frame()
if(d < 3){
for(i in 1:12){best_times[i,1:2] = best_monthly_time(i, "max")}
}
if(d >= 3){
for(i in 1:12){best_times[i,1:2] = best_monthly_time(i, "min")}
}
best_times$time = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M")
#plot results
colfunc <- colorRampPalette(c("darkblue", "blue", "lightblue", "yellow", "orange", "red", "darkred"))
cols = colfunc(146)
#y lim definitions
if(d == 1){
ylim_vals = c(-0.1,0.8)
yjust = 0.05
}
if(d == 2){
ylim_vals = c(-0.1,0.8)
yjust = 0.05
}
if(d == 3){
ylim_vals = c(-0.8,0.1)
yjust = -0.05
}
if(d == 4){
ylim_vals = c(-0.8,0.1)
yjust = -0.05
}
timescale_line_plot = ggplot()+
geom_line(data = NULL, aes(x = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"), y = monthly_df[,1]), color = cols[1]) +
theme_bw(base_size = 20) +
ylab("Correlation (r)")+
xlab("Month")+
ggtitle(index_names[d])+
scale_x_datetime(labels = date_format("%b"),
date_breaks = "2 month")+
ylim(ylim_vals)+
theme(plot.title = element_text(hjust = 0.5))+
geom_text(data = best_times, aes(x = time, y = V2+yjust, label = V1))
for(g in 2:length(monthly_ls)){
temp_data = data.frame(x = as.POSIXct(paste0(as.Date(paste0(1:12,"-01-2018"), format("%m-%d-%Y"))," 00:00"),
format = "%Y-%m-%d %H:%M"),
y = monthly_df[,g])
timescale_line_plot = timescale_line_plot +
geom_line(data = temp_data, aes(x = x, y = y), color = cols[g])
}
return(timescale_line_plot)
}
colfunc <- colorRampPalette(c("darkblue", "blue", "lightblue", "yellow", "orange", "red", "darkred"))
#function to draw manual ramp
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
legend
}
dummy_plot = ggplot(data = data.frame(x = seq(1:146), y = seq(1:146), z = seq(5,730, 5))) +
geom_tile(aes(y=y, x=x, fill = z), alpha = 1)+
scale_fill_gradientn("Days",colours=(colfunc(100)))
#draw ramp
legend <- g_legend(dummy_plot)
plot_grid_timescales = cowplot::plot_grid(plot_monthy(1),plot_monthy(2), NULL,
plot_monthy(3),plot_monthy(4), NULL,
nrow = 2, rel_widths = c(1, 1, 0.1,
1, 1, 0.1))
library(cowplot)
plot_grid_timescales_inset =
ggdraw() +
draw_plot(plot_grid_timescales) +
draw_plot(legend, x = .95, y = -0.05, width = .4, height = .4)
ggsave(paste0("./validation/soil_moisture/plots/summary/timescale_lines.png"),
plot_grid_timescales_inset, width = 14, height = 10, units = "in", dpi = 300)
# observed vs modeled
load('/home/zhoylman/drought_indicators_data/correlation_matrix/observed_modeled_cor.RData')
load("/home/zhoylman/drought_indicators_data/correlation_matrix/observed_modeled_cpc_cor.RData")
data = observed_vs_modeled %>%
dplyr::select(sm_gamma)%>%
tidyr::drop_na()
data2 = observed_vs_modeled_cpc %>%
dplyr::select(sm_gamma)%>%
tidyr::drop_na()
data_density = density(data$sm_gamma)
data_density$name = "Topofire"
data_density_2 = density(data2$sm_gamma)
data_density_2$name = "CPC"
master_times_summer_no_na = master_times_summer %>%
tidyr::drop_na()
density_list = list()
drought_names = c("SPI", "SPEI", 'EDDI', "SEDI")
for(i in 1:4){
density_list[[i]] = density(master_times_summer_no_na[,i+8])
density_list[[i]]$name = drought_names[i]
}
density_data = data.frame(x = c(data_density$x, data_density_2$x, density_list[[1]]$x,
density_list[[2]]$x, density_list[[3]]$x, density_list[[4]]$x),
y = c(data_density$y, data_density_2$y, density_list[[1]]$y,
density_list[[2]]$y, density_list[[3]]$y, density_list[[4]]$y),
name = c(rep("Topofire", 512), rep("CPC", 512), rep(density_list[[1]]$name, 512),
rep(density_list[[2]]$name, 512), rep(density_list[[3]]$name, 512), rep(density_list[[4]]$name, 512)))
plot = ggplot(data = density_data, aes(x = x, y=y, color = name))+
geom_line()+
ggtitle("Soil Moisture Correlations")+
xlab("Correlation (r)")+
ylab("Density")+
theme_bw(base_size = 12)+
theme(legend.background = element_rect(color = 'black', fill = 'white', linetype='solid'),
plot.title = element_text(hjust = 0.5))+
xlim(-1, 1)+
scale_color_manual(values=c("red", "purple", "green", "blue", "#E69F00", "black"),
limits = c(drought_names, "CPC", "Topofire"), name = "Predictor")
plot
ggsave(paste0("./validation/soil_moisture/plots/summary/correlation_distrobution_all.png"),
plot, width = 8, height = 5, units = "in", dpi = 300)
master_list_modeled_observed = rbind(station_data, snotel_cropped)
master_list_modeled_observed$r = observed_vs_modeled$sm_gamma
master_list_modeled_observed = master_list_modeled_observed %>%
tidyr::drop_na()
observed_vs_modeled_spatial = ggplot() +
geom_sf(data = states, fill = "transparent")+
theme_bw(base_size = 16)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_point(data = master_list_modeled_observed, aes(x = longitude, y = latitude, fill = r),
color = 'black', shape = 21, alpha = 0.8, size = 2)+
xlab("")+
ylab("")+
scale_fill_gradientn("",colours=rev(rbPal(100)))+
ggtitle(paste0("Observed ~ Modeled Soil Moisture Correlation (r)"))+
theme(plot.title = element_text(hjust = 0.5),
legend.position = c(0.92,0.35))
observed_vs_modeled_spatial
ggsave(paste0("./validation/soil_moisture/plots/summary/observed_vs_modeled_spatial.png"),
observed_vs_modeled_spatial, width = 10, height = 5, units = "in", dpi = 400)
|
#' app UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd
#'
#' @importFrom shiny NS tagList
mod_app_ui <- function(id) {
ns <- NS(id)
dashboard_header <- bs4Dash::dashboardHeader(
title = "COVID-19 in Canada",
fixed = TRUE,
border = FALSE
)
dashboard_sidebar <- bs4Dash::dashboardSidebar(
mod_select_province_ui(
id = ns("select_province")
),
bs4Dash::sidebarMenu(
tab_item_overview(),
tab_item_comparisons(),
tab_item_maps(),
tab_item_vaccines(),
tab_item_cases(),
tab_item_mortality(),
tab_item_recovered(),
tab_item_testing(),
tab_item_about()
)
)
dashboard_body <- bs4Dash::dashboardBody(
fresh::use_googlefont("Lato"),
bs4Dash::tabItems(
mod_tab_overview_ui(id = ns("overview")),
mod_tab_comparisons_ui(id = ns("comparisons")),
mod_tab_maps_ui(id = ns("maps")),
mod_tab_vaccines_ui(id = ns("vaccines")),
mod_tab_cases_ui(id = ns("cases")),
mod_tab_mortality_ui(id = ns("mortality")),
mod_tab_recovered_ui(id = ns("recovered")),
mod_tab_testing_ui(id = ns("testing")),
mod_tab_about_ui(id = ns("about"))
)
)
bs4Dash::dashboardPage(
freshTheme = fresh_theme(),
header = dashboard_header,
sidebar = dashboard_sidebar,
body = dashboard_body,
title = "COVID-19 in Canada",
preloader = preloader_spinner(),
fullscreen = TRUE,
scrollToTop = TRUE,
dark = TRUE
)
}
#' app Server Functions
#'
#' @noRd
mod_app_server <- function(
id,
.daily_canada_data,
.daily_province_data,
.update_time,
.dark_mode
) {
moduleServer(id, function(input, output, session) {
api_data <- get_api_data()
daily_province_data <- pluck(
api_data,
"daily_province_data"
)
daily_canada_data <- pluck(
api_data,
"daily_canada_data"
)
update_time <- pluck(
api_data,
"update_time"
)
province <- mod_select_province_server(
id = "select_province",
.daily_province_data = daily_province_data
)
daily_data_filtered <- mod_filter_province_server(
id = "filter_province",
.daily_canada_data = daily_canada_data,
.daily_province_data = daily_province_data,
.province = province
)
mod_tab_overview_server(
id = "overview",
.daily_data_filtered = daily_data_filtered,
.daily_province_data = daily_province_data,
.daily_canada_data = daily_canada_data,
.province = province,
.update_time = update_time,
.dark_mode = .dark_mode
)
mod_tab_comparisons_server(id = "comparisons")
mod_tab_maps_server(id = "maps")
mod_tab_vaccines_server(id = "vaccines")
mod_tab_cases_server(id = "cases")
mod_tab_mortality_server(id = "mortality")
mod_tab_recovered_server(id = "recovered")
mod_tab_testing_server(id = "testing")
mod_tab_about_server(id = "about")
})
}
|
/R/mod_app.R
|
permissive
|
armcn/covidashboard
|
R
| false
| false
| 3,119
|
r
|
#' app UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd
#'
#' @importFrom shiny NS tagList
mod_app_ui <- function(id) {
ns <- NS(id)
dashboard_header <- bs4Dash::dashboardHeader(
title = "COVID-19 in Canada",
fixed = TRUE,
border = FALSE
)
dashboard_sidebar <- bs4Dash::dashboardSidebar(
mod_select_province_ui(
id = ns("select_province")
),
bs4Dash::sidebarMenu(
tab_item_overview(),
tab_item_comparisons(),
tab_item_maps(),
tab_item_vaccines(),
tab_item_cases(),
tab_item_mortality(),
tab_item_recovered(),
tab_item_testing(),
tab_item_about()
)
)
dashboard_body <- bs4Dash::dashboardBody(
fresh::use_googlefont("Lato"),
bs4Dash::tabItems(
mod_tab_overview_ui(id = ns("overview")),
mod_tab_comparisons_ui(id = ns("comparisons")),
mod_tab_maps_ui(id = ns("maps")),
mod_tab_vaccines_ui(id = ns("vaccines")),
mod_tab_cases_ui(id = ns("cases")),
mod_tab_mortality_ui(id = ns("mortality")),
mod_tab_recovered_ui(id = ns("recovered")),
mod_tab_testing_ui(id = ns("testing")),
mod_tab_about_ui(id = ns("about"))
)
)
bs4Dash::dashboardPage(
freshTheme = fresh_theme(),
header = dashboard_header,
sidebar = dashboard_sidebar,
body = dashboard_body,
title = "COVID-19 in Canada",
preloader = preloader_spinner(),
fullscreen = TRUE,
scrollToTop = TRUE,
dark = TRUE
)
}
#' app Server Functions
#'
#' @noRd
mod_app_server <- function(
id,
.daily_canada_data,
.daily_province_data,
.update_time,
.dark_mode
) {
moduleServer(id, function(input, output, session) {
api_data <- get_api_data()
daily_province_data <- pluck(
api_data,
"daily_province_data"
)
daily_canada_data <- pluck(
api_data,
"daily_canada_data"
)
update_time <- pluck(
api_data,
"update_time"
)
province <- mod_select_province_server(
id = "select_province",
.daily_province_data = daily_province_data
)
daily_data_filtered <- mod_filter_province_server(
id = "filter_province",
.daily_canada_data = daily_canada_data,
.daily_province_data = daily_province_data,
.province = province
)
mod_tab_overview_server(
id = "overview",
.daily_data_filtered = daily_data_filtered,
.daily_province_data = daily_province_data,
.daily_canada_data = daily_canada_data,
.province = province,
.update_time = update_time,
.dark_mode = .dark_mode
)
mod_tab_comparisons_server(id = "comparisons")
mod_tab_maps_server(id = "maps")
mod_tab_vaccines_server(id = "vaccines")
mod_tab_cases_server(id = "cases")
mod_tab_mortality_server(id = "mortality")
mod_tab_recovered_server(id = "recovered")
mod_tab_testing_server(id = "testing")
mod_tab_about_server(id = "about")
})
}
|
library(dplyr)
library(cluster)
###################
# UI
###################
clusteringModuleUI <- function(id) {
ns <- NS(id)
fluidRow(
h2(class="panel__title", i18n$t("Clustering")),
box( width = 12,
column(12,uiOutput(ns("setup")))
),
plotOutput(ns("clusteringPlot"))
)
}
###################
# Server
###################
clusteringModule <- function(input, output, session, data) {
ns <- session$ns
output$setup <- renderUI({
column(6,
selectInput(
ns("columnY"),
"Choose a column Y:",
choices = colnames(data)
),
selectInput(
ns("columnX"),
"Choose a column X:",
choices = colnames(data)
),
numericInput(ns("clustersNumber"), 'Cluster count', 3,
min = 1, max = 9
),
actionButton(
inputId = ns("submit"),
label = "Submit"
)
)
})
clusteringData <- eventReactive( input$submit, {
cleanData <- data[data==""]<-NA
cleanData <- data[, c(input$columnY, input$columnX )] %>%
filter(complete.cases(.)) %>% na.omit
})
clusters <- reactive({
kmeans(clusteringData(), input$clustersNumber)
})
output$clusteringPlot <- renderPlot({
palette <- c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
"#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999")
dataClustered <- data.frame(clusteringData(), cluster=factor(clusters()$cluster))
names(dataClustered) <- c("Y_col", "X_col", "cluster")
# TODO: add centroid to plot
ggplot(dataClustered)+
geom_point(
aes(
dataClustered[["X_col"]],dataClustered[["Y_col"]],
col=dataClustered[["cluster"]], shape = dataClustered[["cluster"]]
),
size=6
) + xlab(input$columnX) + ylab(input$columnY)
# # par(mar = c(5.1, 4.1, 0, 1))
# plot(clusteringData(), col = clusters()$cluster, pch = 20, cex = 3 )
# points(clusters()$centers, pch = 4, cex = 4, lwd = 4)
})
}
|
/modules/clusteringModule.R
|
no_license
|
qomposer/survey-shiny-app
|
R
| false
| false
| 1,992
|
r
|
library(dplyr)
library(cluster)
###################
# UI
###################
clusteringModuleUI <- function(id) {
ns <- NS(id)
fluidRow(
h2(class="panel__title", i18n$t("Clustering")),
box( width = 12,
column(12,uiOutput(ns("setup")))
),
plotOutput(ns("clusteringPlot"))
)
}
###################
# Server
###################
clusteringModule <- function(input, output, session, data) {
ns <- session$ns
output$setup <- renderUI({
column(6,
selectInput(
ns("columnY"),
"Choose a column Y:",
choices = colnames(data)
),
selectInput(
ns("columnX"),
"Choose a column X:",
choices = colnames(data)
),
numericInput(ns("clustersNumber"), 'Cluster count', 3,
min = 1, max = 9
),
actionButton(
inputId = ns("submit"),
label = "Submit"
)
)
})
clusteringData <- eventReactive( input$submit, {
cleanData <- data[data==""]<-NA
cleanData <- data[, c(input$columnY, input$columnX )] %>%
filter(complete.cases(.)) %>% na.omit
})
clusters <- reactive({
kmeans(clusteringData(), input$clustersNumber)
})
output$clusteringPlot <- renderPlot({
palette <- c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
"#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999")
dataClustered <- data.frame(clusteringData(), cluster=factor(clusters()$cluster))
names(dataClustered) <- c("Y_col", "X_col", "cluster")
# TODO: add centroid to plot
ggplot(dataClustered)+
geom_point(
aes(
dataClustered[["X_col"]],dataClustered[["Y_col"]],
col=dataClustered[["cluster"]], shape = dataClustered[["cluster"]]
),
size=6
) + xlab(input$columnX) + ylab(input$columnY)
# # par(mar = c(5.1, 4.1, 0, 1))
# plot(clusteringData(), col = clusters()$cluster, pch = 20, cex = 3 )
# points(clusters()$centers, pch = 4, cex = 4, lwd = 4)
})
}
|
setwd('/Users/ivanliu/Downloads/Prudential-Life-Insurance-Assessment')
library(readr)
library(xgboost)
library(Metrics)
library(Hmisc)
rm(list=ls());gc()
load('data/fin_train_test_prod.RData')
evalerror = function(preds, dtrain) {
labels <- getinfo(dtrain, "label")
err <- ScoreQuadraticWeightedKappa(as.numeric(labels),as.numeric(round(preds)))
return(list(metric = "kappa", value = err))
}
evalerror_2 = function(x = seq(1.5, 7.5, by = 1), preds, labels) {
cuts = c(min(preds), x[1], x[2], x[3], x[4], x[5], x[6], x[7], max(preds))
preds = as.numeric(Hmisc::cut2(preds, cuts))
err = Metrics::ScoreQuadraticWeightedKappa(as.numeric(labels), preds, 1, 8)
return(-err)
}
### Split Data ###
set.seed(1989)
cv <- 10
folds <- createFolds(as.factor(train$Response), k = cv, list = FALSE)
dropitems <- c('Id','Response')
feature.names <- names(train)[!names(train) %in% dropitems]
train_sc <- train
test_sc <- test
### Start Training ###
for(i in 1:cv){
f <- folds==i
dval <- xgb.DMatrix(data=data.matrix(train_sc[f,feature.names]),label=train_sc[f,'Response'])
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[!f,feature.names]),label=train_sc[!f,'Response'])
watchlist <- list(val=dval,train=dtrain)
# Feat1
clf <- xgb.train(data = dtrain, eval_metric = 'rmse',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_rmse <- predict(clf, dval)
# Feat2
clf <- xgb.train(data = dtrain, feval = evalerror,
early.stop.round = 200, watchlist = watchlist, maximize = T,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_kappa <- predict(clf, dval)
# Leafs
clf <- xgb.train(data = dtrain,
nrounds = 16,
early.stop.round = 200,
watchlist = watchlist,
feval = evalerror,
# eval_metric = 'rmse',
maximize = TRUE,
objective = "reg:linear",
booster = "gbtree",
eta = 0.6,
max_depth = 6,
min_child_weight = 200,
subsample = 0.8,
colsample = 0.67,
print.every.n = 1
)
validPreds <- as.data.frame(predict(clf, dval, predleaf = TRUE))
names(validPreds) <- c(paste0('xgb_leaf_', 1:16))
dval <- xgb.DMatrix(data=data.matrix(train_sc[f,feature.names]),label=train_sc[f,'Response']-1)
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[!f,feature.names]),label=train_sc[!f,'Response']-1)
watchlist <- list(val=dval,train=dtrain)
# Feat3
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax <- predict(clf, dval)
# Feat4
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob <- predict(clf, dval)
# Feat5
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 800, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax_mlog <- predict(clf, dval)
# Feat6
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob_mlog <- predict(clf, dval)
### Make new features
if(i==1){
train_2nd <- train_sc[f,]
train_2nd$XGB_RMSE <- pred_rmse
train_2nd$XGB_KAPPA <- pred_kappa
train_2nd$XGB_SOFTMAX <- pred_softmax
train_2nd$XGB_SOFTMAX_MLOG <- pred_softmax_mlog
META_XGB_MULSOFT <- as.data.frame(t(matrix(pred_softprob, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT) <- paste('META_XGB_MUL_', 1:8, sep = '')
META_XGB_MULSOFT_MLOG <- as.data.frame(t(matrix(pred_softprob_mlog, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT_MLOG) <- paste('META_XGB_MUL_MLOG_', 1:8, sep = '')
train_2nd <- cbind(train_2nd, META_XGB_MULSOFT, META_XGB_MULSOFT_MLOG, validPreds)
train_meta <- train_2nd
}else{
train_2nd <- train_sc[f,]
train_2nd$XGB_RMSE <- pred_rmse
train_2nd$XGB_KAPPA <- pred_kappa
train_2nd$XGB_SOFTMAX <- pred_softmax
train_2nd$XGB_SOFTMAX_MLOG <- pred_softmax_mlog
META_XGB_MULSOFT <- as.data.frame(t(matrix(pred_softprob, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT) <- paste('META_XGB_MUL_', 1:8, sep = '')
META_XGB_MULSOFT_MLOG <- as.data.frame(t(matrix(pred_softprob_mlog, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT_MLOG) <- paste('META_XGB_MUL_MLOG_', 1:8, sep = '')
train_2nd <- cbind(train_2nd, META_XGB_MULSOFT, META_XGB_MULSOFT_MLOG, validPreds)
train_meta <- rbind(train_meta, train_2nd)
}
}
save(train_meta, file='../final_train_meta.RData')
# For test data
dtest <- xgb.DMatrix(data=data.matrix(test_sc[,feature.names]),label=test_sc[,'Response'])
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[,feature.names]),label=train_sc[,'Response'])
watchlist <- list(val=dtest,train=dtrain)
# Feat1
clf <- xgb.train(data = dtrain, eval_metric = 'rmse',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_rmse <- predict(clf, dtest)
# Feat2
clf <- xgb.train(data = dtrain, feval = evalerror,
early.stop.round = 200, watchlist = watchlist, maximize = T,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_kappa <- predict(clf, dtest)
# Leafs
clf <- xgb.train(data = dtrain,
nrounds = 16,
early.stop.round = 200,
watchlist = watchlist,
feval = evalerror,
maximize = TRUE,
objective = "reg:linear",
booster = "gbtree",
eta = 0.6,
max_depth = 6,
min_child_weight = 200,
subsample = 0.8,
colsample = 0.67,
print.every.n = 1
)
validPreds <- as.data.frame(predict(clf, dtest, predleaf = TRUE))
names(validPreds) <- c(paste0('xgb_leaf_', 1:16))
dtest <- xgb.DMatrix(data=data.matrix(test_sc[,feature.names]),label=test_sc[,'Response'])
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[,feature.names]),label=train_sc[,'Response']-1)
watchlist <- list(val=dtest,train=dtrain)
# Feat3
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax <- predict(clf, dtest)
# Feat4
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob <- predict(clf, dtest)
# Feat5
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 800, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax_mlog <- predict(clf, dtest)
# Feat6
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob_mlog <- predict(clf, dtest)
### Make predictions
train_2nd <- test_sc
train_2nd$XGB_RMSE <- pred_rmse
train_2nd$XGB_KAPPA <- pred_kappa
train_2nd$XGB_SOFTMAX <- pred_softmax
train_2nd$XGB_SOFTMAX_MLOG <- pred_softmax_mlog
META_XGB_MULSOFT <- as.data.frame(t(matrix(pred_softprob, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT) <- paste('META_XGB_MUL_', 1:8, sep = '')
META_XGB_MULSOFT_MLOG <- as.data.frame(t(matrix(pred_softprob_mlog, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT_MLOG) <- paste('META_XGB_MUL_MLOG_', 1:8, sep = '')
train_2nd <- cbind(train_2nd, META_XGB_MULSOFT, META_XGB_MULSOFT_MLOG, validPreds)
test_meta <- train_2nd
train <- train_meta
test <- test_meta
######################################
# 4. Split/Output Data #####
############################
total_new <- rbind(train_meta, test_meta)
for (col in paste0('xgb_leaf_',1:16)){
total_new[,col] <- as.factor(total_new[,col])
}
dummies <- dummyVars(Response ~ ., data = total_new[,c(paste0("xgb_leaf_", 1:16), 'Response')],
sep = "_", levelsOnly = FALSE, fullRank = TRUE)
total1 <- as.data.frame(predict(dummies, newdata = total_new))
total_new <- cbind(total_new[,-c(ncol(total_new))], total1, Response=total_new$Response)
train <- total_new[total_new$Response != 0, ]
test <- total_new[total_new$Response == 0, ]
save(train, test, file = 'data/xgb_meta_leaf_20150211_dummy.RData')
|
/Rscripts/_Fin_meta_data.R
|
no_license
|
ivanliu1989/Prudential-Life-Insurance-Assessment
|
R
| false
| false
| 11,932
|
r
|
setwd('/Users/ivanliu/Downloads/Prudential-Life-Insurance-Assessment')
library(readr)
library(xgboost)
library(Metrics)
library(Hmisc)
rm(list=ls());gc()
load('data/fin_train_test_prod.RData')
evalerror = function(preds, dtrain) {
labels <- getinfo(dtrain, "label")
err <- ScoreQuadraticWeightedKappa(as.numeric(labels),as.numeric(round(preds)))
return(list(metric = "kappa", value = err))
}
evalerror_2 = function(x = seq(1.5, 7.5, by = 1), preds, labels) {
cuts = c(min(preds), x[1], x[2], x[3], x[4], x[5], x[6], x[7], max(preds))
preds = as.numeric(Hmisc::cut2(preds, cuts))
err = Metrics::ScoreQuadraticWeightedKappa(as.numeric(labels), preds, 1, 8)
return(-err)
}
### Split Data ###
set.seed(1989)
cv <- 10
folds <- createFolds(as.factor(train$Response), k = cv, list = FALSE)
dropitems <- c('Id','Response')
feature.names <- names(train)[!names(train) %in% dropitems]
train_sc <- train
test_sc <- test
### Start Training ###
for(i in 1:cv){
f <- folds==i
dval <- xgb.DMatrix(data=data.matrix(train_sc[f,feature.names]),label=train_sc[f,'Response'])
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[!f,feature.names]),label=train_sc[!f,'Response'])
watchlist <- list(val=dval,train=dtrain)
# Feat1
clf <- xgb.train(data = dtrain, eval_metric = 'rmse',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_rmse <- predict(clf, dval)
# Feat2
clf <- xgb.train(data = dtrain, feval = evalerror,
early.stop.round = 200, watchlist = watchlist, maximize = T,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_kappa <- predict(clf, dval)
# Leafs
clf <- xgb.train(data = dtrain,
nrounds = 16,
early.stop.round = 200,
watchlist = watchlist,
feval = evalerror,
# eval_metric = 'rmse',
maximize = TRUE,
objective = "reg:linear",
booster = "gbtree",
eta = 0.6,
max_depth = 6,
min_child_weight = 200,
subsample = 0.8,
colsample = 0.67,
print.every.n = 1
)
validPreds <- as.data.frame(predict(clf, dval, predleaf = TRUE))
names(validPreds) <- c(paste0('xgb_leaf_', 1:16))
dval <- xgb.DMatrix(data=data.matrix(train_sc[f,feature.names]),label=train_sc[f,'Response']-1)
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[!f,feature.names]),label=train_sc[!f,'Response']-1)
watchlist <- list(val=dval,train=dtrain)
# Feat3
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax <- predict(clf, dval)
# Feat4
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob <- predict(clf, dval)
# Feat5
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 800, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax_mlog <- predict(clf, dval)
# Feat6
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob_mlog <- predict(clf, dval)
### Make new features
if(i==1){
train_2nd <- train_sc[f,]
train_2nd$XGB_RMSE <- pred_rmse
train_2nd$XGB_KAPPA <- pred_kappa
train_2nd$XGB_SOFTMAX <- pred_softmax
train_2nd$XGB_SOFTMAX_MLOG <- pred_softmax_mlog
META_XGB_MULSOFT <- as.data.frame(t(matrix(pred_softprob, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT) <- paste('META_XGB_MUL_', 1:8, sep = '')
META_XGB_MULSOFT_MLOG <- as.data.frame(t(matrix(pred_softprob_mlog, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT_MLOG) <- paste('META_XGB_MUL_MLOG_', 1:8, sep = '')
train_2nd <- cbind(train_2nd, META_XGB_MULSOFT, META_XGB_MULSOFT_MLOG, validPreds)
train_meta <- train_2nd
}else{
train_2nd <- train_sc[f,]
train_2nd$XGB_RMSE <- pred_rmse
train_2nd$XGB_KAPPA <- pred_kappa
train_2nd$XGB_SOFTMAX <- pred_softmax
train_2nd$XGB_SOFTMAX_MLOG <- pred_softmax_mlog
META_XGB_MULSOFT <- as.data.frame(t(matrix(pred_softprob, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT) <- paste('META_XGB_MUL_', 1:8, sep = '')
META_XGB_MULSOFT_MLOG <- as.data.frame(t(matrix(pred_softprob_mlog, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT_MLOG) <- paste('META_XGB_MUL_MLOG_', 1:8, sep = '')
train_2nd <- cbind(train_2nd, META_XGB_MULSOFT, META_XGB_MULSOFT_MLOG, validPreds)
train_meta <- rbind(train_meta, train_2nd)
}
}
save(train_meta, file='../final_train_meta.RData')
# For test data
dtest <- xgb.DMatrix(data=data.matrix(test_sc[,feature.names]),label=test_sc[,'Response'])
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[,feature.names]),label=train_sc[,'Response'])
watchlist <- list(val=dtest,train=dtrain)
# Feat1
clf <- xgb.train(data = dtrain, eval_metric = 'rmse',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_rmse <- predict(clf, dtest)
# Feat2
clf <- xgb.train(data = dtrain, feval = evalerror,
early.stop.round = 200, watchlist = watchlist, maximize = T,
verbose = 1, objective = "reg:linear",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 700, colsample = 0.67, print.every.n = 10
)
pred_kappa <- predict(clf, dtest)
# Leafs
clf <- xgb.train(data = dtrain,
nrounds = 16,
early.stop.round = 200,
watchlist = watchlist,
feval = evalerror,
maximize = TRUE,
objective = "reg:linear",
booster = "gbtree",
eta = 0.6,
max_depth = 6,
min_child_weight = 200,
subsample = 0.8,
colsample = 0.67,
print.every.n = 1
)
validPreds <- as.data.frame(predict(clf, dtest, predleaf = TRUE))
names(validPreds) <- c(paste0('xgb_leaf_', 1:16))
dtest <- xgb.DMatrix(data=data.matrix(test_sc[,feature.names]),label=test_sc[,'Response'])
dtrain <- xgb.DMatrix(data=data.matrix(train_sc[,feature.names]),label=train_sc[,'Response']-1)
watchlist <- list(val=dtest,train=dtrain)
# Feat3
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax <- predict(clf, dtest)
# Feat4
clf <- xgb.train(data = dtrain, eval_metric = 'merror',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob <- predict(clf, dtest)
# Feat5
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softmax",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 800, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softmax_mlog <- predict(clf, dtest)
# Feat6
clf <- xgb.train(data = dtrain, eval_metric = 'mlogloss',
early.stop.round = 200, watchlist = watchlist, maximize = F,
verbose = 1, objective = "multi:softprob",
booste = "gbtree", eta = 0.035, max_depth = 6, min_child_weight = 50, subsample = 0.8,
nrounds = 500, colsample = 0.7, print.every.n = 10 ,num_class = 8
)
pred_softprob_mlog <- predict(clf, dtest)
### Make predictions
train_2nd <- test_sc
train_2nd$XGB_RMSE <- pred_rmse
train_2nd$XGB_KAPPA <- pred_kappa
train_2nd$XGB_SOFTMAX <- pred_softmax
train_2nd$XGB_SOFTMAX_MLOG <- pred_softmax_mlog
META_XGB_MULSOFT <- as.data.frame(t(matrix(pred_softprob, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT) <- paste('META_XGB_MUL_', 1:8, sep = '')
META_XGB_MULSOFT_MLOG <- as.data.frame(t(matrix(pred_softprob_mlog, 8, nrow(train_2nd))))
names(META_XGB_MULSOFT_MLOG) <- paste('META_XGB_MUL_MLOG_', 1:8, sep = '')
train_2nd <- cbind(train_2nd, META_XGB_MULSOFT, META_XGB_MULSOFT_MLOG, validPreds)
test_meta <- train_2nd
train <- train_meta
test <- test_meta
######################################
# 4. Split/Output Data #####
############################
total_new <- rbind(train_meta, test_meta)
for (col in paste0('xgb_leaf_',1:16)){
total_new[,col] <- as.factor(total_new[,col])
}
dummies <- dummyVars(Response ~ ., data = total_new[,c(paste0("xgb_leaf_", 1:16), 'Response')],
sep = "_", levelsOnly = FALSE, fullRank = TRUE)
total1 <- as.data.frame(predict(dummies, newdata = total_new))
total_new <- cbind(total_new[,-c(ncol(total_new))], total1, Response=total_new$Response)
train <- total_new[total_new$Response != 0, ]
test <- total_new[total_new$Response == 0, ]
save(train, test, file = 'data/xgb_meta_leaf_20150211_dummy.RData')
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fit_and_reporting.R
\name{geometric_mean}
\alias{geometric_mean}
\title{Geometric Mean}
\usage{
geometric_mean(x, na.rm = c(TRUE, FALSE))
}
\arguments{
\item{x}{A vector of values.}
\item{na.rm}{remove NAs by default.}
}
\value{
\itemize{
\item Geometric mean of x
}
}
\description{
\verb{Geometric means} are the nth-root of the product of the input values.
Common uses include computing economic utility.
}
\examples{
geometric_mean(c(50, 100))
# For a given sum, geometric mean is maximised with equality
geometric_mean(c(75,75))
v = c(1, 149); c(sum(v), geometric_mean(v), mean(v), median(v))
# 150.00000 12.20656 75.00000 75.00000
# Underlying logic
sqrt(50 * 100)
# Alternate form using logs
exp(mean(log(c(50 *100))))
# Reciprocal duality
1/geometric_mean(c(100, 50))
geometric_mean(c(1/100, 1/50))
}
\references{
\itemize{
\item \url{https://en.wikipedia.org/wiki/Geometric_mean}
}
}
\seealso{
Other Miscellaneous Stats Helpers:
\code{\link{FishersMethod}()},
\code{\link{SE_from_p}()},
\code{\link{harmonic_mean}()},
\code{\link{oddsratio}()},
\code{\link{reliability}()},
\code{\link{umxCov2cor}()},
\code{\link{umxHetCor}()},
\code{\link{umxWeightedAIC}()},
\code{\link{umx_apply}()},
\code{\link{umx_cor}()},
\code{\link{umx_means}()},
\code{\link{umx_r_test}()},
\code{\link{umx_round}()},
\code{\link{umx_scale}()},
\code{\link{umx_var}()},
\code{\link{umx}}
}
\concept{Miscellaneous Stats Helpers}
|
/man/geometric_mean.Rd
|
no_license
|
jishanling/umx
|
R
| false
| true
| 1,501
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fit_and_reporting.R
\name{geometric_mean}
\alias{geometric_mean}
\title{Geometric Mean}
\usage{
geometric_mean(x, na.rm = c(TRUE, FALSE))
}
\arguments{
\item{x}{A vector of values.}
\item{na.rm}{remove NAs by default.}
}
\value{
\itemize{
\item Geometric mean of x
}
}
\description{
\verb{Geometric means} are the nth-root of the product of the input values.
Common uses include computing economic utility.
}
\examples{
geometric_mean(c(50, 100))
# For a given sum, geometric mean is maximised with equality
geometric_mean(c(75,75))
v = c(1, 149); c(sum(v), geometric_mean(v), mean(v), median(v))
# 150.00000 12.20656 75.00000 75.00000
# Underlying logic
sqrt(50 * 100)
# Alternate form using logs
exp(mean(log(c(50 *100))))
# Reciprocal duality
1/geometric_mean(c(100, 50))
geometric_mean(c(1/100, 1/50))
}
\references{
\itemize{
\item \url{https://en.wikipedia.org/wiki/Geometric_mean}
}
}
\seealso{
Other Miscellaneous Stats Helpers:
\code{\link{FishersMethod}()},
\code{\link{SE_from_p}()},
\code{\link{harmonic_mean}()},
\code{\link{oddsratio}()},
\code{\link{reliability}()},
\code{\link{umxCov2cor}()},
\code{\link{umxHetCor}()},
\code{\link{umxWeightedAIC}()},
\code{\link{umx_apply}()},
\code{\link{umx_cor}()},
\code{\link{umx_means}()},
\code{\link{umx_r_test}()},
\code{\link{umx_round}()},
\code{\link{umx_scale}()},
\code{\link{umx_var}()},
\code{\link{umx}}
}
\concept{Miscellaneous Stats Helpers}
|
#######################################
# Author: Rother Jay B. Copino #
# Date Create: 02/24/2017 #
# Dataset: Electric Power Consumption #
# File: plot2.png #
#######################################
# Set the current working directory
setwd("Downloads/Data Science/Module 4/Peer-graded-Project-1/ExData_Plotting1/")
# Read the data from the input file
epc <- read.table("household_power_consumption.txt",header=TRUE,sep=";",stringsAsFactors=FALSE)
# Subset the epc with Date February 1, 2007 and February 2, 2007
subset_epc <- subset(epc, Date %in% c('1/2/2007', '2/2/2007'))
# Convert the Date and Time variables to Date/Time classes
datetime <- strptime(paste(subset_epc$Date, subset_epc$Time, sep=" "), "%d/%m/%Y %H:%M:%S")
# Initiaze the parameters of the device
png("plot2.png", width = 1024, height = 1024)
# Generate the histogram for the Global Active Power vector
plot(datetime, as.numeric(subset_epc$Global_active_power), type="l", xlab = "", ylab = "Global Active Power (kilowatts)", ylim = range(0,6))
# Close the device
dev.off()
|
/plot2.R
|
no_license
|
rotherjay/ExData_Plotting1
|
R
| false
| false
| 1,086
|
r
|
#######################################
# Author: Rother Jay B. Copino #
# Date Create: 02/24/2017 #
# Dataset: Electric Power Consumption #
# File: plot2.png #
#######################################
# Set the current working directory
setwd("Downloads/Data Science/Module 4/Peer-graded-Project-1/ExData_Plotting1/")
# Read the data from the input file
epc <- read.table("household_power_consumption.txt",header=TRUE,sep=";",stringsAsFactors=FALSE)
# Subset the epc with Date February 1, 2007 and February 2, 2007
subset_epc <- subset(epc, Date %in% c('1/2/2007', '2/2/2007'))
# Convert the Date and Time variables to Date/Time classes
datetime <- strptime(paste(subset_epc$Date, subset_epc$Time, sep=" "), "%d/%m/%Y %H:%M:%S")
# Initiaze the parameters of the device
png("plot2.png", width = 1024, height = 1024)
# Generate the histogram for the Global Active Power vector
plot(datetime, as.numeric(subset_epc$Global_active_power), type="l", xlab = "", ylab = "Global Active Power (kilowatts)", ylim = range(0,6))
# Close the device
dev.off()
|
########################UPSETR##############################
#UpsetR takes a list of genes, with each column named after the DE list, with 1's (present gene) and 0's. I made a combined list of
HAM_24hpi_DE_genes_FDR_0.05$HAM_24hpi <- rep(1,nrow(HAM_24hpi_DE_genes_FDR_0.05))
MDM_24hpi_DE_genes_FDR_0.05$MDM_24hpi <- rep(1,nrow(MDM_24hpi_DE_genes_FDR_0.05))
MB_24hpi_DE_genes_FDR_0.05$MB_24hpi <- rep(1,nrow(MB_24hpi_DE_genes_FDR_0.05))
TB_24hpi_DE_genes_FDR_0.05$TB_24hpi <- rep(1,nrow(TB_24hpi_DE_genes_FDR_0.05))
UpsetR_figure <- merge(Human_and_Bovine_gene_list, HAM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure <- merge(UpsetR_figure, MDM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure <- merge(UpsetR_figure, MB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure <- merge(UpsetR_figure, TB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure[is.na(UpsetR_figure)] <- 0
#simple
upset(UpsetR_figure, sets = c("hAM_TB_24hpi", "hMDM_TB_24hpi", "bAM_TB_24hpi", "bAM_MB_24hpi"),
sets.bar.color = c("#809fff", "#ffcc80", "#ff6666", "#8cd98c" ), order.by = "freq", empty.intersections = "on",
matrix.color = "#3d3d5c", main.bar.color = "#52527a" )
#for getting avg logfc
UpsetR_figure_LFC <- merge(Human_and_Bovine_gene_list, HAM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
UpsetR_figure_LFC <- merge(UpsetR_figure_LFC, MDM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
UpsetR_figure_LFC <- merge(UpsetR_figure_LFC, MB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
UpsetR_figure_LFC <- merge(UpsetR_figure_LFC, TB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
colnames(UpsetR_figure_LFC)[2] <- "Log2FC_hAM_TB_24hpi"
colnames(UpsetR_figure_LFC)[5] <- "Log2FC_hMDM_TB_24hpi"
colnames(UpsetR_figure_LFC)[8] <- "Log2FC_bAM_MB_24hpi"
colnames(UpsetR_figure_LFC)[11] <- "Log2FC_bAM_TB_24hpi"
colnames(UpsetR_figure_LFC)[3] <- "FDR_hAM_TB_24hpi"
colnames(UpsetR_figure_LFC)[6] <- "FDR_hMDM_TB_24hpi"
colnames(UpsetR_figure_LFC)[9] <- "FDR_bAM_MB_24hpi"
colnames(UpsetR_figure_LFC)[12] <- "FDR_bAM_TB_24hpi"
UpsetR_figure_LFC <- subset(UpsetR_figure_LFC, select = c(1,2,5,8,11,3,6,9,12))
UpsetR_figure_LFC$Avg_Log2FC<- rowMeans(UpsetR_figure_LFC[,2:5], na.rm = TRUE)
UpsetR_figure_LFC$Avg_FDR<- rowMeans(UpsetR_figure_LFC[,6:9], na.rm = TRUE)
UpsetR_figure_avg <- merge(UpsetR_figure, UpsetR_figure_LFC, by = "Gene_ID", all.x = TRUE)
|
/R_scripts/PLOT_UpsetR.R
|
no_license
|
ThomasHall1688/Human_Bovine_comparison
|
R
| false
| false
| 3,008
|
r
|
########################UPSETR##############################
#UpsetR takes a list of genes, with each column named after the DE list, with 1's (present gene) and 0's. I made a combined list of
HAM_24hpi_DE_genes_FDR_0.05$HAM_24hpi <- rep(1,nrow(HAM_24hpi_DE_genes_FDR_0.05))
MDM_24hpi_DE_genes_FDR_0.05$MDM_24hpi <- rep(1,nrow(MDM_24hpi_DE_genes_FDR_0.05))
MB_24hpi_DE_genes_FDR_0.05$MB_24hpi <- rep(1,nrow(MB_24hpi_DE_genes_FDR_0.05))
TB_24hpi_DE_genes_FDR_0.05$TB_24hpi <- rep(1,nrow(TB_24hpi_DE_genes_FDR_0.05))
UpsetR_figure <- merge(Human_and_Bovine_gene_list, HAM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure <- merge(UpsetR_figure, MDM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure <- merge(UpsetR_figure, MB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure <- merge(UpsetR_figure, TB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure$log2FoldChange <- NULL
UpsetR_figure$`p-value` <- NULL
UpsetR_figure$FDR <- NULL
UpsetR_figure[is.na(UpsetR_figure)] <- 0
#simple
upset(UpsetR_figure, sets = c("hAM_TB_24hpi", "hMDM_TB_24hpi", "bAM_TB_24hpi", "bAM_MB_24hpi"),
sets.bar.color = c("#809fff", "#ffcc80", "#ff6666", "#8cd98c" ), order.by = "freq", empty.intersections = "on",
matrix.color = "#3d3d5c", main.bar.color = "#52527a" )
#for getting avg logfc
UpsetR_figure_LFC <- merge(Human_and_Bovine_gene_list, HAM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
UpsetR_figure_LFC <- merge(UpsetR_figure_LFC, MDM_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
UpsetR_figure_LFC <- merge(UpsetR_figure_LFC, MB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
UpsetR_figure_LFC <- merge(UpsetR_figure_LFC, TB_24hpi_DE_genes_FDR_0.05, by = "Gene_ID", all.x = TRUE)
UpsetR_figure_LFC$`p-value` <- NULL
colnames(UpsetR_figure_LFC)[2] <- "Log2FC_hAM_TB_24hpi"
colnames(UpsetR_figure_LFC)[5] <- "Log2FC_hMDM_TB_24hpi"
colnames(UpsetR_figure_LFC)[8] <- "Log2FC_bAM_MB_24hpi"
colnames(UpsetR_figure_LFC)[11] <- "Log2FC_bAM_TB_24hpi"
colnames(UpsetR_figure_LFC)[3] <- "FDR_hAM_TB_24hpi"
colnames(UpsetR_figure_LFC)[6] <- "FDR_hMDM_TB_24hpi"
colnames(UpsetR_figure_LFC)[9] <- "FDR_bAM_MB_24hpi"
colnames(UpsetR_figure_LFC)[12] <- "FDR_bAM_TB_24hpi"
UpsetR_figure_LFC <- subset(UpsetR_figure_LFC, select = c(1,2,5,8,11,3,6,9,12))
UpsetR_figure_LFC$Avg_Log2FC<- rowMeans(UpsetR_figure_LFC[,2:5], na.rm = TRUE)
UpsetR_figure_LFC$Avg_FDR<- rowMeans(UpsetR_figure_LFC[,6:9], na.rm = TRUE)
UpsetR_figure_avg <- merge(UpsetR_figure, UpsetR_figure_LFC, by = "Gene_ID", all.x = TRUE)
|
\name{LapDem_Model_calc_logPP_orig}
\alias{LapDem_Model_calc_logPP_orig}
\title{The function calculating posterior probability of parameter values}
\usage{
LapDem_Model_calc_logPP_orig(params, MyData)
}
\arguments{
\item{params}{the parameter values}
\item{MyData}{The
\code{\link[LaplacesDemon]{LaplacesDemon}} input data.}
}
\value{
\code{Modelout} The MCMC output.
}
\description{
What it says
}
\note{
Go BEARS!
}
\examples{
test=1
}
\author{
Nicholas J. Matzke \email{matzke@berkeley.edu}
}
\references{
\url{http://phylo.wikidot.com/matzke-2013-international-biogeography-society-poster}
LaplacesDemon_Tutorial
Matzke_2012_IBS
}
\seealso{
\code{\link[LaplacesDemon]{LaplacesDemon}}
}
|
/man/LapDem_Model_calc_logPP_orig.Rd
|
no_license
|
pedroreys/BioGeoBEARS
|
R
| false
| false
| 718
|
rd
|
\name{LapDem_Model_calc_logPP_orig}
\alias{LapDem_Model_calc_logPP_orig}
\title{The function calculating posterior probability of parameter values}
\usage{
LapDem_Model_calc_logPP_orig(params, MyData)
}
\arguments{
\item{params}{the parameter values}
\item{MyData}{The
\code{\link[LaplacesDemon]{LaplacesDemon}} input data.}
}
\value{
\code{Modelout} The MCMC output.
}
\description{
What it says
}
\note{
Go BEARS!
}
\examples{
test=1
}
\author{
Nicholas J. Matzke \email{matzke@berkeley.edu}
}
\references{
\url{http://phylo.wikidot.com/matzke-2013-international-biogeography-society-poster}
LaplacesDemon_Tutorial
Matzke_2012_IBS
}
\seealso{
\code{\link[LaplacesDemon]{LaplacesDemon}}
}
|
testlist <- list(cost = structure(c(1.44888560957826e+135, 1.6249392498385e+65, 5.27956628994611e-134, 1.56839475268612e-251, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 5L)), flow = structure(c(3.80768289350145e+125, 8.58414828913381e+155, 3.37787969964034e+43, 2.83184518248624e-19, 7.49487861616974e+223, 8.52929466674086e+86, 2.51852491380534e-303, 3.12954510408264e-253, 2.45741775099414e-215, 6.59159492364721e+70, 2.33952815237705e+77, 3.1674929214459e+282, 1.0709591854537e+63, 7.43876613929257e+191, 8.31920980250172e+78, 1.26747339146319e+161, 5.68076251052666e-141, 9.98610641272026e+182, 232665383858.491, 3.75587249552337e-34, 8.67688084914444e+71, 2.85936996201565e+135, 5.49642980516022e+268, 854537747349405, 1.33507119962914e+95, 2.76994725819545e+63, 4.08029273738449e+275, 4.93486427894025e+289, 1.24604061502336e+294, 3.2125809174767e-185, 9.58716852715016e+39, 6.94657888227078e+275, 3.46330348083089e+199, 3.28318446108869e-286, 6.12239214969922e-296 ), .Dim = c(5L, 7L)))
result <- do.call(epiphy:::costTotCPP,testlist)
str(result)
|
/epiphy/inst/testfiles/costTotCPP/AFL_costTotCPP/costTotCPP_valgrind_files/1615927191-test.R
|
no_license
|
akhikolla/updatedatatype-list2
|
R
| false
| false
| 1,101
|
r
|
testlist <- list(cost = structure(c(1.44888560957826e+135, 1.6249392498385e+65, 5.27956628994611e-134, 1.56839475268612e-251, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(5L, 5L)), flow = structure(c(3.80768289350145e+125, 8.58414828913381e+155, 3.37787969964034e+43, 2.83184518248624e-19, 7.49487861616974e+223, 8.52929466674086e+86, 2.51852491380534e-303, 3.12954510408264e-253, 2.45741775099414e-215, 6.59159492364721e+70, 2.33952815237705e+77, 3.1674929214459e+282, 1.0709591854537e+63, 7.43876613929257e+191, 8.31920980250172e+78, 1.26747339146319e+161, 5.68076251052666e-141, 9.98610641272026e+182, 232665383858.491, 3.75587249552337e-34, 8.67688084914444e+71, 2.85936996201565e+135, 5.49642980516022e+268, 854537747349405, 1.33507119962914e+95, 2.76994725819545e+63, 4.08029273738449e+275, 4.93486427894025e+289, 1.24604061502336e+294, 3.2125809174767e-185, 9.58716852715016e+39, 6.94657888227078e+275, 3.46330348083089e+199, 3.28318446108869e-286, 6.12239214969922e-296 ), .Dim = c(5L, 7L)))
result <- do.call(epiphy:::costTotCPP,testlist)
str(result)
|
########################################################################################################################
## segmentation.R
## created: 2019-01-04
## creator: Michael Scherer
## ---------------------------------------------------------------------------------------------------------------------
## Functions for segmentation of the methylome through MethylSeekR
########################################################################################################################
#' rnb.execute.segmentation
#'
#' This function computes methylation segmentation by MethylSeekR into PMDs, UMRs/LMRs, and HMDs. It is recommened to only
#' execute this function on WGBS data (with coverage >=10 according to the developer's recommendation), but could also be
#' used with RRBS_HaeIII without guarantee and the results should be interpreted carefully.
#'
#' @param rnb.set An object of type \code{\link{RnBiseqSet-class}} containing methylation and coverage information.
#' @param sample.name The sample for which segmentation is to be executed. Segemntation can only be exectued for each sample
#' individually.
#' @param meth.level Methylation cutoff to be used in UMR/LMR computation
#' @param fdr False discovery rate cutoff to be used in percent
#' @param min.cover The coverage threshold
#' @param n.cores The number of cores available for analysis
#' @param chr.sel Selected chromosome for model training in "chrAB" format. Defaults to "chr2".
#' @param plot.path Location on disk on which diagnostic plots are to be stored. Defaults to the working directory.
#' @param temp.dir The temporary directory. Defaults to the R temporary directory.
#' @return The input RnBSet object with segementation added as an additional region type. Furthermore, three new annotations
#' are set globally containing segmentation into PMDs, UMRs/LMRs, and HMDs for the sample that was specified.
#' @details For further descriptions on the methods, see \code{MethylSeekR}-documentation. The new annotations can be accessed
#' via \code{rnb.get.annotation("[PMDs,UMRs,LMRs,HMDs]_[sample.name]")}.
#' @references 1. Burger, Lukas, Gaidatzis, Dimos, Schuebeler, Dirk, and Stadler, Michael B. (2013)
#' Identification of active regulatory regions from DNA methylation data.
#' Nucleic Acids Research 41(16):e155.
#' @author Michael Scherer, based on a script by Abdulrahman Salhab
#' @export
rnb.execute.segmentation <- function(rnb.set,
sample.name,
meth.level=0.5,
fdr=5,
min.cover=5,
n.cores=1,
chr.sel="chr2",
plot.path=getwd(),
temp.dir=tempdir()){
if(!inherits(rnb.set,"RnBiseqSet")){
logger.error("Invalid value for rnb.set, needs to be RnBiseqSet")
}
if(length(sample.name)>1){
logger.error("Only single sample can be analysed")
}
rnb.require("MethylSeekR")
asb <- assembly(rnb.set)
if(asb %in% c("hg19","hg38")){
rnb.require(paste0("BSgenome.Hsapiens.UCSC.",asb))
myGenomeSeq <- Hsapiens
}else if(asb %in% "mm10"){
rnb.require(paste0("BSgenome.Mmusculus.UCSC.",asb))
myGenomeSeq <- Mmusculus
}else{
logger.info("Invalid assembly; Segmentation only supported for hg19, hg38 and mm10")
}
sLengths <- seqlengths(rnb.get.annotation("CpG",assembly = asb))
sLengths.gr <- GRanges(Rle(names(sLengths)),IRanges(start = 1,end=sLengths))
CpGislands.gr <- rnb.get.annotation("cpgislands",assembly = asb)
CpGislands.gr <-suppressWarnings(resize(CpGislands.gr, 5000, fix="center"))
session <- browserSession(url = 'http://genome-euro.ucsc.edu/cgi-bin/')
genome(session) <- asb
query <- ucscTableQuery(session, table="gap")
gaps <- getTable(query)
gaps.gr <- makeGRangesFromDataFrame(gaps, starts.in.df.are.0based=TRUE) # the second argument to be discussed 0/1 based
if(any(!(rnb.region.types.for.analysis(rnb.set) %in% rnb.region.types(assembly(rnb.set))))){
rnb.load.annotation.from.db(rnb.region.types.for.analysis(rnb.set)[!(rnb.region.types.for.analysis(rnb.set) %in% rnb.region.types(assembly(rnb.set)))],assembly(rnb.set))
}
sel.sample <- samples(rnb.set) %in% sample.name
if(!any(sel.sample)){
logger.error(paste("Specified sample",sample.name,"not in RnBSet"))
}
sel.sample <- which(sel.sample)
meth.rnb <- rnb.set@meth.sites[,sel.sample]
is.na.meth <- is.na(meth.rnb)
covg.rnb <- rnb.set@covg.sites[,sel.sample]
meth.matrix <- round(meth.rnb*covg.rnb)
nas <- is.na(covg.rnb) | is.na.meth
anno.rnb <- data.frame2GRanges(annotation(rnb.set),assembly=assembly(rnb.set))
anno.rnb <- sort(anno.rnb)
anno.rnb <- anno.rnb[!nas]
tmp.anno <- anno.rnb
values(tmp.anno) <- data.frame(T=covg.rnb[!nas],M=meth.matrix[!nas])
tmp.file.meth <- file.path(temp.dir,"GRanges_for_MethylSeekR.RDS")
saveRDS(tmp.anno,tmp.file.meth)
data.gr <- readMethylome(tmp.file.meth, seqLengths=sLengths, format="GRanges")
### read SNPs
anno.rnb <- anno.rnb[!is.na(values(anno.rnb)$SNPs)]
values(anno.rnb) <- values(anno.rnb)$SNPs
tmp.file.snps <- file.path(temp.dir,"GRangesSNP_for_MethylSeekR.RDS")
saveRDS(anno.rnb,tmp.file.snps)
snps.gr <- readSNPTable(tmp.file.snps, seqLengths=sLengths, format="GRanges")
### removing SNPs
if(length(snps.gr)>0){
cat("Filtering the SNPs ......\n")
data.gr <- removeSNPs(data.gr, snps.gr)
}
### find PMD and plot
logger.start("Detecting PMDs")
PMDsegments.gr <- segmentPMDs(m=data.gr,pdfFilename=file.path(plot.path,paste(sample.name,"alpha.model.fit.pdf",sep=".")), chr.sel=chr.sel,seqLengths=sLengths, num.cores=n.cores)
logger.completed()
logger.start("Plotting alpha distribution")
plotAlphaDistributionOneChr(m=data.gr, chr.sel=chr.sel,pdfFilename=file.path(plot.path,paste(sample.name,"alpha_distribution.pdf",sep=".")),num.cores=n.cores)
logger.completed()
### FDR calculation
logger.start("FDR calculation")
stats <- calculateFDRs(m=data.gr, CGIs=CpGislands.gr,PMDs=PMDsegments.gr, nCpG.cutoffs =seq(1, 17, by=3),pdfFilename=file.path(plot.path,paste(sample.name,"FDR.pdf",sep=".")),num.cores=n.cores)
FDR.cutoff <- as.numeric(fdr)
m.sel <- as.numeric(meth.level)
n.sel <- as.integer(names(stats$FDRs[as.character(m.sel), ][stats$FDRs[as.character(m.sel), ]<FDR.cutoff])[1])
logger.info(paste("Minimum number of CpGs in LMRs:",n.sel,"CpGs"))
logger.completed()
### find UMR and LMR
logger.start("Detecting UMRs and LMRs")
UMRLMRsegments.gr <- segmentUMRsLMRs(m=data.gr, meth.cutoff=m.sel,nCpG.cutoff=n.sel, PMDs=PMDsegments.gr,pdfFilename=file.path(plot.path,paste(sample.name,"UMR.LMR.scatter.pdf",sep=".")),num.cores=n.cores, myGenomeSeq=myGenomeSeq,seqLengths=sLengths, minCover = min.cover)
logger.completed()
# create final segmentation
logger.start("Create final segmentation")
PMDsegments.gr <- PMDsegments.gr[PMDsegments.gr$type=="PMD"]
PMDsegments.gr <- setdiff(PMDsegments.gr,gaps.gr)
PMDsegments.gr$type <- "PMD"
hmr.segments<- setdiff(sLengths.gr,c(PMDsegments.gr,UMRLMRsegments.gr,gaps.gr))
values(hmr.segments)$HMR <- rep("HMR",length(hmr.segments))
logger.completed()
# set new annotations PMD, UMR/LMR, HMR
logger.start("Set new annotations and summarize methylation")
pmd.frame <- data.frame(Chromosome=seqnames(PMDsegments.gr),Start=start(PMDsegments.gr),End=end(PMDsegments.gr),
PMDs=values(PMDsegments.gr)$type)
rnb.set.annotation(paste0("PMDs_",sample.name),regions=pmd.frame,description = "Partially Methylated Domains by MethylSeekR",assembly = asb)
umr.lmr.frame <- data.frame(Chromosome=seqnames(UMRLMRsegments.gr),Start=start(UMRLMRsegments.gr),End=end(UMRLMRsegments.gr),
UMRsLMRs=values(UMRLMRsegments.gr)$type)
umr.frame <- umr.lmr.frame[umr.lmr.frame$UMRsLMRs=="UMR",]
rnb.set.annotation(paste0("UMRs_",sample.name),regions=umr.frame,description = "Unmethylated Regions by MethylSeekR",assembly = asb)
lmr.frame <- umr.lmr.frame[umr.lmr.frame$UMRsLMRs=="LMR",]
rnb.set.annotation(paste0("LMRs_",sample.name),regions=lmr.frame,description = "Lowly Methylated Regions by MethylSeekR",assembly = asb)
hmr.frame <- data.frame(Chromosome=seqnames(hmr.segments),Start=start(hmr.segments),End=end(hmr.segments),
HMDs=values(hmr.segments)$HMR)
rnb.set.annotation(paste0("HMDs_",sample.name),regions=hmr.frame,description = "Highly Methylated Regions by MethylSeekR",assembly = asb)
rnb.set <- summarize.regions(rnb.set,paste("PMDs",sample.name,sep="_"))
rnb.set <- summarize.regions(rnb.set,paste("UMRs",sample.name,sep="_"))
rnb.set <- summarize.regions(rnb.set,paste("LMRs",sample.name,sep="_"))
rnb.set <- summarize.regions(rnb.set,paste("HMDs",sample.name,sep="_"))
logger.completed()
unlink(tmp.file.meth)
unlink(tmp.file.snps)
return(rnb.set)
}
#' rnb.bed.from.segmentation
#'
#' This function creates a BED file from the segmentation result of \code{rnb.execute.segmentation} and stores it on disk.
#'
#' @param rnb.set An \code{\link{RnBSet-class}} object obtained by executing \code{rnb.execute.segmentation}.
#' @param sample.name The sample name for which segmentation was computed.
#' @param type The type of segmentation (\code{PMDs}, \code{UMRs}, \code{LMRs}, \code{HMDs} or \code{final}).
#' @param store.path Path to which the BED file is to be stored.
#' @author Michael Scherer
#' @export
rnb.bed.from.segmentation <- function(rnb.set,
sample.name,
type="final",
store.path=getwd()){
if(!type %in% c("PMDs","UMRs","LMRs","HMDs","final")){
logger.error("Invalid value for type, needs to be PMDs, UMRs, LMRs or HMDs.")
}
if(!(sample.name %in% samples(rnb.set))){
logger.error("Specify a sample that is available in the rnb.set")
}
if(type != "final"){
region.name <- paste(type,sample.name,sep = "_")
if(!(region.name %in% summarized.regions(rnb.set))){
logger.error("Segmentation not yet available, execute rnb.execute.segementation first")
}
bed.frame <- annotation(rnb.set,region.name)
meth.seg <- meth(rnb.set,region.name)[,sample.name]
bed.frame <- data.frame(bed.frame[,c("Chromosome","Start","End",type)],AvgMeth=meth.seg)
}else{
bed.frame <- rnb.final.segmentation(rnb.set,sample.name)
}
write.table(bed.frame,file.path(store.path,paste0(sample.name,"_",type,".bed")),sep="\t",row.names=F,col.names=F,quote = F)
}
#' rnb.boxplot.from.segmentation
#'
#' This function creates a boxplot from the segmentation result of \code{rnb.execute.segmentation}.
#'
#' @param rnb.set An \code{\link{RnBSet-class}} object obtained by executing \code{rnb.execute.segmentation}.
#' @param sample.name The sample name for which segmentation was computed.
#' @param type The type of segmentation (\code{PMDs}, \code{UMRs}, \code{LMRs}, \code{HMDs} or \code{final}).
#' @return An object of type \code{ggplot} visualizing the methylation values in the segments.
#' @author Michael Scherer
#' @export
rnb.boxplot.from.segmentation <- function(rnb.set,
sample.name,
type="final"){
if(!type %in% c("PMDs","UMRs","LMRs","HMDs","final")){
logger.error("Invalid value for type, needs to be PMDs, UMRs, LMRs or HMDs.")
}
if(!(sample.name %in% samples(rnb.set))){
logger.error("Specify a sample that is available in the rnb.set")
}
if(type != "final"){
region.name <- paste(type,sample.name,sep = "_")
if(!(region.name %in% summarized.regions(rnb.set))){
logger.error("Segmentation not yet available, execute rnb.execute.segementation first")
}
bed.frame <- annotation(rnb.set,region.name)
meth.seg <- meth(rnb.set,region.name)[,sample.name]
to.plot <- data.frame(bed.frame[,type],AvgMeth=meth.seg)
colnames(to.plot)[1] <- "Segment"
}else{
to.plot <- rnb.final.segmentation(rnb.set,sample.name)
colnames(to.plot)[4] <- "Segment"
to.plot[,"Segment"] <- factor(to.plot[,"Segment"], levels=c("HMR","PMD","LMR","UMR"))
}
plot <- ggplot(to.plot,aes(x=Segment,y=AvgMeth,fill=Segment))+geom_boxplot()+scale_fill_manual(values=rnb.getOption("colors.category"))
return(plot)
}
#' rnb.final.segmentation
#'
#' This function creates a single segmentation, assigning each region to PMD, HMR, UMR or LMR.
#'
#' @param rnb.set The \code{\link{RnBSet-class}}-object, for which segmentation was computed using \code{\link{rnb.execute.segmentation}}
#' @param sample.name The sample name in \code{rnb.set} for which segmentation was conducted.
#' @author Michael Scherer
#' @noRd
rnb.final.segmentation <- function(rnb.set,
sample.name){
if(!(sample.name %in% samples(rnb.set))){
logger.error("Specify a sample that is available in the rnb.set")
}
region.names <- c(paste("PMDs",sample.name,sep = "_"),paste("HMDs",sample.name,sep = "_"),paste("UMRs",sample.name,sep = "_"),paste("LMRs",sample.name,sep = "_"))
if(any(!(region.names %in% summarized.regions(rnb.set)))){
logger.error("Segmentation not yet available, execute rnb.execute.segementation first")
}
pmd.frame <- annotation(rnb.set,region.names[1])
pmd.meth <- meth(rnb.set,region.names[1])[,sample.name]
pmd.frame <- data.frame(pmd.frame,AvgMeth=pmd.meth)
colnames(pmd.frame)[5] <- "Segment"
hmr.frame <- annotation(rnb.set,region.names[2])
hmr.meth <- meth(rnb.set,region.names[2])[,sample.name]
hmr.frame <- data.frame(hmr.frame,AvgMeth=hmr.meth)
colnames(hmr.frame)[5] <- "Segment"
umr.frame <- annotation(rnb.set,region.names[3])
umr.meth <- meth(rnb.set,region.names[3])[,sample.name]
umr.frame <- data.frame(umr.frame,AvgMeth=umr.meth)
colnames(umr.frame)[5] <- "Segment"
lmr.frame <- annotation(rnb.set,region.names[4])
lmr.meth <- meth(rnb.set,region.names[4])[,sample.name]
lmr.frame <- data.frame(lmr.frame,AvgMeth=lmr.meth)
colnames(lmr.frame)[5] <- "Segment"
final.frame <- data.frame(rbind(pmd.frame,rbind(hmr.frame,umr.frame,lmr.frame)))
final.frame <- final.frame[order(final.frame$Chromosome,final.frame$Start,final.frame$End),]
color.code <- rep("202,0,32",nrow(final.frame))
color.code[final.frame$Segment %in% "PMD"] <- "244,165,130"
color.code[final.frame$Segment %in% "UMR"] <- "5,113,176"
color.code[final.frame$Segment %in% "LMR"] <- "146,197,222"
final.frame <- data.frame(final.frame[,c(1,2,3,5,6)],rep(".",nrow(final.frame)),final.frame[,c(2,3)],color.code)
return(final.frame)
}
#' rnb.plot.segmentation.final
#'
#' This functions plots the final segmentation result.
#'
#' @param data.gr The data object as \code{\link{GRanges}} object
#' @param UMR.LMR.segments.gr Segmentation into UMR/LMR as GRanges
#' @param PMD.segments Segmentation into PMDs/notPMDs as GRanges
#' @param n.regions Number of regions
#' @param meth.cutoff The methylation cutoff
#' @author Michael Scherer
#' @noRd
rnb.plot.segmentation.final <- function(data.gr,
UMR.LMR.segments.gr,
PMD.segments,
n.regions=4,
meth.cutoff){
logger.start("Plotting final segmentation")
plotFinalSegmentation(m=data.gr, segs=UMR.LMR.segments.gr,PMDs=PMD.segments,numRegions = n.regions,meth.cutoff=meth.cutoff)
logger.completed()
}
#'rnb.plot.segmentation.distributions
#'
#'Plots the distributions of methylation and coverage.
#'
#'@param data.gr The data object as \code{\link{GRanges}} object
#'@author Michael Scherer
#'@noRd
rnb.plot.segmentation.distributions <- function(data.gr){
df <- as.data.frame(data.gr)
df$meth <- df$M/df$T
meth.plot <- ggplot(df[df$T>=5,], aes(x=df[df$T>=5,"meth"])) + geom_density(colour="dodgerblue1",size=1) + ylab("density") + xlab("beta value") + ggtitle("Methylation level density")
covg.plot <- ggplot(df, aes(x=df$T)) + geom_histogram(binwidth=1,alpha=.5,position="identity",colour = "dodgerblue1", fill = "dodgerblue1") + geom_vline(xintercept=mean(df$T),colour="black", linetype = "longdash") + ylab("Frequency") + xlab("read coverage per CpG") + geom_text(aes(x2,y2,label = texthere),data.frame(x2=mean(df$T), y2=max(table(df$T)), texthere=round(mean(df$T),2)))
return((list(Methylation=meth.plot,Coverage=covg.plot)))
}
|
/R/segmentation.R
|
no_license
|
epigen/RnBeads
|
R
| false
| false
| 16,660
|
r
|
########################################################################################################################
## segmentation.R
## created: 2019-01-04
## creator: Michael Scherer
## ---------------------------------------------------------------------------------------------------------------------
## Functions for segmentation of the methylome through MethylSeekR
########################################################################################################################
#' rnb.execute.segmentation
#'
#' This function computes methylation segmentation by MethylSeekR into PMDs, UMRs/LMRs, and HMDs. It is recommened to only
#' execute this function on WGBS data (with coverage >=10 according to the developer's recommendation), but could also be
#' used with RRBS_HaeIII without guarantee and the results should be interpreted carefully.
#'
#' @param rnb.set An object of type \code{\link{RnBiseqSet-class}} containing methylation and coverage information.
#' @param sample.name The sample for which segmentation is to be executed. Segemntation can only be exectued for each sample
#' individually.
#' @param meth.level Methylation cutoff to be used in UMR/LMR computation
#' @param fdr False discovery rate cutoff to be used in percent
#' @param min.cover The coverage threshold
#' @param n.cores The number of cores available for analysis
#' @param chr.sel Selected chromosome for model training in "chrAB" format. Defaults to "chr2".
#' @param plot.path Location on disk on which diagnostic plots are to be stored. Defaults to the working directory.
#' @param temp.dir The temporary directory. Defaults to the R temporary directory.
#' @return The input RnBSet object with segementation added as an additional region type. Furthermore, three new annotations
#' are set globally containing segmentation into PMDs, UMRs/LMRs, and HMDs for the sample that was specified.
#' @details For further descriptions on the methods, see \code{MethylSeekR}-documentation. The new annotations can be accessed
#' via \code{rnb.get.annotation("[PMDs,UMRs,LMRs,HMDs]_[sample.name]")}.
#' @references 1. Burger, Lukas, Gaidatzis, Dimos, Schuebeler, Dirk, and Stadler, Michael B. (2013)
#' Identification of active regulatory regions from DNA methylation data.
#' Nucleic Acids Research 41(16):e155.
#' @author Michael Scherer, based on a script by Abdulrahman Salhab
#' @export
rnb.execute.segmentation <- function(rnb.set,
sample.name,
meth.level=0.5,
fdr=5,
min.cover=5,
n.cores=1,
chr.sel="chr2",
plot.path=getwd(),
temp.dir=tempdir()){
if(!inherits(rnb.set,"RnBiseqSet")){
logger.error("Invalid value for rnb.set, needs to be RnBiseqSet")
}
if(length(sample.name)>1){
logger.error("Only single sample can be analysed")
}
rnb.require("MethylSeekR")
asb <- assembly(rnb.set)
if(asb %in% c("hg19","hg38")){
rnb.require(paste0("BSgenome.Hsapiens.UCSC.",asb))
myGenomeSeq <- Hsapiens
}else if(asb %in% "mm10"){
rnb.require(paste0("BSgenome.Mmusculus.UCSC.",asb))
myGenomeSeq <- Mmusculus
}else{
logger.info("Invalid assembly; Segmentation only supported for hg19, hg38 and mm10")
}
sLengths <- seqlengths(rnb.get.annotation("CpG",assembly = asb))
sLengths.gr <- GRanges(Rle(names(sLengths)),IRanges(start = 1,end=sLengths))
CpGislands.gr <- rnb.get.annotation("cpgislands",assembly = asb)
CpGislands.gr <-suppressWarnings(resize(CpGislands.gr, 5000, fix="center"))
session <- browserSession(url = 'http://genome-euro.ucsc.edu/cgi-bin/')
genome(session) <- asb
query <- ucscTableQuery(session, table="gap")
gaps <- getTable(query)
gaps.gr <- makeGRangesFromDataFrame(gaps, starts.in.df.are.0based=TRUE) # the second argument to be discussed 0/1 based
if(any(!(rnb.region.types.for.analysis(rnb.set) %in% rnb.region.types(assembly(rnb.set))))){
rnb.load.annotation.from.db(rnb.region.types.for.analysis(rnb.set)[!(rnb.region.types.for.analysis(rnb.set) %in% rnb.region.types(assembly(rnb.set)))],assembly(rnb.set))
}
sel.sample <- samples(rnb.set) %in% sample.name
if(!any(sel.sample)){
logger.error(paste("Specified sample",sample.name,"not in RnBSet"))
}
sel.sample <- which(sel.sample)
meth.rnb <- rnb.set@meth.sites[,sel.sample]
is.na.meth <- is.na(meth.rnb)
covg.rnb <- rnb.set@covg.sites[,sel.sample]
meth.matrix <- round(meth.rnb*covg.rnb)
nas <- is.na(covg.rnb) | is.na.meth
anno.rnb <- data.frame2GRanges(annotation(rnb.set),assembly=assembly(rnb.set))
anno.rnb <- sort(anno.rnb)
anno.rnb <- anno.rnb[!nas]
tmp.anno <- anno.rnb
values(tmp.anno) <- data.frame(T=covg.rnb[!nas],M=meth.matrix[!nas])
tmp.file.meth <- file.path(temp.dir,"GRanges_for_MethylSeekR.RDS")
saveRDS(tmp.anno,tmp.file.meth)
data.gr <- readMethylome(tmp.file.meth, seqLengths=sLengths, format="GRanges")
### read SNPs
anno.rnb <- anno.rnb[!is.na(values(anno.rnb)$SNPs)]
values(anno.rnb) <- values(anno.rnb)$SNPs
tmp.file.snps <- file.path(temp.dir,"GRangesSNP_for_MethylSeekR.RDS")
saveRDS(anno.rnb,tmp.file.snps)
snps.gr <- readSNPTable(tmp.file.snps, seqLengths=sLengths, format="GRanges")
### removing SNPs
if(length(snps.gr)>0){
cat("Filtering the SNPs ......\n")
data.gr <- removeSNPs(data.gr, snps.gr)
}
### find PMD and plot
logger.start("Detecting PMDs")
PMDsegments.gr <- segmentPMDs(m=data.gr,pdfFilename=file.path(plot.path,paste(sample.name,"alpha.model.fit.pdf",sep=".")), chr.sel=chr.sel,seqLengths=sLengths, num.cores=n.cores)
logger.completed()
logger.start("Plotting alpha distribution")
plotAlphaDistributionOneChr(m=data.gr, chr.sel=chr.sel,pdfFilename=file.path(plot.path,paste(sample.name,"alpha_distribution.pdf",sep=".")),num.cores=n.cores)
logger.completed()
### FDR calculation
logger.start("FDR calculation")
stats <- calculateFDRs(m=data.gr, CGIs=CpGislands.gr,PMDs=PMDsegments.gr, nCpG.cutoffs =seq(1, 17, by=3),pdfFilename=file.path(plot.path,paste(sample.name,"FDR.pdf",sep=".")),num.cores=n.cores)
FDR.cutoff <- as.numeric(fdr)
m.sel <- as.numeric(meth.level)
n.sel <- as.integer(names(stats$FDRs[as.character(m.sel), ][stats$FDRs[as.character(m.sel), ]<FDR.cutoff])[1])
logger.info(paste("Minimum number of CpGs in LMRs:",n.sel,"CpGs"))
logger.completed()
### find UMR and LMR
logger.start("Detecting UMRs and LMRs")
UMRLMRsegments.gr <- segmentUMRsLMRs(m=data.gr, meth.cutoff=m.sel,nCpG.cutoff=n.sel, PMDs=PMDsegments.gr,pdfFilename=file.path(plot.path,paste(sample.name,"UMR.LMR.scatter.pdf",sep=".")),num.cores=n.cores, myGenomeSeq=myGenomeSeq,seqLengths=sLengths, minCover = min.cover)
logger.completed()
# create final segmentation
logger.start("Create final segmentation")
PMDsegments.gr <- PMDsegments.gr[PMDsegments.gr$type=="PMD"]
PMDsegments.gr <- setdiff(PMDsegments.gr,gaps.gr)
PMDsegments.gr$type <- "PMD"
hmr.segments<- setdiff(sLengths.gr,c(PMDsegments.gr,UMRLMRsegments.gr,gaps.gr))
values(hmr.segments)$HMR <- rep("HMR",length(hmr.segments))
logger.completed()
# set new annotations PMD, UMR/LMR, HMR
logger.start("Set new annotations and summarize methylation")
pmd.frame <- data.frame(Chromosome=seqnames(PMDsegments.gr),Start=start(PMDsegments.gr),End=end(PMDsegments.gr),
PMDs=values(PMDsegments.gr)$type)
rnb.set.annotation(paste0("PMDs_",sample.name),regions=pmd.frame,description = "Partially Methylated Domains by MethylSeekR",assembly = asb)
umr.lmr.frame <- data.frame(Chromosome=seqnames(UMRLMRsegments.gr),Start=start(UMRLMRsegments.gr),End=end(UMRLMRsegments.gr),
UMRsLMRs=values(UMRLMRsegments.gr)$type)
umr.frame <- umr.lmr.frame[umr.lmr.frame$UMRsLMRs=="UMR",]
rnb.set.annotation(paste0("UMRs_",sample.name),regions=umr.frame,description = "Unmethylated Regions by MethylSeekR",assembly = asb)
lmr.frame <- umr.lmr.frame[umr.lmr.frame$UMRsLMRs=="LMR",]
rnb.set.annotation(paste0("LMRs_",sample.name),regions=lmr.frame,description = "Lowly Methylated Regions by MethylSeekR",assembly = asb)
hmr.frame <- data.frame(Chromosome=seqnames(hmr.segments),Start=start(hmr.segments),End=end(hmr.segments),
HMDs=values(hmr.segments)$HMR)
rnb.set.annotation(paste0("HMDs_",sample.name),regions=hmr.frame,description = "Highly Methylated Regions by MethylSeekR",assembly = asb)
rnb.set <- summarize.regions(rnb.set,paste("PMDs",sample.name,sep="_"))
rnb.set <- summarize.regions(rnb.set,paste("UMRs",sample.name,sep="_"))
rnb.set <- summarize.regions(rnb.set,paste("LMRs",sample.name,sep="_"))
rnb.set <- summarize.regions(rnb.set,paste("HMDs",sample.name,sep="_"))
logger.completed()
unlink(tmp.file.meth)
unlink(tmp.file.snps)
return(rnb.set)
}
#' rnb.bed.from.segmentation
#'
#' This function creates a BED file from the segmentation result of \code{rnb.execute.segmentation} and stores it on disk.
#'
#' @param rnb.set An \code{\link{RnBSet-class}} object obtained by executing \code{rnb.execute.segmentation}.
#' @param sample.name The sample name for which segmentation was computed.
#' @param type The type of segmentation (\code{PMDs}, \code{UMRs}, \code{LMRs}, \code{HMDs} or \code{final}).
#' @param store.path Path to which the BED file is to be stored.
#' @author Michael Scherer
#' @export
rnb.bed.from.segmentation <- function(rnb.set,
sample.name,
type="final",
store.path=getwd()){
if(!type %in% c("PMDs","UMRs","LMRs","HMDs","final")){
logger.error("Invalid value for type, needs to be PMDs, UMRs, LMRs or HMDs.")
}
if(!(sample.name %in% samples(rnb.set))){
logger.error("Specify a sample that is available in the rnb.set")
}
if(type != "final"){
region.name <- paste(type,sample.name,sep = "_")
if(!(region.name %in% summarized.regions(rnb.set))){
logger.error("Segmentation not yet available, execute rnb.execute.segementation first")
}
bed.frame <- annotation(rnb.set,region.name)
meth.seg <- meth(rnb.set,region.name)[,sample.name]
bed.frame <- data.frame(bed.frame[,c("Chromosome","Start","End",type)],AvgMeth=meth.seg)
}else{
bed.frame <- rnb.final.segmentation(rnb.set,sample.name)
}
write.table(bed.frame,file.path(store.path,paste0(sample.name,"_",type,".bed")),sep="\t",row.names=F,col.names=F,quote = F)
}
#' rnb.boxplot.from.segmentation
#'
#' This function creates a boxplot from the segmentation result of \code{rnb.execute.segmentation}.
#'
#' @param rnb.set An \code{\link{RnBSet-class}} object obtained by executing \code{rnb.execute.segmentation}.
#' @param sample.name The sample name for which segmentation was computed.
#' @param type The type of segmentation (\code{PMDs}, \code{UMRs}, \code{LMRs}, \code{HMDs} or \code{final}).
#' @return An object of type \code{ggplot} visualizing the methylation values in the segments.
#' @author Michael Scherer
#' @export
rnb.boxplot.from.segmentation <- function(rnb.set,
sample.name,
type="final"){
if(!type %in% c("PMDs","UMRs","LMRs","HMDs","final")){
logger.error("Invalid value for type, needs to be PMDs, UMRs, LMRs or HMDs.")
}
if(!(sample.name %in% samples(rnb.set))){
logger.error("Specify a sample that is available in the rnb.set")
}
if(type != "final"){
region.name <- paste(type,sample.name,sep = "_")
if(!(region.name %in% summarized.regions(rnb.set))){
logger.error("Segmentation not yet available, execute rnb.execute.segementation first")
}
bed.frame <- annotation(rnb.set,region.name)
meth.seg <- meth(rnb.set,region.name)[,sample.name]
to.plot <- data.frame(bed.frame[,type],AvgMeth=meth.seg)
colnames(to.plot)[1] <- "Segment"
}else{
to.plot <- rnb.final.segmentation(rnb.set,sample.name)
colnames(to.plot)[4] <- "Segment"
to.plot[,"Segment"] <- factor(to.plot[,"Segment"], levels=c("HMR","PMD","LMR","UMR"))
}
plot <- ggplot(to.plot,aes(x=Segment,y=AvgMeth,fill=Segment))+geom_boxplot()+scale_fill_manual(values=rnb.getOption("colors.category"))
return(plot)
}
#' rnb.final.segmentation
#'
#' This function creates a single segmentation, assigning each region to PMD, HMR, UMR or LMR.
#'
#' @param rnb.set The \code{\link{RnBSet-class}}-object, for which segmentation was computed using \code{\link{rnb.execute.segmentation}}
#' @param sample.name The sample name in \code{rnb.set} for which segmentation was conducted.
#' @author Michael Scherer
#' @noRd
rnb.final.segmentation <- function(rnb.set,
sample.name){
if(!(sample.name %in% samples(rnb.set))){
logger.error("Specify a sample that is available in the rnb.set")
}
region.names <- c(paste("PMDs",sample.name,sep = "_"),paste("HMDs",sample.name,sep = "_"),paste("UMRs",sample.name,sep = "_"),paste("LMRs",sample.name,sep = "_"))
if(any(!(region.names %in% summarized.regions(rnb.set)))){
logger.error("Segmentation not yet available, execute rnb.execute.segementation first")
}
pmd.frame <- annotation(rnb.set,region.names[1])
pmd.meth <- meth(rnb.set,region.names[1])[,sample.name]
pmd.frame <- data.frame(pmd.frame,AvgMeth=pmd.meth)
colnames(pmd.frame)[5] <- "Segment"
hmr.frame <- annotation(rnb.set,region.names[2])
hmr.meth <- meth(rnb.set,region.names[2])[,sample.name]
hmr.frame <- data.frame(hmr.frame,AvgMeth=hmr.meth)
colnames(hmr.frame)[5] <- "Segment"
umr.frame <- annotation(rnb.set,region.names[3])
umr.meth <- meth(rnb.set,region.names[3])[,sample.name]
umr.frame <- data.frame(umr.frame,AvgMeth=umr.meth)
colnames(umr.frame)[5] <- "Segment"
lmr.frame <- annotation(rnb.set,region.names[4])
lmr.meth <- meth(rnb.set,region.names[4])[,sample.name]
lmr.frame <- data.frame(lmr.frame,AvgMeth=lmr.meth)
colnames(lmr.frame)[5] <- "Segment"
final.frame <- data.frame(rbind(pmd.frame,rbind(hmr.frame,umr.frame,lmr.frame)))
final.frame <- final.frame[order(final.frame$Chromosome,final.frame$Start,final.frame$End),]
color.code <- rep("202,0,32",nrow(final.frame))
color.code[final.frame$Segment %in% "PMD"] <- "244,165,130"
color.code[final.frame$Segment %in% "UMR"] <- "5,113,176"
color.code[final.frame$Segment %in% "LMR"] <- "146,197,222"
final.frame <- data.frame(final.frame[,c(1,2,3,5,6)],rep(".",nrow(final.frame)),final.frame[,c(2,3)],color.code)
return(final.frame)
}
#' rnb.plot.segmentation.final
#'
#' This functions plots the final segmentation result.
#'
#' @param data.gr The data object as \code{\link{GRanges}} object
#' @param UMR.LMR.segments.gr Segmentation into UMR/LMR as GRanges
#' @param PMD.segments Segmentation into PMDs/notPMDs as GRanges
#' @param n.regions Number of regions
#' @param meth.cutoff The methylation cutoff
#' @author Michael Scherer
#' @noRd
rnb.plot.segmentation.final <- function(data.gr,
UMR.LMR.segments.gr,
PMD.segments,
n.regions=4,
meth.cutoff){
logger.start("Plotting final segmentation")
plotFinalSegmentation(m=data.gr, segs=UMR.LMR.segments.gr,PMDs=PMD.segments,numRegions = n.regions,meth.cutoff=meth.cutoff)
logger.completed()
}
#'rnb.plot.segmentation.distributions
#'
#'Plots the distributions of methylation and coverage.
#'
#'@param data.gr The data object as \code{\link{GRanges}} object
#'@author Michael Scherer
#'@noRd
rnb.plot.segmentation.distributions <- function(data.gr){
df <- as.data.frame(data.gr)
df$meth <- df$M/df$T
meth.plot <- ggplot(df[df$T>=5,], aes(x=df[df$T>=5,"meth"])) + geom_density(colour="dodgerblue1",size=1) + ylab("density") + xlab("beta value") + ggtitle("Methylation level density")
covg.plot <- ggplot(df, aes(x=df$T)) + geom_histogram(binwidth=1,alpha=.5,position="identity",colour = "dodgerblue1", fill = "dodgerblue1") + geom_vline(xintercept=mean(df$T),colour="black", linetype = "longdash") + ylab("Frequency") + xlab("read coverage per CpG") + geom_text(aes(x2,y2,label = texthere),data.frame(x2=mean(df$T), y2=max(table(df$T)), texthere=round(mean(df$T),2)))
return((list(Methylation=meth.plot,Coverage=covg.plot)))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_page_range.R
\name{get_page_range}
\alias{get_page_range}
\title{get_page_range}
\usage{
get_page_range(
country = NULL,
branch = NULL,
type = NULL,
operator_force = NULL,
query = NULL,
environment = NULL,
post_date = NULL,
start_date = NULL,
event_type = NULL,
market = NULL,
end_user_country = NULL,
overall_family = NULL,
endpoint = c("inventories", "equipment", "orbats", "news", "bases", "airports",
"countryrisks", "companies", "events", "equipmentrelationships", "references",
"samsites", "ewsites", "satelliteImages", "marketforecasts", "nuclearsites")
)
}
\arguments{
\item{country}{Country filter for news}
\item{branch}{Military branch}
\item{type}{Depends on endpoint}
\item{operator_force}{Operator force}
\item{query}{Query}
\item{environment}{Of search, i.e. "Air"}
\item{post_date}{Event post date}
\item{start_date}{Event start date}
\item{event_type}{Event type - JTIC or Intel Event}
\item{market}{Markets Forecast market}
\item{end_user_country}{JMF end user country}
\item{overall_family}{Overall equipment family}
\item{endpoint}{One of 6 options currently}
}
\value{
Janes page ranges for a given search.
}
\description{
Pulls Janes page ranges for all data endpoints. Helper function
}
|
/man/get_page_range.Rd
|
no_license
|
cgpeltier/janes
|
R
| false
| true
| 1,338
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_page_range.R
\name{get_page_range}
\alias{get_page_range}
\title{get_page_range}
\usage{
get_page_range(
country = NULL,
branch = NULL,
type = NULL,
operator_force = NULL,
query = NULL,
environment = NULL,
post_date = NULL,
start_date = NULL,
event_type = NULL,
market = NULL,
end_user_country = NULL,
overall_family = NULL,
endpoint = c("inventories", "equipment", "orbats", "news", "bases", "airports",
"countryrisks", "companies", "events", "equipmentrelationships", "references",
"samsites", "ewsites", "satelliteImages", "marketforecasts", "nuclearsites")
)
}
\arguments{
\item{country}{Country filter for news}
\item{branch}{Military branch}
\item{type}{Depends on endpoint}
\item{operator_force}{Operator force}
\item{query}{Query}
\item{environment}{Of search, i.e. "Air"}
\item{post_date}{Event post date}
\item{start_date}{Event start date}
\item{event_type}{Event type - JTIC or Intel Event}
\item{market}{Markets Forecast market}
\item{end_user_country}{JMF end user country}
\item{overall_family}{Overall equipment family}
\item{endpoint}{One of 6 options currently}
}
\value{
Janes page ranges for a given search.
}
\description{
Pulls Janes page ranges for all data endpoints. Helper function
}
|
## ----options, echo=FALSE-------------------------------------------------
opts_chunk$set(comment=NA, fig.width=6, fig.height=5, size='tiny', out.width='0.6\\textwidth', fig.align='center', message=FALSE)
library(plyr)
library(ggplot2)
library(xtable)
## ----bernoulli, echo=FALSE-----------------------------------------------
p = .5
res = ddply(data.frame(n=10^(2:4)), .(n),
function(x) rdply(1000, { y = rbinom(x$n, 1, p); data.frame(x = (mean(y)-p)/(sd(y)/sqrt(x$n))) }))
ggplot(res, aes(x=x)) + geom_histogram(aes(y=..density..), alpha=0.4) + stat_function(fun=dnorm, col="red") + facet_wrap(~n)
## ----rustyd_leaves_data, results='asis', echo=FALSE----------------------
d = data.frame(year1=c(38,10,84,36,50,35,73,48),
year2=c(32,16,57,28,55,12,61,29))
d$diff = with(d, year1-year2)
d$"diff>0" = (d$diff>0)*1
print(xtable(d, digits=0), include.rownames=FALSE)
## ----sign_test-----------------------------------------------------------
K = sum(d[,4])
n = nrow(d)
sum(dbinom(K:8,8,.5))
## ----pvalue_visualization, echo=FALSE------------------------------------
base_plot <- function(...) {
xx = -1:10
plot(xx-.5,dbinom(xx,8,.5), type="s", ylab="Bin(8,.5) probability mass function",...)
segments(xx+.5, 0, xx+.5, dbinom(xx[-6],8,.5))
abline(h=0)
}
fill_plot <- function(x,...) {
rect(x-.5, 0, x+.5, dbinom(x,8,.5), col="red",...)
}
par(mfrow=c(1,3))
base_plot(main="H1: p<0.5")
fill_plot(0:K)
base_plot(main="H1: p!=0.5")
fill_plot(K:n)
fill_plot(0:(n-K))
base_plot(main="H1: p>0.5")
fill_plot(K:n)
## ----sign_test_approximation---------------------------------------------
Z = (K-n/2)/(sqrt(n/4))
1-pnorm(Z)
## ----sign_test_approximation_with_continuity correction------------------
Z = (K-n/2-1/2)/(sqrt(n/4))
1-pnorm(Z)
## ----continuity_correction, echo=FALSE-----------------------------------
par(mfrow=c(1,1))
base_plot(main="Continuity correction")
fill_plot(6:8)
curve(dnorm(x, n/2, sqrt(n/4)), add=TRUE)
abline(v=6)
## ----ranked_data, echo=FALSE, results='asis'-----------------------------
#Signed rank test
d$absdiff = abs(d$diff)
ordr = order(d$absdiff)
d = d[ordr,]
d$rank = rank(d$absdiff)
#d$rank = as.character(d$rank)
tab = xtable(d, digits=c(NA,0,0,0,0,0,1))
print(tab, include.rownames=FALSE)
## ----signed_rank_test----------------------------------------------------
# By hand
S = sum(d$rank[d$"diff>0"==1])
n = nrow(d)
ES = n*(n+1)/4
SDS = sqrt(n*(n+1)*(2*n+1)/24)
z = (S-ES-0.5)/SDS
1-pnorm(z)
# Using a function
wilcox.test(d$year1, d$year2, paired=T)
## ----mpg, echo=FALSE-----------------------------------------------------
mpg = read.csv("mpg.csv")
ss = ddply(mpg, .(country), summarize, mn=mean(mpg), sd=sd(mpg))
attach(ss)
ggplot(mpg, aes(x=mpg))+
geom_histogram(aes(y=..density..), data=subset(mpg,country=="Japan"), fill="red", alpha=0.5)+
geom_histogram(aes(y=..density..), data=subset(mpg,country=="US"), fill="blue", alpha=0.5)+
stat_function(fun=function(x) dnorm(x,mn[1],sd[1]), colour="red")+
stat_function(fun=function(x) dnorm(x,mn[2],sd[2]), colour="blue")
## ----mpg_small, echo=FALSE, results='asis'-------------------------------
set.seed(2)
id = sample(nrow(mpg),9)
sm = mpg[id,]
ordr = order(sm$mpg)
sm = sm[ordr,]
sm$mpg[5] = 26 # make tie
sm$rank = rank(sm$mpg)
rownames(sm) = 1:nrow(sm)
tab = xtable(sm, digits=c(NA,0,NA,1))
print(tab, include.rownames=FALSE)
## ----mpg_small_by_hand---------------------------------------------------
n1 = sum(sm$country=="Japan")
n2 = sum(sm$country=="US")
U = sum(sm$rank[sm$country=="Japan"])
EU = n1*mean(sm$rank)
SDU = sd(sm$rank) * sqrt(n1*n2/(n1+n2))
Z = (U-.5-EU)/SDU
2*pnorm(-Z)
wilcox.test(mpg~country, sm)
## ----visual_representation, echo=FALSE-----------------------------------
ordr = order(mpg$mpg)
mpg.ordered = mpg[ordr,]
par(mar=c(5,4,0,0)+.1)
plot(mpg.ordered$mpg, 1:nrow(mpg), col=mpg.ordered$country, pch=19, xlab="MPG", cex=0.7, ylab="Rank")
legend("topleft", c("Japan","US"), col=1:2, pch=19)
## ----wilcoxon_rank_sum_test----------------------------------------------
wilcox.test(mpg~country,mpg)
|
/courses/stat587Ag/slides/Ch04.R
|
no_license
|
jarad/jarad.github.com
|
R
| false
| false
| 4,111
|
r
|
## ----options, echo=FALSE-------------------------------------------------
opts_chunk$set(comment=NA, fig.width=6, fig.height=5, size='tiny', out.width='0.6\\textwidth', fig.align='center', message=FALSE)
library(plyr)
library(ggplot2)
library(xtable)
## ----bernoulli, echo=FALSE-----------------------------------------------
p = .5
res = ddply(data.frame(n=10^(2:4)), .(n),
function(x) rdply(1000, { y = rbinom(x$n, 1, p); data.frame(x = (mean(y)-p)/(sd(y)/sqrt(x$n))) }))
ggplot(res, aes(x=x)) + geom_histogram(aes(y=..density..), alpha=0.4) + stat_function(fun=dnorm, col="red") + facet_wrap(~n)
## ----rustyd_leaves_data, results='asis', echo=FALSE----------------------
d = data.frame(year1=c(38,10,84,36,50,35,73,48),
year2=c(32,16,57,28,55,12,61,29))
d$diff = with(d, year1-year2)
d$"diff>0" = (d$diff>0)*1
print(xtable(d, digits=0), include.rownames=FALSE)
## ----sign_test-----------------------------------------------------------
K = sum(d[,4])
n = nrow(d)
sum(dbinom(K:8,8,.5))
## ----pvalue_visualization, echo=FALSE------------------------------------
base_plot <- function(...) {
xx = -1:10
plot(xx-.5,dbinom(xx,8,.5), type="s", ylab="Bin(8,.5) probability mass function",...)
segments(xx+.5, 0, xx+.5, dbinom(xx[-6],8,.5))
abline(h=0)
}
fill_plot <- function(x,...) {
rect(x-.5, 0, x+.5, dbinom(x,8,.5), col="red",...)
}
par(mfrow=c(1,3))
base_plot(main="H1: p<0.5")
fill_plot(0:K)
base_plot(main="H1: p!=0.5")
fill_plot(K:n)
fill_plot(0:(n-K))
base_plot(main="H1: p>0.5")
fill_plot(K:n)
## ----sign_test_approximation---------------------------------------------
Z = (K-n/2)/(sqrt(n/4))
1-pnorm(Z)
## ----sign_test_approximation_with_continuity correction------------------
Z = (K-n/2-1/2)/(sqrt(n/4))
1-pnorm(Z)
## ----continuity_correction, echo=FALSE-----------------------------------
par(mfrow=c(1,1))
base_plot(main="Continuity correction")
fill_plot(6:8)
curve(dnorm(x, n/2, sqrt(n/4)), add=TRUE)
abline(v=6)
## ----ranked_data, echo=FALSE, results='asis'-----------------------------
#Signed rank test
d$absdiff = abs(d$diff)
ordr = order(d$absdiff)
d = d[ordr,]
d$rank = rank(d$absdiff)
#d$rank = as.character(d$rank)
tab = xtable(d, digits=c(NA,0,0,0,0,0,1))
print(tab, include.rownames=FALSE)
## ----signed_rank_test----------------------------------------------------
# By hand
S = sum(d$rank[d$"diff>0"==1])
n = nrow(d)
ES = n*(n+1)/4
SDS = sqrt(n*(n+1)*(2*n+1)/24)
z = (S-ES-0.5)/SDS
1-pnorm(z)
# Using a function
wilcox.test(d$year1, d$year2, paired=T)
## ----mpg, echo=FALSE-----------------------------------------------------
mpg = read.csv("mpg.csv")
ss = ddply(mpg, .(country), summarize, mn=mean(mpg), sd=sd(mpg))
attach(ss)
ggplot(mpg, aes(x=mpg))+
geom_histogram(aes(y=..density..), data=subset(mpg,country=="Japan"), fill="red", alpha=0.5)+
geom_histogram(aes(y=..density..), data=subset(mpg,country=="US"), fill="blue", alpha=0.5)+
stat_function(fun=function(x) dnorm(x,mn[1],sd[1]), colour="red")+
stat_function(fun=function(x) dnorm(x,mn[2],sd[2]), colour="blue")
## ----mpg_small, echo=FALSE, results='asis'-------------------------------
set.seed(2)
id = sample(nrow(mpg),9)
sm = mpg[id,]
ordr = order(sm$mpg)
sm = sm[ordr,]
sm$mpg[5] = 26 # make tie
sm$rank = rank(sm$mpg)
rownames(sm) = 1:nrow(sm)
tab = xtable(sm, digits=c(NA,0,NA,1))
print(tab, include.rownames=FALSE)
## ----mpg_small_by_hand---------------------------------------------------
n1 = sum(sm$country=="Japan")
n2 = sum(sm$country=="US")
U = sum(sm$rank[sm$country=="Japan"])
EU = n1*mean(sm$rank)
SDU = sd(sm$rank) * sqrt(n1*n2/(n1+n2))
Z = (U-.5-EU)/SDU
2*pnorm(-Z)
wilcox.test(mpg~country, sm)
## ----visual_representation, echo=FALSE-----------------------------------
ordr = order(mpg$mpg)
mpg.ordered = mpg[ordr,]
par(mar=c(5,4,0,0)+.1)
plot(mpg.ordered$mpg, 1:nrow(mpg), col=mpg.ordered$country, pch=19, xlab="MPG", cex=0.7, ylab="Rank")
legend("topleft", c("Japan","US"), col=1:2, pch=19)
## ----wilcoxon_rank_sum_test----------------------------------------------
wilcox.test(mpg~country,mpg)
|
context("Test leave-like functions")
test_that("functions 'leaves()' and 'is_leafnode()' work properly", {
expect_identical(list(), leaves(empty_tree()))
tr0 = c_("Bob", "Carl", "Daniel")
expect_identical(list(r_("Daniel")), leaves(tr0))
expect_false(is_leafnode("Bob", tr0))
expect_false(is_leafnode("Carl", tr0))
expect_false(is_leafnode("TOTO", tr0))
expect_true(is_leafnode("Daniel", tr0))
tr1 = r_("Dimitri", s = list(c_("Enoc"), c_("Ferdinand")))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
expect_false(is_leafnode("Dimitri", tr1))
expect_false(is_leafnode("TOTO", tr1))
expect_true(is_leafnode("Enoc", tr1))
expect_true(is_leafnode("Ferdinand", tr1))
tr1 = r_("Caroline", s = list(tr1))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
expect_false(is_leafnode("Caroline", tr1))
expect_false(is_leafnode("Dimitri", tr1))
expect_false(is_leafnode("TOTO", tr1))
expect_true(is_leafnode("Enoc", tr1))
expect_true(is_leafnode("Ferdinand", tr1))
tr1 = r_("Bill", s = list(tr1))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
expect_false(is_leafnode("Bill", tr1))
expect_false(is_leafnode("Caroline", tr1))
expect_false(is_leafnode("Dimitri", tr1))
expect_false(is_leafnode("TOTO", tr1))
expect_true(is_leafnode("Enoc", tr1))
expect_true(is_leafnode("Ferdinand", tr1))
tr2 = r_("Alice", s = list(tr0, tr1))
expect_identical(list(r_("Daniel"), r_("Enoc"), r_("Ferdinand")), leaves(tr2))
expect_false(is_leafnode("Alice", tr2))
expect_false(is_leafnode("Bob", tr2))
expect_false(is_leafnode("Carl", tr2))
expect_false(is_leafnode("TOTO", tr2))
expect_true(is_leafnode("Daniel", tr2))
expect_false(is_leafnode("Bill", tr2))
expect_false(is_leafnode("Caroline", tr2))
expect_false(is_leafnode("Dimitri", tr2))
expect_false(is_leafnode("TOTO", tr2))
expect_true(is_leafnode("Enoc", tr2))
expect_true(is_leafnode("Ferdinand", tr2))
## Unrooted tree
tr3 = r_(s = list(tr2, c_("Grand-Mother", "Father", "Son")))
expect_identical(list(r_("Daniel"), r_("Enoc"), r_("Ferdinand"), r_("Son")), leaves(tr3))
expect_false(is_leafnode("Alice", tr3))
expect_false(is_leafnode("Bob", tr3))
expect_false(is_leafnode("Carl", tr3))
expect_false(is_leafnode("TOTO", tr3))
expect_true(is_leafnode("Daniel", tr3))
expect_false(is_leafnode("Bill", tr3))
expect_false(is_leafnode("Caroline", tr3))
expect_false(is_leafnode("Dimitri", tr3))
expect_false(is_leafnode("TOTO", tr3))
expect_true(is_leafnode("Enoc", tr3))
expect_true(is_leafnode("Ferdinand", tr3))
expect_false(is_leafnode("Grand-Mother", tr3))
expect_false(is_leafnode("Father", tr3))
expect_true(is_leafnode("Son", tr3))
})
test_that("function 'cut_leaves()' works properly", {
expect_identical(empty_tree(), cut_leaves(empty_tree()))
tr0 = c_("Bob", "Carl", "Daniel")
expect_identical(c_("Bob", "Carl"), cut_leaves(tr0))
tr1 = r_("Dimitri", s = list(c_("Enoc"), c_("Ferdinand")))
expect_identical(r_("Dimitri"), cut_leaves(tr1))
tr1 = r_("Caroline", s = list(tr1))
expect_identical(c_("Caroline", "Dimitri"), cut_leaves(tr1))
tr1 = r_("Bill", s = list(tr1))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
tr2 = r_("Alice", s = list(tr0, tr1))
expect_identical(r_("Alice", s = list(cut_leaves(tr0), cut_leaves(tr1))),
cut_leaves(tr2))
## Unrooted tree
tr3 = r_(s = list(tr2, c_("Grand-Mother", "Father", "Son")))
expect_identical(r_(s = list(cut_leaves(tr2), c_("Grand-Mother", "Father"))),
cut_leaves(tr3))
})
|
/tests/testthat/test-leaves.R
|
no_license
|
paulponcet/oak
|
R
| false
| false
| 3,658
|
r
|
context("Test leave-like functions")
test_that("functions 'leaves()' and 'is_leafnode()' work properly", {
expect_identical(list(), leaves(empty_tree()))
tr0 = c_("Bob", "Carl", "Daniel")
expect_identical(list(r_("Daniel")), leaves(tr0))
expect_false(is_leafnode("Bob", tr0))
expect_false(is_leafnode("Carl", tr0))
expect_false(is_leafnode("TOTO", tr0))
expect_true(is_leafnode("Daniel", tr0))
tr1 = r_("Dimitri", s = list(c_("Enoc"), c_("Ferdinand")))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
expect_false(is_leafnode("Dimitri", tr1))
expect_false(is_leafnode("TOTO", tr1))
expect_true(is_leafnode("Enoc", tr1))
expect_true(is_leafnode("Ferdinand", tr1))
tr1 = r_("Caroline", s = list(tr1))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
expect_false(is_leafnode("Caroline", tr1))
expect_false(is_leafnode("Dimitri", tr1))
expect_false(is_leafnode("TOTO", tr1))
expect_true(is_leafnode("Enoc", tr1))
expect_true(is_leafnode("Ferdinand", tr1))
tr1 = r_("Bill", s = list(tr1))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
expect_false(is_leafnode("Bill", tr1))
expect_false(is_leafnode("Caroline", tr1))
expect_false(is_leafnode("Dimitri", tr1))
expect_false(is_leafnode("TOTO", tr1))
expect_true(is_leafnode("Enoc", tr1))
expect_true(is_leafnode("Ferdinand", tr1))
tr2 = r_("Alice", s = list(tr0, tr1))
expect_identical(list(r_("Daniel"), r_("Enoc"), r_("Ferdinand")), leaves(tr2))
expect_false(is_leafnode("Alice", tr2))
expect_false(is_leafnode("Bob", tr2))
expect_false(is_leafnode("Carl", tr2))
expect_false(is_leafnode("TOTO", tr2))
expect_true(is_leafnode("Daniel", tr2))
expect_false(is_leafnode("Bill", tr2))
expect_false(is_leafnode("Caroline", tr2))
expect_false(is_leafnode("Dimitri", tr2))
expect_false(is_leafnode("TOTO", tr2))
expect_true(is_leafnode("Enoc", tr2))
expect_true(is_leafnode("Ferdinand", tr2))
## Unrooted tree
tr3 = r_(s = list(tr2, c_("Grand-Mother", "Father", "Son")))
expect_identical(list(r_("Daniel"), r_("Enoc"), r_("Ferdinand"), r_("Son")), leaves(tr3))
expect_false(is_leafnode("Alice", tr3))
expect_false(is_leafnode("Bob", tr3))
expect_false(is_leafnode("Carl", tr3))
expect_false(is_leafnode("TOTO", tr3))
expect_true(is_leafnode("Daniel", tr3))
expect_false(is_leafnode("Bill", tr3))
expect_false(is_leafnode("Caroline", tr3))
expect_false(is_leafnode("Dimitri", tr3))
expect_false(is_leafnode("TOTO", tr3))
expect_true(is_leafnode("Enoc", tr3))
expect_true(is_leafnode("Ferdinand", tr3))
expect_false(is_leafnode("Grand-Mother", tr3))
expect_false(is_leafnode("Father", tr3))
expect_true(is_leafnode("Son", tr3))
})
test_that("function 'cut_leaves()' works properly", {
expect_identical(empty_tree(), cut_leaves(empty_tree()))
tr0 = c_("Bob", "Carl", "Daniel")
expect_identical(c_("Bob", "Carl"), cut_leaves(tr0))
tr1 = r_("Dimitri", s = list(c_("Enoc"), c_("Ferdinand")))
expect_identical(r_("Dimitri"), cut_leaves(tr1))
tr1 = r_("Caroline", s = list(tr1))
expect_identical(c_("Caroline", "Dimitri"), cut_leaves(tr1))
tr1 = r_("Bill", s = list(tr1))
expect_identical(list(r_("Enoc"), r_("Ferdinand")), leaves(tr1))
tr2 = r_("Alice", s = list(tr0, tr1))
expect_identical(r_("Alice", s = list(cut_leaves(tr0), cut_leaves(tr1))),
cut_leaves(tr2))
## Unrooted tree
tr3 = r_(s = list(tr2, c_("Grand-Mother", "Father", "Son")))
expect_identical(r_(s = list(cut_leaves(tr2), c_("Grand-Mother", "Father"))),
cut_leaves(tr3))
})
|
testlist <- list(A = structure(c(2.31584307392677e+77, 9.53818252170339e+295, 1.22810536108123e+146, 4.12396251261199e-221, 0), .Dim = c(5L, 1L)), 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/1613112954-test.R
|
no_license
|
akhikolla/updatedatatype-list3
|
R
| false
| false
| 251
|
r
|
testlist <- list(A = structure(c(2.31584307392677e+77, 9.53818252170339e+295, 1.22810536108123e+146, 4.12396251261199e-221, 0), .Dim = c(5L, 1L)), B = structure(0, .Dim = c(1L, 1L)))
result <- do.call(multivariance:::match_rows,testlist)
str(result)
|
#Chapter 3 - analysis with spark
#Thomas Zwagerman
#06/08
#Libraries----
#Read in the library
library(sparklyr)
library(dplyr)
#connect to spark
sc <- spark_connect(master = "local", version = "2.3")
#import cars into spark
cars <- copy_to(sc, mtcars)
#Note: When using real clusters, you should use copy_to() to transfer only small tables from R;
#large data transfers should be performed with specialized data transfer tools.
#Wrangle----
summarize_all(cars, mean) %>%
show_query()
cars %>%
mutate(transmission = ifelse(am == 0, "automatic", "manual")) %>%
group_by(transmission) %>%
summarise_all(mean)
#Built-in functions
#functions that aren't in dplyr can still be passed on ie percentile() in this example
summarise(cars, mpg_percentile = percentile(mpg, 0.25)) %>%
show_query()
#another hive function is array()
summarise(cars, mpg_percentile = percentile(mpg, array(0.25, 0.5, 0.75)))
#can use the explode() function to seperate Spark's array values into their own record
summarise(cars, mpg_percentile = percentile(mpg, array(0.25, 0.5, 0.75))) %>%
mutate(mpg_percentile = explode(mpg_percentile))
|
/chapter_3_analysis.R
|
no_license
|
thomaszwagerman/learning_spark
|
R
| false
| false
| 1,132
|
r
|
#Chapter 3 - analysis with spark
#Thomas Zwagerman
#06/08
#Libraries----
#Read in the library
library(sparklyr)
library(dplyr)
#connect to spark
sc <- spark_connect(master = "local", version = "2.3")
#import cars into spark
cars <- copy_to(sc, mtcars)
#Note: When using real clusters, you should use copy_to() to transfer only small tables from R;
#large data transfers should be performed with specialized data transfer tools.
#Wrangle----
summarize_all(cars, mean) %>%
show_query()
cars %>%
mutate(transmission = ifelse(am == 0, "automatic", "manual")) %>%
group_by(transmission) %>%
summarise_all(mean)
#Built-in functions
#functions that aren't in dplyr can still be passed on ie percentile() in this example
summarise(cars, mpg_percentile = percentile(mpg, 0.25)) %>%
show_query()
#another hive function is array()
summarise(cars, mpg_percentile = percentile(mpg, array(0.25, 0.5, 0.75)))
#can use the explode() function to seperate Spark's array values into their own record
summarise(cars, mpg_percentile = percentile(mpg, array(0.25, 0.5, 0.75))) %>%
mutate(mpg_percentile = explode(mpg_percentile))
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/replicapool_functions.R
\name{replicas.delete}
\alias{replicas.delete}
\title{Deletes a replica from the pool.}
\usage{
replicas.delete(ReplicasDeleteRequest, projectName, zone, poolName, replicaName)
}
\arguments{
\item{ReplicasDeleteRequest}{The \link{ReplicasDeleteRequest} object to pass to this method}
\item{projectName}{The project ID for this request}
\item{zone}{The zone where the replica lives}
\item{poolName}{The replica pool name for this request}
\item{replicaName}{The name of the replica for this request}
}
\description{
Autogenerated via \code{\link[googleAuthR]{gar_create_api_skeleton}}
}
\details{
Authentication scopes used by this function are:
\itemize{
\item https://www.googleapis.com/auth/cloud-platform
\item https://www.googleapis.com/auth/ndev.cloudman
\item https://www.googleapis.com/auth/replicapool
}
Set \code{options(googleAuthR.scopes.selected = c(https://www.googleapis.com/auth/cloud-platform, https://www.googleapis.com/auth/ndev.cloudman, https://www.googleapis.com/auth/replicapool)}
Then run \code{googleAuthR::gar_auth()} to authenticate.
See \code{\link[googleAuthR]{gar_auth}} for details.
}
\seealso{
\href{https://developers.google.com/compute/docs/replica-pool/}{Google Documentation}
Other ReplicasDeleteRequest functions: \code{\link{ReplicasDeleteRequest}}
}
|
/googlereplicapoolv1beta1.auto/man/replicas.delete.Rd
|
permissive
|
Phippsy/autoGoogleAPI
|
R
| false
| true
| 1,399
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/replicapool_functions.R
\name{replicas.delete}
\alias{replicas.delete}
\title{Deletes a replica from the pool.}
\usage{
replicas.delete(ReplicasDeleteRequest, projectName, zone, poolName, replicaName)
}
\arguments{
\item{ReplicasDeleteRequest}{The \link{ReplicasDeleteRequest} object to pass to this method}
\item{projectName}{The project ID for this request}
\item{zone}{The zone where the replica lives}
\item{poolName}{The replica pool name for this request}
\item{replicaName}{The name of the replica for this request}
}
\description{
Autogenerated via \code{\link[googleAuthR]{gar_create_api_skeleton}}
}
\details{
Authentication scopes used by this function are:
\itemize{
\item https://www.googleapis.com/auth/cloud-platform
\item https://www.googleapis.com/auth/ndev.cloudman
\item https://www.googleapis.com/auth/replicapool
}
Set \code{options(googleAuthR.scopes.selected = c(https://www.googleapis.com/auth/cloud-platform, https://www.googleapis.com/auth/ndev.cloudman, https://www.googleapis.com/auth/replicapool)}
Then run \code{googleAuthR::gar_auth()} to authenticate.
See \code{\link[googleAuthR]{gar_auth}} for details.
}
\seealso{
\href{https://developers.google.com/compute/docs/replica-pool/}{Google Documentation}
Other ReplicasDeleteRequest functions: \code{\link{ReplicasDeleteRequest}}
}
|
#Load in required packages for functions below
require(qpcR)
require(plyr)
require(ggplot2)
require(splitstackshape)
#Read in raw fluorescence data from 1st Actin replicate
rep1<-read.csv("Actin3rawfluoro.csv", header = T)
#Remove blank first column entitled "X"
rep1$X<-NULL
#Rename columns so that qpcR package and appropriately handle the data
rep1<-rename(rep1, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
#Run data through pcrbatch in qpcR package which analyzes fluorescence and produces efficiency and cycle threshold values
rep1ct<-pcrbatch(rep1, fluo=NULL)
#pcrbatch creates a file with each sample as an individual column in the dataframe. The problem with this is
#that I want to compare all the Ct (labelled sig.cpD2) and generate expression data for them but these values have to be
#in individual columns. To do this I must transpose the data and set the first row as the column names.
rep1res<-setNames(data.frame(t(rep1ct)),rep1ct[,1])
#Now I must remove the first row as it is a duplicate and will cause errors with future analysis
rep1res<-rep1res[-1,]
#since the sample names are now in the first column the column title is row.names. This makes analys hard based on the ability to call the first column.
#to eliminate this issue, I copied the first column into a new column called "Names"
rep1res$Names<-rownames(rep1res)
#Since each sample name contains information such as Population, Treatment, and Sample Number I want to separate out these factors
#into new columns so that I can run future analysis based on population, treatment, or both. Also note the "drop = F" this is so the original names column remains.
rep1res2<-cSplit_f(rep1res, splitCols=c("Names"), sep="_", drop = F)
#After splitting the names column into three new columns I need to rename them appropriately.
rep1res2<-rename(rep1res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#I also create a column with the target gene name. This isn't used in this analysis but will be helpful for future work.
rep1res2$Gene<-rep("Actin", length(rep1res2))
#In transposing the data frame, the column entries became factors which cannot be used for equations.
#to fix this, I set the entries for sig.eff (efficiency) and sig.cpD2 (Ct value) to numeric. Be aware, without the as.character function the factors will be transformed inappropriately.
rep1res2$sig.eff<-as.numeric(as.character(rep1res2$sig.eff))
rep1res2$sig.cpD2<-as.numeric(as.character(rep1res2$sig.cpD2))
#Now I plot the Ct values to see how they align without converting them to expression.
ggplot(rep1res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
#Now I want to get expression information from my data set. qpcR has a way of doing this but its complicated and I'm not comfortable using it.
#Luckily there is an equation I can use to do it. The equation is expression = 1/(1+efficiency)^Ctvalue. I tried multiple ways to get this to work in R
#but it doesn't handle the complicated equation easily.
#To work around this, I created a function in R to run the equation and produce an outcome. x = efficiency argument, y=Ctvalue argument
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
#Now I run the data through the function and produce a useful expression value
rep1res2$expression<-expr(rep1res2$sig.eff, rep1res2$sig.cpD2)
#Graphing the expression values is a good way to examine the data quickly for errors that might have occurred.
ggplot(rep1res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Before I'm able to compare the replicates I need to process the raw fluorescence from the second Actin run.
#To do this I perform all the same steps as the previous replicate.
rep2<-read.csv("Actin4rawfluoro.csv", header = T)
rep2$X<-NULL
rep2<-rename(rep2, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
rep2ct<-pcrbatch(rep2, fluo=NULL)
rep2res<-setNames(data.frame(t(rep2ct)),rep2ct[,1])
rep2res<-rep2res[-1,]
rep2res$Names<-rownames(rep2res)
rep2res2<-cSplit_f(rep2res, splitCols=c("Names"), sep="_", drop = F)
rep2res2<-rename(rep2res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
rep2res2$Gene<-rep("Actin", length(rep2res2))
rep2res2$sig.eff<-as.numeric(as.character(rep2res2$sig.eff))
rep2res2$sig.cpD2<-as.numeric(as.character(rep2res2$sig.cpD2))
ggplot(rep2res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
rep2res2$expression<-expr(rep2res2$sig.eff, rep2res2$sig.cpD2)
ggplot(rep2res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Now that I have Ct values, efficiencies and expression values for both replicates I can create a table of the differences between reps.
#To do this I create a data frame with a single formula that creates a column of values generated by subtracting the first run from the second.
repcomp<-as.data.frame(rep1res2$sig.cpD2-rep2res2$sig.cpD2)
#Now I need to add some Names for the samples to use with ggplot.Since the names column contains all the relevant information
#I copy only that column and run the split function on it again as well as the rename function.
repcomp$Names<-rep1res2$Names
repcomp<-cSplit_f(repcomp, splitCols=c("Names"), sep="_", drop = F)
#To better address the difference column in ggplot I need to rename it something simple and short.
repcomp<-rename(repcomp, c("rep1res2$sig.cpD2 - rep2res2$sig.cpD2"="rep.diff", "Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#Now I just run the data through ggplot to generate a bar graph exploring the differences between the two replicate in terms of Ct values.
ggplot(repcomp, aes(x=Names, y=rep.diff, fill=Pop))+geom_bar(stat="identity")
#Read in raw fluorescence data from 1st Actin replicate
rep3<-read.csv("Actin1rawfluoro.csv", header = T)
#Remove blank first column entitled "X"
rep3$X<-NULL
#Rename columns so that qpcR package and appropriately handle the data
rep3<-rename(rep3, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
#Run data through pcrbatch in qpcR package which analyzes fluorescence and produces efficiency and cycle threshold values
rep3ct<-pcrbatch(rep3, fluo=NULL)
#pcrbatch creates a file with each sample as an individual column in the dataframe. The problem with this is
#that I want to compare all the Ct (labelled sig.cpD2) and generate expression data for them but these values have to be
#in individual columns. To do this I must transpose the data and set the first row as the column names.
rep3res<-setNames(data.frame(t(rep3ct)),rep3ct[,1])
#Now I must remove the first row as it is a duplicate and will cause errors with future analysis
rep3res<-rep3res[-1,]
#since the sample names are now in the first column the column title is row.names. This makes analys hard based on the ability to call the first column.
#to eliminate this issue, I copied the first column into a new column called "Names"
rep3res$Names<-rownames(rep3res)
#Since each sample name contains information such as Population, Treatment, and Sample Number I want to separate out these factors
#into new columns so that I can run future analysis based on population, treatment, or both. Also note the "drop = F" this is so the original names column remains.
rep3res2<-cSplit_f(rep3res, splitCols=c("Names"), sep="_", drop = F)
#After splitting the names column into three new columns I need to rename them appropriately.
rep3res2<-rename(rep3res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#I also create a column with the target gene name. This isn't used in this analysis but will be helpful for future work.
rep3res2$Gene<-rep("Actin", length(rep3res2))
#In transposing the data frame, the column entries became factors which cannot be used for equations.
#to fix this, I set the entries for sig.eff (efficiency) and sig.cpD2 (Ct value) to numeric. Be aware, without the as.character function the factors will be transformed inappropriately.
rep3res2$sig.eff<-as.numeric(as.character(rep3res2$sig.eff))
rep3res2$sig.cpD2<-as.numeric(as.character(rep3res2$sig.cpD2))
#Now I plot the Ct values to see how they align without converting them to expression.
ggplot(rep3res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
#Now I want to get expression information from my data set. qpcR has a way of doing this but its complicated and I'm not comfortable using it.
#Luckily there is an equation I can use to do it. The equation is expression = 1/(1+efficiency)^Ctvalue. I tried multiple ways to get this to work in R
#but it doesn't handle the complicated equation easily.
#To work around this, I created a function in R to run the equation and produce an outcome. x = efficiency argument, y=Ctvalue argument
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
#Now I run the data through the function and produce a useful expression value
rep3res2$expression<-expr(rep3res2$sig.eff, rep3res2$sig.cpD2)
#Graphing the expression values is a good way to examine the data quickly for errors that might have occurred.
ggplot(rep3res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Before I'm able to compare the replicates I need to process the raw fluorescence from the second Actin run.
#To do this I perform all the same steps as the previous replicate.
rep4<-read.csv("Actin2rawfluoro.csv", header = T)
rep4$X<-NULL
rep4<-rename(rep4, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
rep4ct<-pcrbatch(rep4, fluo=NULL)
rep4res<-setNames(data.frame(t(rep4ct)),rep4ct[,1])
rep4res<-rep4res[-1,]
rep4res$Names<-rownames(rep4res)
rep4res2<-cSplit_f(rep4res, splitCols=c("Names"), sep="_", drop = F)
rep4res2<-rename(rep4res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
rep4res2$Gene<-rep("Actin", length(rep4res2))
rep4res2$sig.eff<-as.numeric(as.character(rep4res2$sig.eff))
rep4res2$sig.cpD2<-as.numeric(as.character(rep4res2$sig.cpD2))
ggplot(rep4res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
rep4res2$expression<-expr(rep4res2$sig.eff, rep4res2$sig.cpD2)
ggplot(rep4res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Now that I have Ct values, efficiencies and expression values for both replicates I can create a table of the differences between reps.
#To do this I create a data frame with a single formula that creates a column of values generated by subtracting the first run from the second.
repcomp<-as.data.frame(rep3res2$sig.cpD2-rep4res2$sig.cpD2)
#Now I need to add some Names for the samples to use with ggplot.Since the names column contains all the relevant information
#I copy only that column and run the split function on it again as well as the rename function.
repcomp$Names<-rep3res2$Names
repcomp<-cSplit_f(repcomp, splitCols=c("Names"), sep="_", drop = F)
#To better address the difference column in ggplot I need to rename it something simple and short.
repcomp<-rename(repcomp, c("rep3res2$sig.cpD2 - rep4res2$sig.cpD2"="rep.diff", "Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#Now I just run the data through ggplot to generate a bar graph exploring the differences between the two replicate in terms of Ct values.
ggplot(repcomp, aes(x=Names, y=rep.diff, fill=Pop))+geom_bar(stat="identity")
actstandard<-as.data.frame(cbind(rep1res2$expression,rep1res2$Names,rep1res2$Pop,rep1res2$Treat,rep2res2$expression,rep3res2$expression,rep4res2$expression,rep1res2$sig.cpD2,rep2res2$sig.cpD2,rep3res2$sig.cpD2,rep4res2$sig.cpD2))
actstandard<-rename(actstandard, c(V1="rep1.expr","V2"="name","V3"="pop","V4"="treat"
,"V5"="rep2.expr","V6"="rep3.expr","V7"="rep4.expr",
"V8"="rep1.Ct","V9"="rep2.Ct","V10"="rep3.Ct","V11"="rep4.Ct"))
actstandard$rep1.expr<-as.numeric(as.character(actstandard$rep1.expr))
actstandard$rep2.expr<-as.numeric(as.character(actstandard$rep2.expr))
actstandard$rep3.expr<-as.numeric(as.character(actstandard$rep3.expr))
actstandard$rep4.expr<-as.numeric(as.character(actstandard$rep4.expr))
actstandard$avgexpr<-rowMeans(actstandard[,c("rep1.expr","rep2.expr","rep3.expr","rep4.expr")],na.rm=F)
actstandard<-actstandard[which(actstandard$pop!=c("NT")),]
ggplot(actstandard, aes(x=treat,y=avgexpr, fill=pop))+geom_boxplot()
ggplot(actstandard, aes(x=name, y=avgexpr, fill=pop))+geom_bar(stat="identity")
ggplot(actstandard, aes(x=pop,y=avgexpr, fill=pop))+geom_boxplot()
fit<-aov(avgexpr~pop+treat+pop:treat,data=actstandard)
fit
TukeyHSD(fit)
fit2<-aov(avgexpr ~ pop, data=actstandard[which(actstandard$treat == "C"), ])
fit2
TukeyHSD(fit2)
fit3<-aov(avgexpr~pop, data=actstandard[which(actstandard$treat == "T"), ])
fit3
TukeyHSD(fit3)
fit4<-t.test(avgexpr~treat, data=actstandard[which(actstandard$pop=="H"),])
fit4
fit5<-t.test(avgexpr~treat, data=actstandard[which(actstandard$pop=="N"),])
fit5
fit6<-t.test(avgexpr~treat, data=actstandard[which(actstandard$pop=="S"),])
fit6
|
/qPCR data/raw fluoro/actinstandard.R
|
no_license
|
jheare/Resilience-Project
|
R
| false
| false
| 17,002
|
r
|
#Load in required packages for functions below
require(qpcR)
require(plyr)
require(ggplot2)
require(splitstackshape)
#Read in raw fluorescence data from 1st Actin replicate
rep1<-read.csv("Actin3rawfluoro.csv", header = T)
#Remove blank first column entitled "X"
rep1$X<-NULL
#Rename columns so that qpcR package and appropriately handle the data
rep1<-rename(rep1, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
#Run data through pcrbatch in qpcR package which analyzes fluorescence and produces efficiency and cycle threshold values
rep1ct<-pcrbatch(rep1, fluo=NULL)
#pcrbatch creates a file with each sample as an individual column in the dataframe. The problem with this is
#that I want to compare all the Ct (labelled sig.cpD2) and generate expression data for them but these values have to be
#in individual columns. To do this I must transpose the data and set the first row as the column names.
rep1res<-setNames(data.frame(t(rep1ct)),rep1ct[,1])
#Now I must remove the first row as it is a duplicate and will cause errors with future analysis
rep1res<-rep1res[-1,]
#since the sample names are now in the first column the column title is row.names. This makes analys hard based on the ability to call the first column.
#to eliminate this issue, I copied the first column into a new column called "Names"
rep1res$Names<-rownames(rep1res)
#Since each sample name contains information such as Population, Treatment, and Sample Number I want to separate out these factors
#into new columns so that I can run future analysis based on population, treatment, or both. Also note the "drop = F" this is so the original names column remains.
rep1res2<-cSplit_f(rep1res, splitCols=c("Names"), sep="_", drop = F)
#After splitting the names column into three new columns I need to rename them appropriately.
rep1res2<-rename(rep1res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#I also create a column with the target gene name. This isn't used in this analysis but will be helpful for future work.
rep1res2$Gene<-rep("Actin", length(rep1res2))
#In transposing the data frame, the column entries became factors which cannot be used for equations.
#to fix this, I set the entries for sig.eff (efficiency) and sig.cpD2 (Ct value) to numeric. Be aware, without the as.character function the factors will be transformed inappropriately.
rep1res2$sig.eff<-as.numeric(as.character(rep1res2$sig.eff))
rep1res2$sig.cpD2<-as.numeric(as.character(rep1res2$sig.cpD2))
#Now I plot the Ct values to see how they align without converting them to expression.
ggplot(rep1res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
#Now I want to get expression information from my data set. qpcR has a way of doing this but its complicated and I'm not comfortable using it.
#Luckily there is an equation I can use to do it. The equation is expression = 1/(1+efficiency)^Ctvalue. I tried multiple ways to get this to work in R
#but it doesn't handle the complicated equation easily.
#To work around this, I created a function in R to run the equation and produce an outcome. x = efficiency argument, y=Ctvalue argument
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
#Now I run the data through the function and produce a useful expression value
rep1res2$expression<-expr(rep1res2$sig.eff, rep1res2$sig.cpD2)
#Graphing the expression values is a good way to examine the data quickly for errors that might have occurred.
ggplot(rep1res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Before I'm able to compare the replicates I need to process the raw fluorescence from the second Actin run.
#To do this I perform all the same steps as the previous replicate.
rep2<-read.csv("Actin4rawfluoro.csv", header = T)
rep2$X<-NULL
rep2<-rename(rep2, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
rep2ct<-pcrbatch(rep2, fluo=NULL)
rep2res<-setNames(data.frame(t(rep2ct)),rep2ct[,1])
rep2res<-rep2res[-1,]
rep2res$Names<-rownames(rep2res)
rep2res2<-cSplit_f(rep2res, splitCols=c("Names"), sep="_", drop = F)
rep2res2<-rename(rep2res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
rep2res2$Gene<-rep("Actin", length(rep2res2))
rep2res2$sig.eff<-as.numeric(as.character(rep2res2$sig.eff))
rep2res2$sig.cpD2<-as.numeric(as.character(rep2res2$sig.cpD2))
ggplot(rep2res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
rep2res2$expression<-expr(rep2res2$sig.eff, rep2res2$sig.cpD2)
ggplot(rep2res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Now that I have Ct values, efficiencies and expression values for both replicates I can create a table of the differences between reps.
#To do this I create a data frame with a single formula that creates a column of values generated by subtracting the first run from the second.
repcomp<-as.data.frame(rep1res2$sig.cpD2-rep2res2$sig.cpD2)
#Now I need to add some Names for the samples to use with ggplot.Since the names column contains all the relevant information
#I copy only that column and run the split function on it again as well as the rename function.
repcomp$Names<-rep1res2$Names
repcomp<-cSplit_f(repcomp, splitCols=c("Names"), sep="_", drop = F)
#To better address the difference column in ggplot I need to rename it something simple and short.
repcomp<-rename(repcomp, c("rep1res2$sig.cpD2 - rep2res2$sig.cpD2"="rep.diff", "Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#Now I just run the data through ggplot to generate a bar graph exploring the differences between the two replicate in terms of Ct values.
ggplot(repcomp, aes(x=Names, y=rep.diff, fill=Pop))+geom_bar(stat="identity")
#Read in raw fluorescence data from 1st Actin replicate
rep3<-read.csv("Actin1rawfluoro.csv", header = T)
#Remove blank first column entitled "X"
rep3$X<-NULL
#Rename columns so that qpcR package and appropriately handle the data
rep3<-rename(rep3, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
#Run data through pcrbatch in qpcR package which analyzes fluorescence and produces efficiency and cycle threshold values
rep3ct<-pcrbatch(rep3, fluo=NULL)
#pcrbatch creates a file with each sample as an individual column in the dataframe. The problem with this is
#that I want to compare all the Ct (labelled sig.cpD2) and generate expression data for them but these values have to be
#in individual columns. To do this I must transpose the data and set the first row as the column names.
rep3res<-setNames(data.frame(t(rep3ct)),rep3ct[,1])
#Now I must remove the first row as it is a duplicate and will cause errors with future analysis
rep3res<-rep3res[-1,]
#since the sample names are now in the first column the column title is row.names. This makes analys hard based on the ability to call the first column.
#to eliminate this issue, I copied the first column into a new column called "Names"
rep3res$Names<-rownames(rep3res)
#Since each sample name contains information such as Population, Treatment, and Sample Number I want to separate out these factors
#into new columns so that I can run future analysis based on population, treatment, or both. Also note the "drop = F" this is so the original names column remains.
rep3res2<-cSplit_f(rep3res, splitCols=c("Names"), sep="_", drop = F)
#After splitting the names column into three new columns I need to rename them appropriately.
rep3res2<-rename(rep3res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#I also create a column with the target gene name. This isn't used in this analysis but will be helpful for future work.
rep3res2$Gene<-rep("Actin", length(rep3res2))
#In transposing the data frame, the column entries became factors which cannot be used for equations.
#to fix this, I set the entries for sig.eff (efficiency) and sig.cpD2 (Ct value) to numeric. Be aware, without the as.character function the factors will be transformed inappropriately.
rep3res2$sig.eff<-as.numeric(as.character(rep3res2$sig.eff))
rep3res2$sig.cpD2<-as.numeric(as.character(rep3res2$sig.cpD2))
#Now I plot the Ct values to see how they align without converting them to expression.
ggplot(rep3res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
#Now I want to get expression information from my data set. qpcR has a way of doing this but its complicated and I'm not comfortable using it.
#Luckily there is an equation I can use to do it. The equation is expression = 1/(1+efficiency)^Ctvalue. I tried multiple ways to get this to work in R
#but it doesn't handle the complicated equation easily.
#To work around this, I created a function in R to run the equation and produce an outcome. x = efficiency argument, y=Ctvalue argument
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
#Now I run the data through the function and produce a useful expression value
rep3res2$expression<-expr(rep3res2$sig.eff, rep3res2$sig.cpD2)
#Graphing the expression values is a good way to examine the data quickly for errors that might have occurred.
ggplot(rep3res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Before I'm able to compare the replicates I need to process the raw fluorescence from the second Actin run.
#To do this I perform all the same steps as the previous replicate.
rep4<-read.csv("Actin2rawfluoro.csv", header = T)
rep4$X<-NULL
rep4<-rename(rep4, c("Cycle" = "Cycles", "A1" = "H_C_1", "A2" = "N_C_1",
"A3"= "S_C_1", "A4"="H_T_1", "A5"="N_T_1","A6"="S_T_1",
"A7"="NT_C_1","B1" = "H_C_2", "B2" = "N_C_2","B3"= "S_C_2",
"B4"="H_T_2", "B5"="N_T_2", "B6"="S_T_2","B7"="NT_C_2",
"C1" = "H_C_3", "C2" = "N_C_3","C3"= "S_C_3","C4"="H_T_3",
"C5"="N_T_3", "C6"="S_T_3", "C7"="NT_C_3","D1" = "H_C_4",
"D2" = "N_C_4","D3"= "S_C_4", "D4"="H_T_4", "D5"="N_T_4",
"D6"="S_T_4", "D7"="NT_C_4","E1" = "H_C_5", "E2" = "N_C_5",
"E3"= "S_C_5", "E4"="H_T_5", "E5"="N_T_5", "E6"="S_T_5",
"F1" = "H_C_6", "F2" = "N_C_6","F3"= "S_C_6", "F4"="H_T_6",
"F5"="N_T_6", "F6"="S_T_6","G1" = "H_C_7", "G2" = "N_C_7",
"G3"= "S_C_7", "G4"="H_T_7", "G5"="N_T_7", "G6"="S_T_7",
"H1" = "H_C_8", "H2" = "N_C_8","H3"= "S_C_8", "H4"="H_T_8",
"H5"="N_T_8", "H6"="S_T_8"))
rep4ct<-pcrbatch(rep4, fluo=NULL)
rep4res<-setNames(data.frame(t(rep4ct)),rep4ct[,1])
rep4res<-rep4res[-1,]
rep4res$Names<-rownames(rep4res)
rep4res2<-cSplit_f(rep4res, splitCols=c("Names"), sep="_", drop = F)
rep4res2<-rename(rep4res2, c("Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
rep4res2$Gene<-rep("Actin", length(rep4res2))
rep4res2$sig.eff<-as.numeric(as.character(rep4res2$sig.eff))
rep4res2$sig.cpD2<-as.numeric(as.character(rep4res2$sig.cpD2))
ggplot(rep4res2, aes(x=Names,y=sig.cpD2, fill=Pop))+geom_bar(stat="identity")
expr<-function(x,y){
newVar<-(1+x)^y
1/newVar
}
rep4res2$expression<-expr(rep4res2$sig.eff, rep4res2$sig.cpD2)
ggplot(rep4res2, aes(x=Names,y=expression, fill=Pop))+geom_bar(stat="identity")
#Now that I have Ct values, efficiencies and expression values for both replicates I can create a table of the differences between reps.
#To do this I create a data frame with a single formula that creates a column of values generated by subtracting the first run from the second.
repcomp<-as.data.frame(rep3res2$sig.cpD2-rep4res2$sig.cpD2)
#Now I need to add some Names for the samples to use with ggplot.Since the names column contains all the relevant information
#I copy only that column and run the split function on it again as well as the rename function.
repcomp$Names<-rep3res2$Names
repcomp<-cSplit_f(repcomp, splitCols=c("Names"), sep="_", drop = F)
#To better address the difference column in ggplot I need to rename it something simple and short.
repcomp<-rename(repcomp, c("rep3res2$sig.cpD2 - rep4res2$sig.cpD2"="rep.diff", "Names_1"="Pop", "Names_2"="Treat", "Names_3"="Sample"))
#Now I just run the data through ggplot to generate a bar graph exploring the differences between the two replicate in terms of Ct values.
ggplot(repcomp, aes(x=Names, y=rep.diff, fill=Pop))+geom_bar(stat="identity")
actstandard<-as.data.frame(cbind(rep1res2$expression,rep1res2$Names,rep1res2$Pop,rep1res2$Treat,rep2res2$expression,rep3res2$expression,rep4res2$expression,rep1res2$sig.cpD2,rep2res2$sig.cpD2,rep3res2$sig.cpD2,rep4res2$sig.cpD2))
actstandard<-rename(actstandard, c(V1="rep1.expr","V2"="name","V3"="pop","V4"="treat"
,"V5"="rep2.expr","V6"="rep3.expr","V7"="rep4.expr",
"V8"="rep1.Ct","V9"="rep2.Ct","V10"="rep3.Ct","V11"="rep4.Ct"))
actstandard$rep1.expr<-as.numeric(as.character(actstandard$rep1.expr))
actstandard$rep2.expr<-as.numeric(as.character(actstandard$rep2.expr))
actstandard$rep3.expr<-as.numeric(as.character(actstandard$rep3.expr))
actstandard$rep4.expr<-as.numeric(as.character(actstandard$rep4.expr))
actstandard$avgexpr<-rowMeans(actstandard[,c("rep1.expr","rep2.expr","rep3.expr","rep4.expr")],na.rm=F)
actstandard<-actstandard[which(actstandard$pop!=c("NT")),]
ggplot(actstandard, aes(x=treat,y=avgexpr, fill=pop))+geom_boxplot()
ggplot(actstandard, aes(x=name, y=avgexpr, fill=pop))+geom_bar(stat="identity")
ggplot(actstandard, aes(x=pop,y=avgexpr, fill=pop))+geom_boxplot()
fit<-aov(avgexpr~pop+treat+pop:treat,data=actstandard)
fit
TukeyHSD(fit)
fit2<-aov(avgexpr ~ pop, data=actstandard[which(actstandard$treat == "C"), ])
fit2
TukeyHSD(fit2)
fit3<-aov(avgexpr~pop, data=actstandard[which(actstandard$treat == "T"), ])
fit3
TukeyHSD(fit3)
fit4<-t.test(avgexpr~treat, data=actstandard[which(actstandard$pop=="H"),])
fit4
fit5<-t.test(avgexpr~treat, data=actstandard[which(actstandard$pop=="N"),])
fit5
fit6<-t.test(avgexpr~treat, data=actstandard[which(actstandard$pop=="S"),])
fit6
|
#' wrapper function of rmarkdown::render for opencpu to render a report for maxquant summary from markdown template
#'
#' This function is destined for working on the opencpu server end, accepting file posted by front end to produce an html file to send to the front end.
#' It also works in stand-alone mode, to generate a report file, output.html, using a public accessible rmd file on github. Of course, this need internet connection to run
#'
#' @param type string, type of the result to generate the report on, one of summary, peptides,proteingroups,taxon, function
#' @param file string, the file (path) of the summary.txt from maxquant result txt folder, mandatory
#' @param meta the file (path), optional,string is the tsv file, generated by MetaLab2.0, 1st columns as sample name, 2nd column as experiment name, 3rd column and after as grouping
#' @param template_version string, can be "latest","stable", or a specific number, like "1.0", "1.1". Default as "stable". Will use the local template in the package (system.file("rmd","MQ_report_summary.Rmd", package = "metareport")), otherwise, it will try to curl the corresponding file from the deposit from either gitlab/github. Besure to use the correct number. If the version defined does not exist, or failed to retrieve from the deposit, it will use the stable version instead.
#' @param output_format see output_format in render, default as html, which has interactivity with plotly support
#' @param output_dir see output_dir in render, default as the same path of the rmarkdown input
#'
#' @return no direct return, but write an output.html to the temp session on the opencpu server
#' @seealso \code{\link{render}} \code{\link{knit}} \code{\link{render_peptide_file}}
#' @examples
#' datafile <- system.file("extdata","summary.txt", package = "metareport")
#' metafile <-system.file("extdata","metainfo.txt", package = "metareport")
#'
#' # generate a report without meta information
#' render_MQsummary_file(file = datafile, output_dir = getwd())
#' # generate a report with meta information
# render_MQsummary_file(file = datafile , meta =metafile, output_dir = getwd())
#' @importFrom utils
#' @export
#'
#'
#'
metareport <- function(type = "summary" ,file, meta = NULL, template_version = "stable" ,output_format = "html_document", output_dir = NULL){
# choose the right markdown file as input to render
input_file <- switch(type,
"summary" = "MQ_report_summary.Rmd",
"peptides" = "MQ_report_pepides.Rmd",
"proteins" = "MQ_report_proteinGroups.Rmd",
"taxon" = "ML_report_taxonomy.Rmd",
"function" = "ML_report_function.Rmd",
"no_imput.Rmd"
)
if (template_version == "stable"){ # use the local one
local_file_path <- system.file("rmd","MQ_report_summary.Rmd", package = "metareport")
} else{
url_deposit <- "https://gitlab.com/iMetaLab/rmdocpu/-/raw/master/" # github was blocked on some servers
#myfile <- RCurl::getURL(paste0(url_deposit,template_version, "/", "MQ_report_summary.Rmd")) # RCurl does not work on windows
remote_file <- httr::GET(paste0(url_deposit,template_version, "/", "MQ_report_summary.Rmd")) #
if( remote_file$status_code == 200){ # if file exists
writeLines(rawToChar(remote_file$content), con="input.Rmd")
local_file_path <- "input.Rmd"
}else{ # use local file if the requested file does not exists
local_file_path <- system.file("rmd","MQ_report_summary.Rmd", package = "metareport")
}
}
data_table <- read.delim(file, header = TRUE,check.names = FALSE, stringsAsFactors = FALSE) # read in the data table
if(!is.null(meta)){
meta_table <- read.delim(meta, header = TRUE, check.names = FALSE, stringsAsFactors = FALSE) # with meta file
rmarkdown::render(local_file_path,output_format = output_format, params = list(summary_file_tbl = data_table, meta_table = meta_table), output_file="output.html", output_dir = output_dir)
}else{
rmarkdown::render(local_file_path,output_format = output_format, params = list(summary_file_tbl = data_table), output_file="output.html", output_dir = output_dir)
}
invisible()
}
|
/R/archived/report_metalab.R
|
permissive
|
caitsimop/metareport
|
R
| false
| false
| 4,324
|
r
|
#' wrapper function of rmarkdown::render for opencpu to render a report for maxquant summary from markdown template
#'
#' This function is destined for working on the opencpu server end, accepting file posted by front end to produce an html file to send to the front end.
#' It also works in stand-alone mode, to generate a report file, output.html, using a public accessible rmd file on github. Of course, this need internet connection to run
#'
#' @param type string, type of the result to generate the report on, one of summary, peptides,proteingroups,taxon, function
#' @param file string, the file (path) of the summary.txt from maxquant result txt folder, mandatory
#' @param meta the file (path), optional,string is the tsv file, generated by MetaLab2.0, 1st columns as sample name, 2nd column as experiment name, 3rd column and after as grouping
#' @param template_version string, can be "latest","stable", or a specific number, like "1.0", "1.1". Default as "stable". Will use the local template in the package (system.file("rmd","MQ_report_summary.Rmd", package = "metareport")), otherwise, it will try to curl the corresponding file from the deposit from either gitlab/github. Besure to use the correct number. If the version defined does not exist, or failed to retrieve from the deposit, it will use the stable version instead.
#' @param output_format see output_format in render, default as html, which has interactivity with plotly support
#' @param output_dir see output_dir in render, default as the same path of the rmarkdown input
#'
#' @return no direct return, but write an output.html to the temp session on the opencpu server
#' @seealso \code{\link{render}} \code{\link{knit}} \code{\link{render_peptide_file}}
#' @examples
#' datafile <- system.file("extdata","summary.txt", package = "metareport")
#' metafile <-system.file("extdata","metainfo.txt", package = "metareport")
#'
#' # generate a report without meta information
#' render_MQsummary_file(file = datafile, output_dir = getwd())
#' # generate a report with meta information
# render_MQsummary_file(file = datafile , meta =metafile, output_dir = getwd())
#' @importFrom utils
#' @export
#'
#'
#'
metareport <- function(type = "summary" ,file, meta = NULL, template_version = "stable" ,output_format = "html_document", output_dir = NULL){
# choose the right markdown file as input to render
input_file <- switch(type,
"summary" = "MQ_report_summary.Rmd",
"peptides" = "MQ_report_pepides.Rmd",
"proteins" = "MQ_report_proteinGroups.Rmd",
"taxon" = "ML_report_taxonomy.Rmd",
"function" = "ML_report_function.Rmd",
"no_imput.Rmd"
)
if (template_version == "stable"){ # use the local one
local_file_path <- system.file("rmd","MQ_report_summary.Rmd", package = "metareport")
} else{
url_deposit <- "https://gitlab.com/iMetaLab/rmdocpu/-/raw/master/" # github was blocked on some servers
#myfile <- RCurl::getURL(paste0(url_deposit,template_version, "/", "MQ_report_summary.Rmd")) # RCurl does not work on windows
remote_file <- httr::GET(paste0(url_deposit,template_version, "/", "MQ_report_summary.Rmd")) #
if( remote_file$status_code == 200){ # if file exists
writeLines(rawToChar(remote_file$content), con="input.Rmd")
local_file_path <- "input.Rmd"
}else{ # use local file if the requested file does not exists
local_file_path <- system.file("rmd","MQ_report_summary.Rmd", package = "metareport")
}
}
data_table <- read.delim(file, header = TRUE,check.names = FALSE, stringsAsFactors = FALSE) # read in the data table
if(!is.null(meta)){
meta_table <- read.delim(meta, header = TRUE, check.names = FALSE, stringsAsFactors = FALSE) # with meta file
rmarkdown::render(local_file_path,output_format = output_format, params = list(summary_file_tbl = data_table, meta_table = meta_table), output_file="output.html", output_dir = output_dir)
}else{
rmarkdown::render(local_file_path,output_format = output_format, params = list(summary_file_tbl = data_table), output_file="output.html", output_dir = output_dir)
}
invisible()
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/twoCatCI.R
\name{twoCatCI}
\alias{twoCatCI}
\title{Confidence intervals and standard errors of multiple imputation for the cross-tabulation of two categorical variables.}
\usage{
twoCatCI(obs_data, imp_data_list, type, vars, sig = 4, alpha = 0.05)
}
\arguments{
\item{obs_data}{The original dataset to which the next will be compared, of the type "data.frame".}
\item{imp_data_list}{A list composed of \code{m} synthetic data sets.}
\item{type}{Specifies which type of datasets are in \code{imp_data_list}. Options are "synthetic" and "imputed".}
\item{vars}{A vector of the two categorical variable being checked. Should be of type "factor".}
\item{sig}{The number of significant digits in the output dataframes. Defaults to 4.}
\item{alpha}{Test size, defaults to 0.05.}
}
\value{
This function returns a list of five data frames:
\item{Observed}{A cross-tabular proportion of observed values}
\item{Lower}{Lower limit of the confidence interval}
\item{Upper}{Upper limit of the confidence interval}
\item{SEs}{Standard Errors}
\item{CI_Indicator}{"YES"/"NO" indicating whether or not the observed value is within the confidence interval}
}
\description{
This function will calculate confidence intervals and standard errors from the proportional tabular responses of multiple imputed datasets for two categorical variables, and also give a YES/NO indicator for whether or not the observed value is within the confidence interval.
The confidence intervals and standard errors are calculated from formulas that are adapted for partially synthetic data sets. See reference for more information.
}
\details{
This function was developed with the intention of making the job of researching partially synthetic data utility a bit easier by providing another way of measuring utility.
}
\examples{
#PPA is the observed data set. PPAm5 is a list of 5 partially synthetic data sets derived from PPA.
#"sex" and "race" are categorical variables present in the synthesized data sets.
#3 significant digits are desired in the output dataframes.
twoCatCI(PPA, PPAm5, "synthetic", c("sex", "race"), sig=3)
}
\references{
\insertRef{adapt}{SynthTools}
}
\keyword{imputation}
\keyword{multiple}
\keyword{synds}
\keyword{synth}
\keyword{synthetic}
\keyword{utility}
|
/man/twoCatCI.Rd
|
no_license
|
RTIInternational/SynthTools
|
R
| false
| true
| 2,402
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/twoCatCI.R
\name{twoCatCI}
\alias{twoCatCI}
\title{Confidence intervals and standard errors of multiple imputation for the cross-tabulation of two categorical variables.}
\usage{
twoCatCI(obs_data, imp_data_list, type, vars, sig = 4, alpha = 0.05)
}
\arguments{
\item{obs_data}{The original dataset to which the next will be compared, of the type "data.frame".}
\item{imp_data_list}{A list composed of \code{m} synthetic data sets.}
\item{type}{Specifies which type of datasets are in \code{imp_data_list}. Options are "synthetic" and "imputed".}
\item{vars}{A vector of the two categorical variable being checked. Should be of type "factor".}
\item{sig}{The number of significant digits in the output dataframes. Defaults to 4.}
\item{alpha}{Test size, defaults to 0.05.}
}
\value{
This function returns a list of five data frames:
\item{Observed}{A cross-tabular proportion of observed values}
\item{Lower}{Lower limit of the confidence interval}
\item{Upper}{Upper limit of the confidence interval}
\item{SEs}{Standard Errors}
\item{CI_Indicator}{"YES"/"NO" indicating whether or not the observed value is within the confidence interval}
}
\description{
This function will calculate confidence intervals and standard errors from the proportional tabular responses of multiple imputed datasets for two categorical variables, and also give a YES/NO indicator for whether or not the observed value is within the confidence interval.
The confidence intervals and standard errors are calculated from formulas that are adapted for partially synthetic data sets. See reference for more information.
}
\details{
This function was developed with the intention of making the job of researching partially synthetic data utility a bit easier by providing another way of measuring utility.
}
\examples{
#PPA is the observed data set. PPAm5 is a list of 5 partially synthetic data sets derived from PPA.
#"sex" and "race" are categorical variables present in the synthesized data sets.
#3 significant digits are desired in the output dataframes.
twoCatCI(PPA, PPAm5, "synthetic", c("sex", "race"), sig=3)
}
\references{
\insertRef{adapt}{SynthTools}
}
\keyword{imputation}
\keyword{multiple}
\keyword{synds}
\keyword{synth}
\keyword{synthetic}
\keyword{utility}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/clump.R
\name{.check_clumps}
\alias{.check_clumps}
\title{Checks if correct clumps were found. If not, finds clumps}
\usage{
.check_clumps(detector, row = NA, col = NA)
}
\arguments{
\item{detector}{Detector object}
\item{row}{Module row number}
\item{col}{Module column number}
}
\value{
detector_events Detector object
}
\description{
Checks if correct clumps were found. If not, finds clumps
}
\keyword{internal}
|
/man/dot-check_clumps.Rd
|
permissive
|
alan-turing-institute/DetectorChecker
|
R
| false
| true
| 496
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/clump.R
\name{.check_clumps}
\alias{.check_clumps}
\title{Checks if correct clumps were found. If not, finds clumps}
\usage{
.check_clumps(detector, row = NA, col = NA)
}
\arguments{
\item{detector}{Detector object}
\item{row}{Module row number}
\item{col}{Module column number}
}
\value{
detector_events Detector object
}
\description{
Checks if correct clumps were found. If not, finds clumps
}
\keyword{internal}
|
folderLocation <- choose.dir()
setwd(folderLocation)
vctFiles <- c(list.files(path = folderLocation,pattern = "csv",recursive = FALSE))
vctFiles
total.logs <- length(vctFiles) #log count
total.logs
#create variables
EqName <- ("ET101")
TestName <- ("MyTest")
#create loop
datalist10 = list()
for ( j in 1:length(vctFiles) ) {
lp.file <- vctFiles[j]
{
#print("Load file")
f1 <- read.csv(lp.file,header = TRUE,sep = ",")
datalist10[[j]] <- f1
}
}
library(plyr)
f2=rbind.fill(datalist10,f1)
system.time(write.csv(f2,"write_TRD_combined_files.csv"))
system.time(write.csv(f2,"write_noRowNames_TRD_combined_files.csv",row.names = FALSE))
library(data.table)
system.time(fwrite(f2,"fread_TRD_combined_files.csv"))
|
/r/Session 2 Multiple Structured/1 exercise/session 2 exercise 1.R
|
permissive
|
justwinata/Py-R
|
R
| false
| false
| 745
|
r
|
folderLocation <- choose.dir()
setwd(folderLocation)
vctFiles <- c(list.files(path = folderLocation,pattern = "csv",recursive = FALSE))
vctFiles
total.logs <- length(vctFiles) #log count
total.logs
#create variables
EqName <- ("ET101")
TestName <- ("MyTest")
#create loop
datalist10 = list()
for ( j in 1:length(vctFiles) ) {
lp.file <- vctFiles[j]
{
#print("Load file")
f1 <- read.csv(lp.file,header = TRUE,sep = ",")
datalist10[[j]] <- f1
}
}
library(plyr)
f2=rbind.fill(datalist10,f1)
system.time(write.csv(f2,"write_TRD_combined_files.csv"))
system.time(write.csv(f2,"write_noRowNames_TRD_combined_files.csv",row.names = FALSE))
library(data.table)
system.time(fwrite(f2,"fread_TRD_combined_files.csv"))
|
rm(list = ls())
CRAN_packages <- c("dplyr", "readr", "magrittr", "lubridate")
lapply(CRAN_packages, require, character.only = TRUE)
main <- function() {
state_county <- clean_state_county()
state_county %>% save_state()
state_county %>% save_county()
return(NULL)
}
clean_state_county <- function() {
state_county <- read_csv("input/full_policy_data.csv",
col_types=cols_only(state_fips = "c", county_fips="c", effective_date_sip="c",
geography="c")) %>%
mutate(effective_date_sip = mdy(ifelse(is.na(effective_date_sip), NA,
paste0(effective_date_sip,"/2020"))))
return(state_county)
}
save_state <- function(state_county) {
state <- state_county %>% filter(!is.na(state_fips) & is.na(county_fips))
stopifnot(all(state$geography=="state"))
state %<>% select(-c(county_fips, geography)) %>%
rename(effective_date_sip_state=effective_date_sip)
state %>% write_csv("output/state_policies.csv")
return(NULL)
}
save_county <- function(state_county) {
state_county %>%
select(-geography) %>%
filter(!is.na(county_fips)) %>%
rename(effective_date_sip_county=effective_date_sip) %>%
write_csv("output/county_policies.csv")
return(NULL)
}
main()
|
/data/code/clean_policies.R
|
no_license
|
gabrieljkelvin/acre_allcott
|
R
| false
| false
| 1,312
|
r
|
rm(list = ls())
CRAN_packages <- c("dplyr", "readr", "magrittr", "lubridate")
lapply(CRAN_packages, require, character.only = TRUE)
main <- function() {
state_county <- clean_state_county()
state_county %>% save_state()
state_county %>% save_county()
return(NULL)
}
clean_state_county <- function() {
state_county <- read_csv("input/full_policy_data.csv",
col_types=cols_only(state_fips = "c", county_fips="c", effective_date_sip="c",
geography="c")) %>%
mutate(effective_date_sip = mdy(ifelse(is.na(effective_date_sip), NA,
paste0(effective_date_sip,"/2020"))))
return(state_county)
}
save_state <- function(state_county) {
state <- state_county %>% filter(!is.na(state_fips) & is.na(county_fips))
stopifnot(all(state$geography=="state"))
state %<>% select(-c(county_fips, geography)) %>%
rename(effective_date_sip_state=effective_date_sip)
state %>% write_csv("output/state_policies.csv")
return(NULL)
}
save_county <- function(state_county) {
state_county %>%
select(-geography) %>%
filter(!is.na(county_fips)) %>%
rename(effective_date_sip_county=effective_date_sip) %>%
write_csv("output/county_policies.csv")
return(NULL)
}
main()
|
library(lessR)
### Name: simCImean
### Title: Pedagogical Simulation for the Confidence Interval of the Mean
### Aliases: simCImean
### Keywords: confidence interval
### ** Examples
# 25 confidence intervals with a sample size each of 100
# mu=0, sigma=1, that is, sample from the standard normal
simCImean(25, 100)
# 25 confidence intervals with a sample size each of 100
# mu=100, sigma=15
# pause after each interval and show the data
simCImean(25, 100, mu=100, sigma=15, show.data=TRUE)
|
/data/genthat_extracted_code/lessR/examples/simCImean.Rd.R
|
no_license
|
surayaaramli/typeRrh
|
R
| false
| false
| 499
|
r
|
library(lessR)
### Name: simCImean
### Title: Pedagogical Simulation for the Confidence Interval of the Mean
### Aliases: simCImean
### Keywords: confidence interval
### ** Examples
# 25 confidence intervals with a sample size each of 100
# mu=0, sigma=1, that is, sample from the standard normal
simCImean(25, 100)
# 25 confidence intervals with a sample size each of 100
# mu=100, sigma=15
# pause after each interval and show the data
simCImean(25, 100, mu=100, sigma=15, show.data=TRUE)
|
#
# If you are going to use results produced by the scripts please do cite the
# SRMSerivce R package by providing the following URL
# www.github.com/protViz/SRMService
# by W.E. Wolski, J. Grossmann, C. Panse
#
library(limma)
library(SRMService)
protein <-
system.file("samples/proteinGroups/proteinGroupsPullDown.txt", package = "SRMService")
protein <- readr::read_tsv(protein)
colnames(protein) <- make.names(colnames(protein))
tmp <- strsplit(protein$Majority.protein.IDs, split = " ")
tmp2 <- sapply(tmp, function(x) {
x[1]
})
protein$Majority.protein.IDs <- gsub(">", "", tmp2)
rawF <-
gsub("Intensity\\.", "", grep("Intensity\\.", colnames(protein), value =
T))
condition <- quantable::split2table(rawF)
condition <- paste(condition[, 4], condition[, 5], sep = "_")
annotation <- data.frame(
Raw.file = rawF,
Condition = condition,
BioReplicate = paste("X", 1:length(condition), sep =
""),
Run = 1:length(condition),
IsotopeLabelType = rep("L", length(condition)),
stringsAsFactors = F
)
workdir <- "output"
dir.create(workdir)
tmp <- cumsum(rev(table(protein$Peptides)))
barplot(tmp[(length(tmp) - 5):length(tmp)], ylim = c(0, length(protein$Peptides)), xlab =
'nr of proteins with at least # peptides')
###################################
### Configuration section
Experimentname = "p2550"
nrNas = 5
nrPeptides = 2
annotation$Condition[grepl("_w$", annotation$Condition)] <- NA
reference = "pegfp_wo" # unique(annotation$Condition)[3]
#write.table(annotation, file="output/annotationused.txt")
####### END of user configuration ##
grp2 <- Grp2Analysis(
annotation,
"Experimentname",
maxNA = nrNas,
nrPeptides = nrPeptides,
reference = reference,
numberOfProteinClusters = 20
)
grp2$setMQProteinGroups(protein)
grp2$qfoldchange = 2
grp2$setQValueThresholds(qvalue = 0.01)
grp2PullDownExample <- grp2
x2 <- grp2$getResultTable()
dim(x2)
x3 <- grp2$getResultTableWithPseudo()
dim(x3)
usethis::use_data(grp2PullDownExample, overwrite = TRUE)
results <- grp2$getResultTable()
#write.table(results, file=file.path(workdir,"pValues.csv"), quote=FALSE, sep = "\t", col.names=NA)
#rmarkdown::render("Grp2Analysis.Rmd", bookdown::pdf_document2())
|
/inst/samples/proteinGroups/PullDownTest.R
|
no_license
|
protViz/SRMService
|
R
| false
| false
| 2,264
|
r
|
#
# If you are going to use results produced by the scripts please do cite the
# SRMSerivce R package by providing the following URL
# www.github.com/protViz/SRMService
# by W.E. Wolski, J. Grossmann, C. Panse
#
library(limma)
library(SRMService)
protein <-
system.file("samples/proteinGroups/proteinGroupsPullDown.txt", package = "SRMService")
protein <- readr::read_tsv(protein)
colnames(protein) <- make.names(colnames(protein))
tmp <- strsplit(protein$Majority.protein.IDs, split = " ")
tmp2 <- sapply(tmp, function(x) {
x[1]
})
protein$Majority.protein.IDs <- gsub(">", "", tmp2)
rawF <-
gsub("Intensity\\.", "", grep("Intensity\\.", colnames(protein), value =
T))
condition <- quantable::split2table(rawF)
condition <- paste(condition[, 4], condition[, 5], sep = "_")
annotation <- data.frame(
Raw.file = rawF,
Condition = condition,
BioReplicate = paste("X", 1:length(condition), sep =
""),
Run = 1:length(condition),
IsotopeLabelType = rep("L", length(condition)),
stringsAsFactors = F
)
workdir <- "output"
dir.create(workdir)
tmp <- cumsum(rev(table(protein$Peptides)))
barplot(tmp[(length(tmp) - 5):length(tmp)], ylim = c(0, length(protein$Peptides)), xlab =
'nr of proteins with at least # peptides')
###################################
### Configuration section
Experimentname = "p2550"
nrNas = 5
nrPeptides = 2
annotation$Condition[grepl("_w$", annotation$Condition)] <- NA
reference = "pegfp_wo" # unique(annotation$Condition)[3]
#write.table(annotation, file="output/annotationused.txt")
####### END of user configuration ##
grp2 <- Grp2Analysis(
annotation,
"Experimentname",
maxNA = nrNas,
nrPeptides = nrPeptides,
reference = reference,
numberOfProteinClusters = 20
)
grp2$setMQProteinGroups(protein)
grp2$qfoldchange = 2
grp2$setQValueThresholds(qvalue = 0.01)
grp2PullDownExample <- grp2
x2 <- grp2$getResultTable()
dim(x2)
x3 <- grp2$getResultTableWithPseudo()
dim(x3)
usethis::use_data(grp2PullDownExample, overwrite = TRUE)
results <- grp2$getResultTable()
#write.table(results, file=file.path(workdir,"pValues.csv"), quote=FALSE, sep = "\t", col.names=NA)
#rmarkdown::render("Grp2Analysis.Rmd", bookdown::pdf_document2())
|
#' Anolis phenotype data
#'
#' Data on anolis phenotype data from Thomas et al. 2009
#'
#' @docType data
#'
#' @usage data(anolis.data)
#'
#' @format An object of class \code{"data.frame"}.
#'
#' @keywords datasets
#'
#' @references Thomas GH, Meiri S, & Phillimore AB. 2009. Body size diversification in Anolis: novel environments and island effects. Evolution 63, 2017-2030.
#' @examples
#' data(anolis.data)
#' head(anolis.data)
"anolis.data"
|
/fuzzedpackages/motmot/R/RData.R
|
no_license
|
akhikolla/testpackages
|
R
| false
| false
| 445
|
r
|
#' Anolis phenotype data
#'
#' Data on anolis phenotype data from Thomas et al. 2009
#'
#' @docType data
#'
#' @usage data(anolis.data)
#'
#' @format An object of class \code{"data.frame"}.
#'
#' @keywords datasets
#'
#' @references Thomas GH, Meiri S, & Phillimore AB. 2009. Body size diversification in Anolis: novel environments and island effects. Evolution 63, 2017-2030.
#' @examples
#' data(anolis.data)
#' head(anolis.data)
"anolis.data"
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{df_neighbors}
\alias{df_neighbors}
\title{Neighbours for locations}
\format{
A nested dataframe of 1,942 rows and 2 variables:
\describe{
\item{grid_id}{unique identifier for each location}
\item{neighbor}{computed neighbours of the location with TOUCH relation}
}
}
\usage{
df_neighbors
}
\description{
Spatial neighbours for locations, where a neighbour has
at least one line in common, but its interior does not intersect with the location
}
\keyword{datasets}
|
/man/df_neighbors.Rd
|
permissive
|
lenamax2355/homelocator
|
R
| false
| true
| 570
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{df_neighbors}
\alias{df_neighbors}
\title{Neighbours for locations}
\format{
A nested dataframe of 1,942 rows and 2 variables:
\describe{
\item{grid_id}{unique identifier for each location}
\item{neighbor}{computed neighbours of the location with TOUCH relation}
}
}
\usage{
df_neighbors
}
\description{
Spatial neighbours for locations, where a neighbour has
at least one line in common, but its interior does not intersect with the location
}
\keyword{datasets}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/BIOMOD_cv.R
\name{BIOMOD_cv}
\alias{BIOMOD_cv}
\title{Custom models cross-validation procedure}
\usage{
BIOMOD_cv(data, k = 5, repetition = 5, do.full.models = TRUE,
stratified.cv = FALSE, stratify = "both", balance = "pres")
}
\arguments{
\item{data}{BIOMOD.formated.data object returned by BIOMOD_FormatingData}
\item{k}{number of bins/partitions for k-fold cv}
\item{repetition}{number of repetitions of k-fold cv (1 if stratified.cv=TRUE)}
\item{do.full.models}{if true, models calibrated and evaluated with the whole dataset are done}
\item{stratified.cv}{logical. run a stratified cv}
\item{stratify}{stratification method of the cv. Could be "x", "y", "both" (default), "block" or the name of a predictor for environmental stratified cv.}
\item{balance}{make balanced particions for "presences" (default) or "absences" (resp. pseudo-absences or background).}
}
\value{
DataSplitTable matrix with k*repetition (+ 1 for Full models if do.full.models = TRUE) columns for BIOMOD_Modeling function.
Stratification "x" and "y" was described in Wenger and Olden 2012. While Stratification "y" uses k partitions along the y-gradient, "x" does the same for the x-gradient and "both" combines them.
Stratification "block" was described in Muscarella et al. 2014. For bins of equal number are partitioned (bottom-left, bottom-right, top-left and top-right).
}
\description{
This function creates a DataSplitTable which could be used to evaluate models in Biomod with repeated
k-fold cross-validation (cv) or stratified cv instead of repeated split sample runs
}
\details{
Stratified cv could be used to test for model overfitting and for assessing transferability in geographic and environmental space.
If balance = "presences" presences are divided (balanced) equally over the particions (e.g. Fig. 1b in Muscarelly et al. 2014).
Pseudo-Absences will however be unbalanced over the particions especially if the presences are clumped on an edge of the study area.
If balance = "absences" absences (resp. Pseudo-Absences or background) are divided (balanced) as equally as possible for the particions
(geographical balanced bins given that absences are spread over the study area equally, approach similar to Fig. 1 in Wenger et Olden 2012).
Presences will however be unbalanced over the particians. Be careful: If the presences are clumped on an edge of the study area it is possible that all presences are in one bin.
}
\examples{
\dontrun{
# species occurrences
DataSpecies <- read.csv(system.file("external/species/mammals_table.csv",
package="biomod2"))
head(DataSpecies)
the name of studied species
myRespName <- 'GuloGulo'
# the presence/absences data for our species
myResp <- as.numeric(DataSpecies[,myRespName])
# the XY coordinates of species data
myRespXY <- DataSpecies[,c("X_WGS84","Y_WGS84")]
# Environmental variables extracted from BIOCLIM (bio_3, bio_4, bio_7, bio_11 & bio_12)
myExpl = stack( system.file( "external/bioclim/current/bio3.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio4.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio7.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio11.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio12.grd",
package="biomod2"))
# 1. Formatting Data
myBiomodData <- BIOMOD_FormatingData(resp.var = myResp,
expl.var = myExpl,
resp.xy = myRespXY,
resp.name = myRespName)
# 2. Defining Models Options using default options.
myBiomodOption <- BIOMOD_ModelingOptions()
# 3. Creating DataSplitTable
DataSplitTable <- BIOMOD_cv(myBiomodData, k=5, rep=2, do.full.models=F)
DataSplitTable.y <- BIOMOD_cv(myBiomodData,stratified.cv=T, stratify="y", k=2)
colnames(DataSplitTable.y)[1:2] <- c("RUN11","RUN12")
DataSplitTable <- cbind(DataSplitTable,DataSplitTable.y)
head(DataSplitTable)
# 4. Doing Modelisation
myBiomodModelOut <- BIOMOD_Modeling( myBiomodData,
models = c('RF'),
models.options = myBiomodOption,
DataSplitTable = DataSplitTable,
VarImport=0,
models.eval.meth = c('ROC'),
do.full.models=FALSE,
modeling.id="test")
## get cv evaluations
eval <- get_evaluations(myBiomodModelOut,as.data.frame=T)
eval$strat <- NA
eval$strat[grepl("13",eval$Model.name)] <- "Full"
eval$strat[!(grepl("11",eval$Model.name)|
grepl("12",eval$Model.name)|
grepl("13",eval$Model.name))] <- "Random"
eval$strat[grepl("11",eval$Model.name)|grepl("12",eval$Model.name)] <- "Strat"
boxplot(eval$Testing.data~ eval$strat, ylab="ROC AUC")
}
}
\references{
Muscarella, R., Galante, P.J., Soley-Guardia, M., Boria, R.A., Kass, J.M., Uriarte, M. & Anderson, R.P. (2014). ENMeval: An R package for conducting spatially independent evaluations and estimating optimal model complexity for Maxent ecological niche models. \emph{Methods in Ecology and Evolution}, \bold{5}, 1198-1205.
Wenger, S.J. & Olden, J.D. (2012). Assessing transferability of ecological models: an underappreciated aspect of statistical validation. \emph{Methods in Ecology and Evolution}, \bold{3}, 260-267.
}
\seealso{
\code{\link[ENMeval]{get.block}}
}
\author{
Frank Breiner \email{frank.breiner@wsl.ch}
}
|
/man/BIOMOD_cv.Rd
|
no_license
|
MirzaCengic/biomod2
|
R
| false
| true
| 5,849
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/BIOMOD_cv.R
\name{BIOMOD_cv}
\alias{BIOMOD_cv}
\title{Custom models cross-validation procedure}
\usage{
BIOMOD_cv(data, k = 5, repetition = 5, do.full.models = TRUE,
stratified.cv = FALSE, stratify = "both", balance = "pres")
}
\arguments{
\item{data}{BIOMOD.formated.data object returned by BIOMOD_FormatingData}
\item{k}{number of bins/partitions for k-fold cv}
\item{repetition}{number of repetitions of k-fold cv (1 if stratified.cv=TRUE)}
\item{do.full.models}{if true, models calibrated and evaluated with the whole dataset are done}
\item{stratified.cv}{logical. run a stratified cv}
\item{stratify}{stratification method of the cv. Could be "x", "y", "both" (default), "block" or the name of a predictor for environmental stratified cv.}
\item{balance}{make balanced particions for "presences" (default) or "absences" (resp. pseudo-absences or background).}
}
\value{
DataSplitTable matrix with k*repetition (+ 1 for Full models if do.full.models = TRUE) columns for BIOMOD_Modeling function.
Stratification "x" and "y" was described in Wenger and Olden 2012. While Stratification "y" uses k partitions along the y-gradient, "x" does the same for the x-gradient and "both" combines them.
Stratification "block" was described in Muscarella et al. 2014. For bins of equal number are partitioned (bottom-left, bottom-right, top-left and top-right).
}
\description{
This function creates a DataSplitTable which could be used to evaluate models in Biomod with repeated
k-fold cross-validation (cv) or stratified cv instead of repeated split sample runs
}
\details{
Stratified cv could be used to test for model overfitting and for assessing transferability in geographic and environmental space.
If balance = "presences" presences are divided (balanced) equally over the particions (e.g. Fig. 1b in Muscarelly et al. 2014).
Pseudo-Absences will however be unbalanced over the particions especially if the presences are clumped on an edge of the study area.
If balance = "absences" absences (resp. Pseudo-Absences or background) are divided (balanced) as equally as possible for the particions
(geographical balanced bins given that absences are spread over the study area equally, approach similar to Fig. 1 in Wenger et Olden 2012).
Presences will however be unbalanced over the particians. Be careful: If the presences are clumped on an edge of the study area it is possible that all presences are in one bin.
}
\examples{
\dontrun{
# species occurrences
DataSpecies <- read.csv(system.file("external/species/mammals_table.csv",
package="biomod2"))
head(DataSpecies)
the name of studied species
myRespName <- 'GuloGulo'
# the presence/absences data for our species
myResp <- as.numeric(DataSpecies[,myRespName])
# the XY coordinates of species data
myRespXY <- DataSpecies[,c("X_WGS84","Y_WGS84")]
# Environmental variables extracted from BIOCLIM (bio_3, bio_4, bio_7, bio_11 & bio_12)
myExpl = stack( system.file( "external/bioclim/current/bio3.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio4.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio7.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio11.grd",
package="biomod2"),
system.file( "external/bioclim/current/bio12.grd",
package="biomod2"))
# 1. Formatting Data
myBiomodData <- BIOMOD_FormatingData(resp.var = myResp,
expl.var = myExpl,
resp.xy = myRespXY,
resp.name = myRespName)
# 2. Defining Models Options using default options.
myBiomodOption <- BIOMOD_ModelingOptions()
# 3. Creating DataSplitTable
DataSplitTable <- BIOMOD_cv(myBiomodData, k=5, rep=2, do.full.models=F)
DataSplitTable.y <- BIOMOD_cv(myBiomodData,stratified.cv=T, stratify="y", k=2)
colnames(DataSplitTable.y)[1:2] <- c("RUN11","RUN12")
DataSplitTable <- cbind(DataSplitTable,DataSplitTable.y)
head(DataSplitTable)
# 4. Doing Modelisation
myBiomodModelOut <- BIOMOD_Modeling( myBiomodData,
models = c('RF'),
models.options = myBiomodOption,
DataSplitTable = DataSplitTable,
VarImport=0,
models.eval.meth = c('ROC'),
do.full.models=FALSE,
modeling.id="test")
## get cv evaluations
eval <- get_evaluations(myBiomodModelOut,as.data.frame=T)
eval$strat <- NA
eval$strat[grepl("13",eval$Model.name)] <- "Full"
eval$strat[!(grepl("11",eval$Model.name)|
grepl("12",eval$Model.name)|
grepl("13",eval$Model.name))] <- "Random"
eval$strat[grepl("11",eval$Model.name)|grepl("12",eval$Model.name)] <- "Strat"
boxplot(eval$Testing.data~ eval$strat, ylab="ROC AUC")
}
}
\references{
Muscarella, R., Galante, P.J., Soley-Guardia, M., Boria, R.A., Kass, J.M., Uriarte, M. & Anderson, R.P. (2014). ENMeval: An R package for conducting spatially independent evaluations and estimating optimal model complexity for Maxent ecological niche models. \emph{Methods in Ecology and Evolution}, \bold{5}, 1198-1205.
Wenger, S.J. & Olden, J.D. (2012). Assessing transferability of ecological models: an underappreciated aspect of statistical validation. \emph{Methods in Ecology and Evolution}, \bold{3}, 260-267.
}
\seealso{
\code{\link[ENMeval]{get.block}}
}
\author{
Frank Breiner \email{frank.breiner@wsl.ch}
}
|
/Tong_Anal/5 두 모집단의 비교.R
|
no_license
|
SilverwestKim/Univ
|
R
| false
| false
| 3,705
|
r
| ||
library(EMCluster)
library(data.table)
setwd('/Users/abhishekjindal/Desktop/UCI_courses/Fall_2017/CS273A/kaggleProj/mlTechniques')
train_x = data.table(read.table('../final_datasets/X_training_100K.txt', sep = ','))
train_y = data.table(read.table('../final_datasets/Y_training_100K.txt', sep = ','))
val_x = data.table(read.table('../final_datasets/X_validation_50K.txt', sep = ','))
val_y = data.table(read.table('../final_datasets/Y_validation_50K.txt', sep = ','))
sample_data = train_x[0:30000]
sample_y = train_y[0:nrow(sample_data)]
nrow(sample_data)
numClasses = 5
ret <- init.EM(sample_data, nclass = numClasses)
ret.new <- assign.class(sample_data, ret, return.all = FALSE)
str(ret.new)
for(i in seq(numClasses)){
print(mean(sample_y[ret.new["class"]$class == i]$V1))
}
ret.new <- assign.class(train_x, ret, return.all = FALSE)
for(i in seq(numClasses)){
print(mean(train_y[ret.new["class"]$class == i]$V1))
}
ret.new <- assign.class(val_x, ret, return.all = FALSE)
for(i in seq(numClasses)){
print(mean(val_y[ret.new["class"]$class == i]$V1))
}
for(i in seq(numClasses)){
print(length(val_y[ret.new["class"]$class == i]$V1))
}
|
/mlTechniques/em_test_v1.R
|
no_license
|
gagankhanijau/ml_cs273_rain_pred
|
R
| false
| false
| 1,152
|
r
|
library(EMCluster)
library(data.table)
setwd('/Users/abhishekjindal/Desktop/UCI_courses/Fall_2017/CS273A/kaggleProj/mlTechniques')
train_x = data.table(read.table('../final_datasets/X_training_100K.txt', sep = ','))
train_y = data.table(read.table('../final_datasets/Y_training_100K.txt', sep = ','))
val_x = data.table(read.table('../final_datasets/X_validation_50K.txt', sep = ','))
val_y = data.table(read.table('../final_datasets/Y_validation_50K.txt', sep = ','))
sample_data = train_x[0:30000]
sample_y = train_y[0:nrow(sample_data)]
nrow(sample_data)
numClasses = 5
ret <- init.EM(sample_data, nclass = numClasses)
ret.new <- assign.class(sample_data, ret, return.all = FALSE)
str(ret.new)
for(i in seq(numClasses)){
print(mean(sample_y[ret.new["class"]$class == i]$V1))
}
ret.new <- assign.class(train_x, ret, return.all = FALSE)
for(i in seq(numClasses)){
print(mean(train_y[ret.new["class"]$class == i]$V1))
}
ret.new <- assign.class(val_x, ret, return.all = FALSE)
for(i in seq(numClasses)){
print(mean(val_y[ret.new["class"]$class == i]$V1))
}
for(i in seq(numClasses)){
print(length(val_y[ret.new["class"]$class == i]$V1))
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/iot_operations.R
\name{iot_create_job}
\alias{iot_create_job}
\title{Creates a job}
\usage{
iot_create_job(jobId, targets, documentSource, document, description,
presignedUrlConfig, targetSelection, jobExecutionsRolloutConfig,
abortConfig, timeoutConfig, tags, namespaceId)
}
\arguments{
\item{jobId}{[required] A job identifier which must be unique for your AWS account. We recommend
using a UUID. Alpha-numeric characters, "-" and "\\_" are valid for use
here.}
\item{targets}{[required] A list of things and thing groups to which the job should be sent.}
\item{documentSource}{An S3 link to the job document.}
\item{document}{The job document.
If the job document resides in an S3 bucket, you must use a placeholder
link when specifying the document.
The placeholder link is of the following form:
\verb{$\\\{aws:iot:s3-presigned-url:https://s3.amazonaws.com/<i>bucket</i>/<i>key</i>\\\}}
where \emph{bucket} is your bucket name and \emph{key} is the object in the bucket
to which you are linking.}
\item{description}{A short text description of the job.}
\item{presignedUrlConfig}{Configuration information for pre-signed S3 URLs.}
\item{targetSelection}{Specifies whether the job will continue to run (CONTINUOUS), or will be
complete after all those things specified as targets have completed the
job (SNAPSHOT). If continuous, the job may also be run on a thing when a
change is detected in a target. For example, a job will run on a thing
when the thing is added to a target group, even after the job was
completed by all things originally in the group.}
\item{jobExecutionsRolloutConfig}{Allows you to create a staged rollout of the job.}
\item{abortConfig}{Allows you to create criteria to abort a job.}
\item{timeoutConfig}{Specifies the amount of time each device has to finish its execution of
the job. The timer is started when the job execution status is set to
\code{IN_PROGRESS}. If the job execution status is not set to another
terminal state before the time expires, it will be automatically set to
\code{TIMED_OUT}.}
\item{tags}{Metadata which can be used to manage the job.}
\item{namespaceId}{The namespace used to indicate that a job is a customer-managed job.
When you specify a value for this parameter, AWS IoT Core sends jobs
notifications to MQTT topics that contain the value in the following
format.
\verb{$aws/things/<i>THING_NAME</i>/jobs/<i>JOB_ID</i>/notify-namespace-<i>NAMESPACE_ID</i>/}
The \code{namespaceId} feature is in public preview.}
}
\description{
Creates a job.
}
\section{Request syntax}{
\preformatted{svc$create_job(
jobId = "string",
targets = list(
"string"
),
documentSource = "string",
document = "string",
description = "string",
presignedUrlConfig = list(
roleArn = "string",
expiresInSec = 123
),
targetSelection = "CONTINUOUS"|"SNAPSHOT",
jobExecutionsRolloutConfig = list(
maximumPerMinute = 123,
exponentialRate = list(
baseRatePerMinute = 123,
incrementFactor = 123.0,
rateIncreaseCriteria = list(
numberOfNotifiedThings = 123,
numberOfSucceededThings = 123
)
)
),
abortConfig = list(
criteriaList = list(
list(
failureType = "FAILED"|"REJECTED"|"TIMED_OUT"|"ALL",
action = "CANCEL",
thresholdPercentage = 123.0,
minNumberOfExecutedThings = 123
)
)
),
timeoutConfig = list(
inProgressTimeoutInMinutes = 123
),
tags = list(
list(
Key = "string",
Value = "string"
)
),
namespaceId = "string"
)
}
}
\keyword{internal}
|
/cran/paws.internet.of.things/man/iot_create_job.Rd
|
permissive
|
sanchezvivi/paws
|
R
| false
| true
| 3,654
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/iot_operations.R
\name{iot_create_job}
\alias{iot_create_job}
\title{Creates a job}
\usage{
iot_create_job(jobId, targets, documentSource, document, description,
presignedUrlConfig, targetSelection, jobExecutionsRolloutConfig,
abortConfig, timeoutConfig, tags, namespaceId)
}
\arguments{
\item{jobId}{[required] A job identifier which must be unique for your AWS account. We recommend
using a UUID. Alpha-numeric characters, "-" and "\\_" are valid for use
here.}
\item{targets}{[required] A list of things and thing groups to which the job should be sent.}
\item{documentSource}{An S3 link to the job document.}
\item{document}{The job document.
If the job document resides in an S3 bucket, you must use a placeholder
link when specifying the document.
The placeholder link is of the following form:
\verb{$\\\{aws:iot:s3-presigned-url:https://s3.amazonaws.com/<i>bucket</i>/<i>key</i>\\\}}
where \emph{bucket} is your bucket name and \emph{key} is the object in the bucket
to which you are linking.}
\item{description}{A short text description of the job.}
\item{presignedUrlConfig}{Configuration information for pre-signed S3 URLs.}
\item{targetSelection}{Specifies whether the job will continue to run (CONTINUOUS), or will be
complete after all those things specified as targets have completed the
job (SNAPSHOT). If continuous, the job may also be run on a thing when a
change is detected in a target. For example, a job will run on a thing
when the thing is added to a target group, even after the job was
completed by all things originally in the group.}
\item{jobExecutionsRolloutConfig}{Allows you to create a staged rollout of the job.}
\item{abortConfig}{Allows you to create criteria to abort a job.}
\item{timeoutConfig}{Specifies the amount of time each device has to finish its execution of
the job. The timer is started when the job execution status is set to
\code{IN_PROGRESS}. If the job execution status is not set to another
terminal state before the time expires, it will be automatically set to
\code{TIMED_OUT}.}
\item{tags}{Metadata which can be used to manage the job.}
\item{namespaceId}{The namespace used to indicate that a job is a customer-managed job.
When you specify a value for this parameter, AWS IoT Core sends jobs
notifications to MQTT topics that contain the value in the following
format.
\verb{$aws/things/<i>THING_NAME</i>/jobs/<i>JOB_ID</i>/notify-namespace-<i>NAMESPACE_ID</i>/}
The \code{namespaceId} feature is in public preview.}
}
\description{
Creates a job.
}
\section{Request syntax}{
\preformatted{svc$create_job(
jobId = "string",
targets = list(
"string"
),
documentSource = "string",
document = "string",
description = "string",
presignedUrlConfig = list(
roleArn = "string",
expiresInSec = 123
),
targetSelection = "CONTINUOUS"|"SNAPSHOT",
jobExecutionsRolloutConfig = list(
maximumPerMinute = 123,
exponentialRate = list(
baseRatePerMinute = 123,
incrementFactor = 123.0,
rateIncreaseCriteria = list(
numberOfNotifiedThings = 123,
numberOfSucceededThings = 123
)
)
),
abortConfig = list(
criteriaList = list(
list(
failureType = "FAILED"|"REJECTED"|"TIMED_OUT"|"ALL",
action = "CANCEL",
thresholdPercentage = 123.0,
minNumberOfExecutedThings = 123
)
)
),
timeoutConfig = list(
inProgressTimeoutInMinutes = 123
),
tags = list(
list(
Key = "string",
Value = "string"
)
),
namespaceId = "string"
)
}
}
\keyword{internal}
|
#' Python configuration
#'
#' Information on Python and Numpy versions detected
#'
#' @return Python configuration object; Logical indicating whether Python
#' bindings are available
#'
#' @export
py_config <- function() {
ensure_python_initialized()
.globals$py_config
}
#' Build Python configuration error message
#'
#' @param prefix Error message prefix
#'
#' @keywords internal
#' @export
py_config_error_message <- function(prefix) {
message <- prefix
config <- py_config()
if (!is.null(config)) {
message <- paste0(message, "\n\nDetected Python configuration:\n\n",
str(config), "\n")
}
message
}
#' Check if Python is available on this system
#'
#' @param initialize `TRUE` to attempt to initialize Python bindings if they
#' aren't yet available (defaults to `FALSE`).
#'
#' @return Logical indicating whether Python is initialized.
#'
#' @note The `py_numpy_available` function is a superset of the
#' `py_available` function (it calls `py_available` first before
#' checking for NumPy).
#'
#' @export
py_available <- function(initialize = FALSE) {
if (is_python_initialized())
.globals$py_config$available
else if (initialize) {
tryCatch({
ensure_python_initialized()
.globals$py_config$available
}, error = function(e) FALSE)
} else {
FALSE
}
}
#' @rdname py_available
#' @export
py_numpy_available <- function(initialize = FALSE) {
if (!py_available(initialize = initialize))
FALSE
else
py_numpy_available_impl()
}
#' Check if a Python module is available on this system.
#'
#' @param module Name of module
#'
#' @return Logical indicating whether module is available
#'
#' @export
py_module_available <- function(module) {
tryCatch({ import(module); TRUE }, error = clear_error_handler(FALSE))
}
#' Discover the version of Python to use with reticulate.
#'
#' This function enables callers to check which versions of Python will
#' be discovered on a system as well as which one will be chosen for
#' use with reticulate.
#'
#' @param required_module A optional module name that must be available
#' in order for a version of Python to be used.
#'
#' @return Python configuration object.
#'
#' @export
py_discover_config <- function(required_module = NULL) {
# create a list of possible python versions to bind to
# (start with versions specified via environment variable or use_* function)
python_versions <- reticulate_python_versions()
# next look in virtual environments with required module derived names
if (is_windows()) {
registry_versions <- py_versions_windows()
anaconda_registry_versions <- subset(registry_versions, registry_versions$type == "Anaconda")
env_dirs <- file.path(anaconda_registry_versions$install_path, "envs")
if (length(env_dirs) > 0) {
if (!is.null(required_module))
python_versions <- c(python_versions, python_environments(env_dirs, required_module))
}
} else {
# virtualenv_wrapper allows redirection of root envs directory via WORKON_HOME
workon_home <- Sys.getenv("WORKON_HOME", unset = NA)
if (is.na(workon_home))
workon_home <- NULL
# all possible environment dirs
env_dirs <- c(workon_home, "~/.virtualenvs",
"~/anaconda/envs", "~/anaconda3/envs", "~/anaconda3/envs",
"~")
if (!is.null(required_module))
python_versions <- c(python_versions, python_environments(env_dirs, required_module))
}
# look on system path
python <- as.character(Sys.which("python"))
if (nzchar(python))
python_versions <- c(python_versions, python)
# provide other common locations
if (is_windows()) {
python_versions <- c(python_versions, registry_versions$executable_path)
} else {
python_versions <- c(python_versions,
"/usr/bin/python",
"/usr/local/bin/python",
"/opt/python/bin/python",
"/opt/local/python/bin/python",
"/usr/bin/python3",
"/usr/local/bin/python3",
"/opt/python/bin/python3",
"/opt/local/python/bin/python3",
path.expand("~/anaconda/bin/python"),
path.expand("~/anaconda3/bin/python")
)
}
# next virtual or conda environments
if (length(env_dirs) > 0)
python_versions <- c(python_versions, python_environments(env_dirs))
# de-duplicate
python_versions <- unique(python_versions)
# filter locations by existence
if (length(python_versions) > 0)
python_versions <- python_versions[file.exists(python_versions)]
# scan until we find a version of python that meets our qualifying conditions
valid_python_versions <- c()
for (python_version in python_versions) {
# get the config
config <- python_config(python_version, required_module, python_versions)
# if we have a required module ensure it's satsified.
# also check architecture (can be an issue on windows)
has_python_gte_27 <- as.numeric_version(config$version) >= "2.7"
has_compatible_arch <- !is_incompatible_arch(config)
has_preferred_numpy <- !is.null(config$numpy) && config$numpy$version >= "1.6"
if (has_compatible_arch && has_preferred_numpy)
valid_python_versions <- c(valid_python_versions, python_version)
has_required_module <- is.null(config$required_module) || !is.null(config$required_module_path)
if (has_python_gte_27 && has_compatible_arch && has_preferred_numpy && has_required_module)
return(config)
}
# no preferred found, return first with valid config if we have it or NULL
if (length(valid_python_versions) > 0)
return(python_config(valid_python_versions[[1]], required_module, python_versions))
else if (length(python_versions) > 0)
return(python_config(python_versions[[1]], required_module, python_versions))
else
return(NULL)
}
#' Discover versions of Python installed on a Windows system
#'
#' @return Data frame with `type`, `hive`, `install_path`, `executable_path`,
#' and `version`.
#'
#' @keywords internal
#' @export
py_versions_windows <- function() {
rbind(
read_python_versions_from_registry("HCU", key = "PythonCore"),
read_python_versions_from_registry("HLM", key = "PythonCore"),
windows_registry_anaconda_versions()
)
}
python_environments <- function(env_dirs, required_module = NULL) {
# filter env_dirs by existence
env_dirs <- env_dirs[utils::file_test("-d", env_dirs)]
# envs to return
envs <- c()
# python bin differs by platform
python_bin <- ifelse(is_windows(), "python.exe", "bin/python")
for (env_dir in env_dirs) {
# filter by required module if requested
if (!is.null(required_module)) {
module_envs <- c(paste0("r-", required_module), required_module)
envs <- c(envs, path.expand(sprintf("%s/%s/%s", env_dir, module_envs, python_bin)))
# otherwise return all
} else {
envs <- c(envs, path.expand(sprintf("%s/%s",
list.dirs(env_dir, recursive = FALSE),
python_bin)))
}
}
# filter by existence
if (length(envs) > 0)
envs[file.exists(envs)]
else
envs
}
python_config <- function(python, required_module, python_versions) {
# collect configuration information
if (!is.null(required_module)) {
Sys.setenv(RETICULATE_REQUIRED_MODULE = required_module)
on.exit(Sys.unsetenv("RETICULATE_REQUIRED_MODULE"), add = TRUE)
}
config_script <- system.file("config/config.py", package = "reticulate")
config <- system2(command = python, args = paste0('"', config_script, '"'), stdout = TRUE)
status <- attr(config, "status")
if (!is.null(status)) {
errmsg <- attr(config, "errmsg")
stop("Error ", status, " occurred running ", python, " ", errmsg)
}
config <- read.dcf(textConnection(config), all = TRUE)
# get the full textual version and the numeric version, check for anaconda
version_string <- config$Version
version <- config$VersionNumber
anaconda <- grepl("continuum", tolower(version_string)) || grepl("anaconda", tolower(version_string))
architecture <- config$Architecture
# determine the location of libpython (see also # https://github.com/JuliaPy/PyCall.jl/blob/master/deps/build.jl)
if (is_windows()) {
# note that 'prefix' has the binary location and 'py_version_nodot` has the suffix`
python_libdir <- dirname(python)
python_dll <- paste0("python", gsub(".", "", version, fixed = TRUE), ".dll")
libpython <- file.path(python_libdir, python_dll)
if (!file.exists(libpython))
libpython <- python_dll
} else {
# (note that the LIBRARY variable has the name of the static library)
python_libdir_config <- function(var) {
python_libdir <- config[[var]]
ext <- switch(Sys.info()[["sysname"]], Darwin = ".dylib", Windows = ".dll", ".so")
libpython <- file.path(python_libdir, paste0("libpython" , version, c("", "m"), ext))
libpython_exists <- libpython[file.exists(libpython)]
if (length(libpython_exists) > 0)
libpython_exists[[1]]
else
libpython[[1]]
}
if (!is.null(config$LIBPL)) {
libpython <- python_libdir_config("LIBPL")
if (!file.exists(libpython)) {
if (!is.null(config$LIBDIR))
libpython <- python_libdir_config("LIBDIR")
else
libpython <- NULL
}
} else {
libpython <- NULL
}
}
# determine PYTHONHOME
if (!is.null(config$PREFIX)) {
pythonhome <- config$PREFIX
if (!is_windows())
pythonhome <- paste(pythonhome, config$EXEC_PREFIX, sep = ":")
} else {
pythonhome <- NULL
}
as_numeric_version <- function(version) {
version <- clean_version(version)
numeric_version(version)
}
# check for numpy
if (!is.null(config$NumpyPath))
numpy <- list(path = config$NumpyPath,
version = as_numeric_version(config$NumpyVersion))
else
numpy <- NULL
# check for virtualenv activate script
activate_this <- file.path(dirname(python), "activate_this.py")
if (file.exists(activate_this))
virtualenv_activate <- activate_this
else
virtualenv_activate <- ""
# check for required module
required_module_path <- config$RequiredModulePath
# return config info
structure(class = "py_config", list(
python = python,
libpython = libpython,
pythonhome = pythonhome,
virtualenv_activate = virtualenv_activate,
version_string = version_string,
version = version,
architecture = architecture,
anaconda = anaconda,
numpy = numpy,
required_module = required_module,
required_module_path = required_module_path,
available = FALSE,
python_versions = python_versions
))
}
#' @export
str.py_config <- function(object, ...) {
x <- object
out <- ""
out <- paste0(out, "python: ", x$python, "\n")
out <- paste0(out, "libpython: ", ifelse(is.null(x$libpython), "[NOT FOUND]", x$libpython), ifelse(is_windows() || is.null(x$libpython) || file.exists(x$libpython), "", "[NOT FOUND]"), "\n")
out <- paste0(out, "pythonhome: ", ifelse(is.null(x$pythonhome), "[NOT FOUND]", x$pythonhome), "\n")
if (nzchar(x$virtualenv_activate))
out <- paste0(out, "virtualenv: ", x$virtualenv_activate, "\n")
out <- paste0(out, "version: ", x$version_string, "\n")
if (is_windows())
out <- paste0(out, "Architecture: ", x$architecture, "\n")
if (!is.null(x$numpy)) {
out <- paste0(out, "numpy: ", x$numpy$path, "\n")
out <- paste0(out, "numpy_version: ", as.character(x$numpy$version), "\n")
} else {
out <- paste0(out, "numpy: [NOT FOUND]\n")
}
if (!is.null(x$required_module)) {
out <- paste0(out, sprintf("%-16s", paste0(x$required_module, ":")))
if (!is.null(x$required_module_path))
out <- paste0(out, x$required_module_path, "\n")
else
out <- paste0(out, "[NOT FOUND]\n")
}
if (length(x$python_versions) > 1) {
out <- paste0(out, "\npython versions found: \n")
python_versions <- paste0(" ", x$python_versions, collapse = "\n")
out <- paste0(out, python_versions, sep = "\n")
}
out
}
#' @export
print.py_config <- function(x, ...) {
cat(str(x))
}
is_windows <- function() {
identical(.Platform$OS.type, "windows")
}
is_osx <- function() {
Sys.info()["sysname"] == "Darwin"
}
clean_version <- function(version) {
gsub("\\.$", "", gsub("[A-Za-z_]+", "", version))
}
reticulate_python_versions <- function() {
# python versions to return
python_versions <- c()
# combine registered versions with the RETICULATE_PYTHON environment variable
reticulate_python_options <- .globals$use_python_versions
reticulate_python_env <- Sys.getenv("RETICULATE_PYTHON", unset = NA)
if (!is.na(reticulate_python_env))
reticulate_python_options <- c(reticulate_python_env, reticulate_python_options)
# determine python versions to return
if (length(reticulate_python_options) > 0) {
for (i in 1:length(reticulate_python_options)) {
python <- normalize_python_path(reticulate_python_options[[i]])
if (python$exists)
python_versions <- c(python_versions, python$path)
}
}
# return them
python_versions
}
normalize_python_path <- function(python) {
# normalize trailing slash and expand
python <- gsub("[\\/]+$", "", python)
python <- path.expand(python)
# check for existence
if (!utils::file_test("-d", python) &&
!utils::file_test("-f", python)) {
list(
path = python,
exists = FALSE
)
} else {
# append binary if it's a directory
if (utils::file_test("-d", python))
python <- file.path(python, "python")
# append .exe if necessary on windows
if (is_windows() && (!grepl("^.*\\.exe$", tolower(python))))
python <- paste0(python, ".exe")
# return
list(
path = python,
exists = TRUE
)
}
}
windows_registry_anaconda_versions <- function() {
rbind(read_python_versions_from_registry("HCU", key = "ContinuumAnalytics", type = "Anaconda"),
read_python_versions_from_registry("HLM", key = "ContinuumAnalytics", type = "Anaconda"))
}
read_python_versions_from_registry <- function(hive, key,type=key) {
python_core_key <- tryCatch(utils::readRegistry(
key = paste0("SOFTWARE\\Python\\", key), hive = hive, maxdepth = 3),
error = function(e) NULL)
types <- c()
hives <- c()
install_paths <- c()
executable_paths <- c()
versions <- c()
archs <- c()
if (length(python_core_key) > 0) {
for (version in names(python_core_key)) {
version_key <- python_core_key[[version]]
if (is.list(version_key) && !is.null(version_key$InstallPath)) {
version_dir <- version_key$InstallPath$`(Default)`
if (!is.null(version_dir) && utils::file_test("-d", version_dir)) {
# determine install_path and executable_path
install_path <- version_dir
executable_path <- file.path(install_path, "python.exe")
# proceed if it exists
if (file.exists(executable_path)) {
# determine version and arch
if (type == "Anaconda") {
matches <- regexec("^Anaconda.*(32|64).*$", version)
matches <- regmatches(version, matches)[[1]]
if (length(matches) == 2) {
version <- version_key$SysVersion
arch <- matches[[2]]
} else {
warning("Unexpected format for Anaconda version: ", version,
"\n(Please install a more recent version of Anaconda)")
arch <- NA
}
} else { # type == "PythonCore"
matches <- regexec("^(\\d)\\.(\\d)(?:-(32|64))?$", version)
matches <- regmatches(version, matches)[[1]]
if (length(matches) == 4) {
version <- paste(matches[[2]], matches[[3]], sep = ".")
arch <- matches[[4]]
if (!nzchar(arch)) {
if (numeric_version(version) >= "3.0")
arch <- "64"
else {
python_arch <- python_arch(executable_path)
arch <- gsub("bit", "", python_arch, fixed = TRUE)
}
}
} else {
warning("Unexpected format for PythonCore version: ", version)
arch <- NA
}
}
if (!is.na(arch)) {
# convert to R arch
if (arch == "32")
arch <- "i386"
else if (arch == "64")
arch <- "x64"
# append to vectors
types <- c(types, type)
hives <- c(hives, hive)
install_paths <- c(install_paths, utils::shortPathName(install_path))
executable_paths <- c(executable_paths, utils::shortPathName(executable_path))
versions <- c(versions, version)
archs <- c(archs, arch)
}
}
}
}
}
}
data.frame(
type = types,
hive = hives,
install_path = install_paths,
executable_path = executable_paths,
version = versions,
arch = archs,
stringsAsFactors = FALSE
)
}
# get the architecture from a python binary
python_arch <- function(python) {
# run command
result <- system2(python, stdout = TRUE, args = c("-c", shQuote(
"import sys; import platform; sys.stdout.write(platform.architecture()[0])")))
# check for error
error_status <- attr(result, "status")
if (!is.null(error_status))
stop("Error ", error_status, " occurred while checking for python architecture", call. = FALSE)
# return arch
result
}
# convert R arch to python arch
current_python_arch <- function() {
if (.Platform$r_arch == "i386")
"32bit"
else if (.Platform$r_arch == "x64")
"64bit"
else
"Unknown"
}
# check for compatible architecture
is_incompatible_arch <- function(config) {
if (is_windows()) {
!identical(current_python_arch(),config$architecture)
} else {
FALSE
}
}
|
/R/config.R
|
permissive
|
nathania/reticulate
|
R
| false
| false
| 18,276
|
r
|
#' Python configuration
#'
#' Information on Python and Numpy versions detected
#'
#' @return Python configuration object; Logical indicating whether Python
#' bindings are available
#'
#' @export
py_config <- function() {
ensure_python_initialized()
.globals$py_config
}
#' Build Python configuration error message
#'
#' @param prefix Error message prefix
#'
#' @keywords internal
#' @export
py_config_error_message <- function(prefix) {
message <- prefix
config <- py_config()
if (!is.null(config)) {
message <- paste0(message, "\n\nDetected Python configuration:\n\n",
str(config), "\n")
}
message
}
#' Check if Python is available on this system
#'
#' @param initialize `TRUE` to attempt to initialize Python bindings if they
#' aren't yet available (defaults to `FALSE`).
#'
#' @return Logical indicating whether Python is initialized.
#'
#' @note The `py_numpy_available` function is a superset of the
#' `py_available` function (it calls `py_available` first before
#' checking for NumPy).
#'
#' @export
py_available <- function(initialize = FALSE) {
if (is_python_initialized())
.globals$py_config$available
else if (initialize) {
tryCatch({
ensure_python_initialized()
.globals$py_config$available
}, error = function(e) FALSE)
} else {
FALSE
}
}
#' @rdname py_available
#' @export
py_numpy_available <- function(initialize = FALSE) {
if (!py_available(initialize = initialize))
FALSE
else
py_numpy_available_impl()
}
#' Check if a Python module is available on this system.
#'
#' @param module Name of module
#'
#' @return Logical indicating whether module is available
#'
#' @export
py_module_available <- function(module) {
tryCatch({ import(module); TRUE }, error = clear_error_handler(FALSE))
}
#' Discover the version of Python to use with reticulate.
#'
#' This function enables callers to check which versions of Python will
#' be discovered on a system as well as which one will be chosen for
#' use with reticulate.
#'
#' @param required_module A optional module name that must be available
#' in order for a version of Python to be used.
#'
#' @return Python configuration object.
#'
#' @export
py_discover_config <- function(required_module = NULL) {
# create a list of possible python versions to bind to
# (start with versions specified via environment variable or use_* function)
python_versions <- reticulate_python_versions()
# next look in virtual environments with required module derived names
if (is_windows()) {
registry_versions <- py_versions_windows()
anaconda_registry_versions <- subset(registry_versions, registry_versions$type == "Anaconda")
env_dirs <- file.path(anaconda_registry_versions$install_path, "envs")
if (length(env_dirs) > 0) {
if (!is.null(required_module))
python_versions <- c(python_versions, python_environments(env_dirs, required_module))
}
} else {
# virtualenv_wrapper allows redirection of root envs directory via WORKON_HOME
workon_home <- Sys.getenv("WORKON_HOME", unset = NA)
if (is.na(workon_home))
workon_home <- NULL
# all possible environment dirs
env_dirs <- c(workon_home, "~/.virtualenvs",
"~/anaconda/envs", "~/anaconda3/envs", "~/anaconda3/envs",
"~")
if (!is.null(required_module))
python_versions <- c(python_versions, python_environments(env_dirs, required_module))
}
# look on system path
python <- as.character(Sys.which("python"))
if (nzchar(python))
python_versions <- c(python_versions, python)
# provide other common locations
if (is_windows()) {
python_versions <- c(python_versions, registry_versions$executable_path)
} else {
python_versions <- c(python_versions,
"/usr/bin/python",
"/usr/local/bin/python",
"/opt/python/bin/python",
"/opt/local/python/bin/python",
"/usr/bin/python3",
"/usr/local/bin/python3",
"/opt/python/bin/python3",
"/opt/local/python/bin/python3",
path.expand("~/anaconda/bin/python"),
path.expand("~/anaconda3/bin/python")
)
}
# next virtual or conda environments
if (length(env_dirs) > 0)
python_versions <- c(python_versions, python_environments(env_dirs))
# de-duplicate
python_versions <- unique(python_versions)
# filter locations by existence
if (length(python_versions) > 0)
python_versions <- python_versions[file.exists(python_versions)]
# scan until we find a version of python that meets our qualifying conditions
valid_python_versions <- c()
for (python_version in python_versions) {
# get the config
config <- python_config(python_version, required_module, python_versions)
# if we have a required module ensure it's satsified.
# also check architecture (can be an issue on windows)
has_python_gte_27 <- as.numeric_version(config$version) >= "2.7"
has_compatible_arch <- !is_incompatible_arch(config)
has_preferred_numpy <- !is.null(config$numpy) && config$numpy$version >= "1.6"
if (has_compatible_arch && has_preferred_numpy)
valid_python_versions <- c(valid_python_versions, python_version)
has_required_module <- is.null(config$required_module) || !is.null(config$required_module_path)
if (has_python_gte_27 && has_compatible_arch && has_preferred_numpy && has_required_module)
return(config)
}
# no preferred found, return first with valid config if we have it or NULL
if (length(valid_python_versions) > 0)
return(python_config(valid_python_versions[[1]], required_module, python_versions))
else if (length(python_versions) > 0)
return(python_config(python_versions[[1]], required_module, python_versions))
else
return(NULL)
}
#' Discover versions of Python installed on a Windows system
#'
#' @return Data frame with `type`, `hive`, `install_path`, `executable_path`,
#' and `version`.
#'
#' @keywords internal
#' @export
py_versions_windows <- function() {
rbind(
read_python_versions_from_registry("HCU", key = "PythonCore"),
read_python_versions_from_registry("HLM", key = "PythonCore"),
windows_registry_anaconda_versions()
)
}
python_environments <- function(env_dirs, required_module = NULL) {
# filter env_dirs by existence
env_dirs <- env_dirs[utils::file_test("-d", env_dirs)]
# envs to return
envs <- c()
# python bin differs by platform
python_bin <- ifelse(is_windows(), "python.exe", "bin/python")
for (env_dir in env_dirs) {
# filter by required module if requested
if (!is.null(required_module)) {
module_envs <- c(paste0("r-", required_module), required_module)
envs <- c(envs, path.expand(sprintf("%s/%s/%s", env_dir, module_envs, python_bin)))
# otherwise return all
} else {
envs <- c(envs, path.expand(sprintf("%s/%s",
list.dirs(env_dir, recursive = FALSE),
python_bin)))
}
}
# filter by existence
if (length(envs) > 0)
envs[file.exists(envs)]
else
envs
}
python_config <- function(python, required_module, python_versions) {
# collect configuration information
if (!is.null(required_module)) {
Sys.setenv(RETICULATE_REQUIRED_MODULE = required_module)
on.exit(Sys.unsetenv("RETICULATE_REQUIRED_MODULE"), add = TRUE)
}
config_script <- system.file("config/config.py", package = "reticulate")
config <- system2(command = python, args = paste0('"', config_script, '"'), stdout = TRUE)
status <- attr(config, "status")
if (!is.null(status)) {
errmsg <- attr(config, "errmsg")
stop("Error ", status, " occurred running ", python, " ", errmsg)
}
config <- read.dcf(textConnection(config), all = TRUE)
# get the full textual version and the numeric version, check for anaconda
version_string <- config$Version
version <- config$VersionNumber
anaconda <- grepl("continuum", tolower(version_string)) || grepl("anaconda", tolower(version_string))
architecture <- config$Architecture
# determine the location of libpython (see also # https://github.com/JuliaPy/PyCall.jl/blob/master/deps/build.jl)
if (is_windows()) {
# note that 'prefix' has the binary location and 'py_version_nodot` has the suffix`
python_libdir <- dirname(python)
python_dll <- paste0("python", gsub(".", "", version, fixed = TRUE), ".dll")
libpython <- file.path(python_libdir, python_dll)
if (!file.exists(libpython))
libpython <- python_dll
} else {
# (note that the LIBRARY variable has the name of the static library)
python_libdir_config <- function(var) {
python_libdir <- config[[var]]
ext <- switch(Sys.info()[["sysname"]], Darwin = ".dylib", Windows = ".dll", ".so")
libpython <- file.path(python_libdir, paste0("libpython" , version, c("", "m"), ext))
libpython_exists <- libpython[file.exists(libpython)]
if (length(libpython_exists) > 0)
libpython_exists[[1]]
else
libpython[[1]]
}
if (!is.null(config$LIBPL)) {
libpython <- python_libdir_config("LIBPL")
if (!file.exists(libpython)) {
if (!is.null(config$LIBDIR))
libpython <- python_libdir_config("LIBDIR")
else
libpython <- NULL
}
} else {
libpython <- NULL
}
}
# determine PYTHONHOME
if (!is.null(config$PREFIX)) {
pythonhome <- config$PREFIX
if (!is_windows())
pythonhome <- paste(pythonhome, config$EXEC_PREFIX, sep = ":")
} else {
pythonhome <- NULL
}
as_numeric_version <- function(version) {
version <- clean_version(version)
numeric_version(version)
}
# check for numpy
if (!is.null(config$NumpyPath))
numpy <- list(path = config$NumpyPath,
version = as_numeric_version(config$NumpyVersion))
else
numpy <- NULL
# check for virtualenv activate script
activate_this <- file.path(dirname(python), "activate_this.py")
if (file.exists(activate_this))
virtualenv_activate <- activate_this
else
virtualenv_activate <- ""
# check for required module
required_module_path <- config$RequiredModulePath
# return config info
structure(class = "py_config", list(
python = python,
libpython = libpython,
pythonhome = pythonhome,
virtualenv_activate = virtualenv_activate,
version_string = version_string,
version = version,
architecture = architecture,
anaconda = anaconda,
numpy = numpy,
required_module = required_module,
required_module_path = required_module_path,
available = FALSE,
python_versions = python_versions
))
}
#' @export
str.py_config <- function(object, ...) {
x <- object
out <- ""
out <- paste0(out, "python: ", x$python, "\n")
out <- paste0(out, "libpython: ", ifelse(is.null(x$libpython), "[NOT FOUND]", x$libpython), ifelse(is_windows() || is.null(x$libpython) || file.exists(x$libpython), "", "[NOT FOUND]"), "\n")
out <- paste0(out, "pythonhome: ", ifelse(is.null(x$pythonhome), "[NOT FOUND]", x$pythonhome), "\n")
if (nzchar(x$virtualenv_activate))
out <- paste0(out, "virtualenv: ", x$virtualenv_activate, "\n")
out <- paste0(out, "version: ", x$version_string, "\n")
if (is_windows())
out <- paste0(out, "Architecture: ", x$architecture, "\n")
if (!is.null(x$numpy)) {
out <- paste0(out, "numpy: ", x$numpy$path, "\n")
out <- paste0(out, "numpy_version: ", as.character(x$numpy$version), "\n")
} else {
out <- paste0(out, "numpy: [NOT FOUND]\n")
}
if (!is.null(x$required_module)) {
out <- paste0(out, sprintf("%-16s", paste0(x$required_module, ":")))
if (!is.null(x$required_module_path))
out <- paste0(out, x$required_module_path, "\n")
else
out <- paste0(out, "[NOT FOUND]\n")
}
if (length(x$python_versions) > 1) {
out <- paste0(out, "\npython versions found: \n")
python_versions <- paste0(" ", x$python_versions, collapse = "\n")
out <- paste0(out, python_versions, sep = "\n")
}
out
}
#' @export
print.py_config <- function(x, ...) {
cat(str(x))
}
is_windows <- function() {
identical(.Platform$OS.type, "windows")
}
is_osx <- function() {
Sys.info()["sysname"] == "Darwin"
}
clean_version <- function(version) {
gsub("\\.$", "", gsub("[A-Za-z_]+", "", version))
}
reticulate_python_versions <- function() {
# python versions to return
python_versions <- c()
# combine registered versions with the RETICULATE_PYTHON environment variable
reticulate_python_options <- .globals$use_python_versions
reticulate_python_env <- Sys.getenv("RETICULATE_PYTHON", unset = NA)
if (!is.na(reticulate_python_env))
reticulate_python_options <- c(reticulate_python_env, reticulate_python_options)
# determine python versions to return
if (length(reticulate_python_options) > 0) {
for (i in 1:length(reticulate_python_options)) {
python <- normalize_python_path(reticulate_python_options[[i]])
if (python$exists)
python_versions <- c(python_versions, python$path)
}
}
# return them
python_versions
}
normalize_python_path <- function(python) {
# normalize trailing slash and expand
python <- gsub("[\\/]+$", "", python)
python <- path.expand(python)
# check for existence
if (!utils::file_test("-d", python) &&
!utils::file_test("-f", python)) {
list(
path = python,
exists = FALSE
)
} else {
# append binary if it's a directory
if (utils::file_test("-d", python))
python <- file.path(python, "python")
# append .exe if necessary on windows
if (is_windows() && (!grepl("^.*\\.exe$", tolower(python))))
python <- paste0(python, ".exe")
# return
list(
path = python,
exists = TRUE
)
}
}
windows_registry_anaconda_versions <- function() {
rbind(read_python_versions_from_registry("HCU", key = "ContinuumAnalytics", type = "Anaconda"),
read_python_versions_from_registry("HLM", key = "ContinuumAnalytics", type = "Anaconda"))
}
read_python_versions_from_registry <- function(hive, key,type=key) {
python_core_key <- tryCatch(utils::readRegistry(
key = paste0("SOFTWARE\\Python\\", key), hive = hive, maxdepth = 3),
error = function(e) NULL)
types <- c()
hives <- c()
install_paths <- c()
executable_paths <- c()
versions <- c()
archs <- c()
if (length(python_core_key) > 0) {
for (version in names(python_core_key)) {
version_key <- python_core_key[[version]]
if (is.list(version_key) && !is.null(version_key$InstallPath)) {
version_dir <- version_key$InstallPath$`(Default)`
if (!is.null(version_dir) && utils::file_test("-d", version_dir)) {
# determine install_path and executable_path
install_path <- version_dir
executable_path <- file.path(install_path, "python.exe")
# proceed if it exists
if (file.exists(executable_path)) {
# determine version and arch
if (type == "Anaconda") {
matches <- regexec("^Anaconda.*(32|64).*$", version)
matches <- regmatches(version, matches)[[1]]
if (length(matches) == 2) {
version <- version_key$SysVersion
arch <- matches[[2]]
} else {
warning("Unexpected format for Anaconda version: ", version,
"\n(Please install a more recent version of Anaconda)")
arch <- NA
}
} else { # type == "PythonCore"
matches <- regexec("^(\\d)\\.(\\d)(?:-(32|64))?$", version)
matches <- regmatches(version, matches)[[1]]
if (length(matches) == 4) {
version <- paste(matches[[2]], matches[[3]], sep = ".")
arch <- matches[[4]]
if (!nzchar(arch)) {
if (numeric_version(version) >= "3.0")
arch <- "64"
else {
python_arch <- python_arch(executable_path)
arch <- gsub("bit", "", python_arch, fixed = TRUE)
}
}
} else {
warning("Unexpected format for PythonCore version: ", version)
arch <- NA
}
}
if (!is.na(arch)) {
# convert to R arch
if (arch == "32")
arch <- "i386"
else if (arch == "64")
arch <- "x64"
# append to vectors
types <- c(types, type)
hives <- c(hives, hive)
install_paths <- c(install_paths, utils::shortPathName(install_path))
executable_paths <- c(executable_paths, utils::shortPathName(executable_path))
versions <- c(versions, version)
archs <- c(archs, arch)
}
}
}
}
}
}
data.frame(
type = types,
hive = hives,
install_path = install_paths,
executable_path = executable_paths,
version = versions,
arch = archs,
stringsAsFactors = FALSE
)
}
# get the architecture from a python binary
python_arch <- function(python) {
# run command
result <- system2(python, stdout = TRUE, args = c("-c", shQuote(
"import sys; import platform; sys.stdout.write(platform.architecture()[0])")))
# check for error
error_status <- attr(result, "status")
if (!is.null(error_status))
stop("Error ", error_status, " occurred while checking for python architecture", call. = FALSE)
# return arch
result
}
# convert R arch to python arch
current_python_arch <- function() {
if (.Platform$r_arch == "i386")
"32bit"
else if (.Platform$r_arch == "x64")
"64bit"
else
"Unknown"
}
# check for compatible architecture
is_incompatible_arch <- function(config) {
if (is_windows()) {
!identical(current_python_arch(),config$architecture)
} else {
FALSE
}
}
|
## This function will creates a matrix and cache it's inverse matrix
## It will create an ordinary matrix
## Get the value of the matrix
## Create value for inverse matrix
## Get the value of inverse matrix
## Lets create the matrix
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
# Initiate the matrix with null
set <- function(y) {
x <<- y # Set the value
m <<- NULL # Clear the cache
}
# Define function for the values of the matrix
get <- function() x
# Define a function to set inverse matrix value
setInverse <- function(inverse) m <<- inverse
# Define function to get the inverse
getInverse <- function() m
# Return a list with the above four functions
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## Now we need to cache and solve to get the inverse
cacheSolve <- function(x, ...) {
m <- x$getInverse() # The cached value for the inverse
if(!is.null(m)) { # Get the non-empty cache
message("getting cached data")
return(m)
}
# Calculate and get cache and inverse
data <- x$get() # Get value of matrix
m <- solve(data) # Calculate inverse
x$setInverse(m) # Cache the result
m # Return the inverse
}
|
/cachematrix.R
|
no_license
|
zillurbmb51/ProgrammingAssignment2
|
R
| false
| false
| 1,435
|
r
|
## This function will creates a matrix and cache it's inverse matrix
## It will create an ordinary matrix
## Get the value of the matrix
## Create value for inverse matrix
## Get the value of inverse matrix
## Lets create the matrix
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
# Initiate the matrix with null
set <- function(y) {
x <<- y # Set the value
m <<- NULL # Clear the cache
}
# Define function for the values of the matrix
get <- function() x
# Define a function to set inverse matrix value
setInverse <- function(inverse) m <<- inverse
# Define function to get the inverse
getInverse <- function() m
# Return a list with the above four functions
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## Now we need to cache and solve to get the inverse
cacheSolve <- function(x, ...) {
m <- x$getInverse() # The cached value for the inverse
if(!is.null(m)) { # Get the non-empty cache
message("getting cached data")
return(m)
}
# Calculate and get cache and inverse
data <- x$get() # Get value of matrix
m <- solve(data) # Calculate inverse
x$setInverse(m) # Cache the result
m # Return the inverse
}
|
\name{Loaloa}
\alias{Loaloa}
\docType{data}
\title{
Loa loa prevalence in North Cameroon, 1991-2001
}
\description{
This data set describes prevalence of infection by the nematode \emph{Loa loa} in North Cameroon, 1991-2001.
This is a superset of the data discussed by Diggle and Ribeiro (2007) and Diggle et al. (2007).
The study investigated the relationship between altitude, vegetation indices, and prevalence of the parasite.
}
\usage{data("Loaloa")}
\format{
The data frame includes 197 observations on the following variables:
\describe{
\item{latitude}{latitude, in degrees.}
\item{longitude}{longitude, in degrees.}
\item{ntot}{sample size per location}
\item{npos}{number of infected individuals per location}
\item{maxNDVI}{maximum normalised-difference vegetation index (NDVI) from repeated satellite scans}
\item{seNDVI}{standard error of NDVI}
\item{elev1}{altitude, in m.}
\item{elev2,elev3,elev4}{Additional altitude variables derived from the previous one, provided for convenience:
respectively, positive values of altitude-650, positive values of altitude-1000, and positive values of altitude-1300}
\item{maxNDVI1}{a copy of maxNDVI modified as \code{maxNDVI1[maxNDVI1>0.8] <- 0.8}}
}
}
\source{
The data were last retrieved on March 1, 2013 from P.J. Ribeiro's web resources
at\cr
\code{www.leg.ufpr.br/doku.php/pessoais:paulojus:mbgbook:datasets}. A current (2022-06-18) source is
\url{https://www.lancaster.ac.uk/staff/diggle/moredata/Loaloa.txt}).
}
\references{
Diggle, P., and Ribeiro, P. 2007. Model-based geostatistics, Springer series
in statistics, Springer, New York.
Diggle, P. J., Thomson, M. C., Christensen, O. F., Rowlingson, B., Obsomer,
V., Gardon, J., Wanji, S., Takougang, I., Enyong, P., Kamgno, J., Remme,
J. H., Boussinesq, M., and Molyneux, D. H. 2007. Spatial modelling and
the prediction of Loa loa risk: decision making under uncertainty, Ann.
Trop. Med. Parasitol. 101, 499-509.
}
\examples{
data("Loaloa")
if (spaMM.getOption("example_maxtime")>5) {
fitme(cbind(npos,ntot-npos)~1 +Matern(1|longitude+latitude),
data=Loaloa, family=binomial())
}
### Variations on the model fit by Diggle et al.
### on a subset of the Loaloa data
### In each case this shows the slight differences in syntax,
### and the difference in 'typical' computation times,
### when fit using corrHLfit() or fitme().
if (spaMM.getOption("example_maxtime")>4) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),method="HL(0,1)",
data=Loaloa,family=binomial(),ranFix=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>1.6) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),method="HL(0,1)",
data=Loaloa,family=binomial(),fixed=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>5.8) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),ranFix=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>2.5) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),fixed=list(nu=0.5),method="REML")
}
## Diggle and Ribeiro (2007) assumed (in this package notation) Nugget=2/7:
if (spaMM.getOption("example_maxtime")>7) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),ranFix=list(nu=0.5,Nugget=2/7))
}
if (spaMM.getOption("example_maxtime")>1.3) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),method="REML",
data=Loaloa,family=binomial(),fixed=list(nu=0.5,Nugget=2/7))
}
## with nugget estimation:
if (spaMM.getOption("example_maxtime")>17) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),
init.corrHLfit=list(Nugget=0.1),ranFix=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>5.5) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),method="REML",
init=list(Nugget=0.1),fixed=list(nu=0.5))
}
}
\keyword{datasets}
|
/man/Loaloa.Rd
|
no_license
|
cran/spaMM
|
R
| false
| false
| 4,677
|
rd
|
\name{Loaloa}
\alias{Loaloa}
\docType{data}
\title{
Loa loa prevalence in North Cameroon, 1991-2001
}
\description{
This data set describes prevalence of infection by the nematode \emph{Loa loa} in North Cameroon, 1991-2001.
This is a superset of the data discussed by Diggle and Ribeiro (2007) and Diggle et al. (2007).
The study investigated the relationship between altitude, vegetation indices, and prevalence of the parasite.
}
\usage{data("Loaloa")}
\format{
The data frame includes 197 observations on the following variables:
\describe{
\item{latitude}{latitude, in degrees.}
\item{longitude}{longitude, in degrees.}
\item{ntot}{sample size per location}
\item{npos}{number of infected individuals per location}
\item{maxNDVI}{maximum normalised-difference vegetation index (NDVI) from repeated satellite scans}
\item{seNDVI}{standard error of NDVI}
\item{elev1}{altitude, in m.}
\item{elev2,elev3,elev4}{Additional altitude variables derived from the previous one, provided for convenience:
respectively, positive values of altitude-650, positive values of altitude-1000, and positive values of altitude-1300}
\item{maxNDVI1}{a copy of maxNDVI modified as \code{maxNDVI1[maxNDVI1>0.8] <- 0.8}}
}
}
\source{
The data were last retrieved on March 1, 2013 from P.J. Ribeiro's web resources
at\cr
\code{www.leg.ufpr.br/doku.php/pessoais:paulojus:mbgbook:datasets}. A current (2022-06-18) source is
\url{https://www.lancaster.ac.uk/staff/diggle/moredata/Loaloa.txt}).
}
\references{
Diggle, P., and Ribeiro, P. 2007. Model-based geostatistics, Springer series
in statistics, Springer, New York.
Diggle, P. J., Thomson, M. C., Christensen, O. F., Rowlingson, B., Obsomer,
V., Gardon, J., Wanji, S., Takougang, I., Enyong, P., Kamgno, J., Remme,
J. H., Boussinesq, M., and Molyneux, D. H. 2007. Spatial modelling and
the prediction of Loa loa risk: decision making under uncertainty, Ann.
Trop. Med. Parasitol. 101, 499-509.
}
\examples{
data("Loaloa")
if (spaMM.getOption("example_maxtime")>5) {
fitme(cbind(npos,ntot-npos)~1 +Matern(1|longitude+latitude),
data=Loaloa, family=binomial())
}
### Variations on the model fit by Diggle et al.
### on a subset of the Loaloa data
### In each case this shows the slight differences in syntax,
### and the difference in 'typical' computation times,
### when fit using corrHLfit() or fitme().
if (spaMM.getOption("example_maxtime")>4) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),method="HL(0,1)",
data=Loaloa,family=binomial(),ranFix=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>1.6) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),method="HL(0,1)",
data=Loaloa,family=binomial(),fixed=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>5.8) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),ranFix=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>2.5) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),fixed=list(nu=0.5),method="REML")
}
## Diggle and Ribeiro (2007) assumed (in this package notation) Nugget=2/7:
if (spaMM.getOption("example_maxtime")>7) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),ranFix=list(nu=0.5,Nugget=2/7))
}
if (spaMM.getOption("example_maxtime")>1.3) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),method="REML",
data=Loaloa,family=binomial(),fixed=list(nu=0.5,Nugget=2/7))
}
## with nugget estimation:
if (spaMM.getOption("example_maxtime")>17) {
corrHLfit(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),
init.corrHLfit=list(Nugget=0.1),ranFix=list(nu=0.5))
}
if (spaMM.getOption("example_maxtime")>5.5) {
fitme(cbind(npos,ntot-npos)~elev1+elev2+elev3+elev4+maxNDVI1+seNDVI
+Matern(1|longitude+latitude),
data=Loaloa,family=binomial(),method="REML",
init=list(Nugget=0.1),fixed=list(nu=0.5))
}
}
\keyword{datasets}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hyperg.R
\name{hyperg}
\alias{hyperg}
\title{Compute hypergeometric backbone}
\usage{
hyperg(B)
}
\arguments{
\item{B}{Matrix: Bipartite network}
}
\value{
list(positive, negative).
positive gives matrix of probability of ties above the observed value.
negative gives matrix of probability of ties below the observed value.
}
\description{
`hyperg` computes the probability of observing
a higher or lower edge weight using the hypergeometric distribution.
Once computed, use \code{\link{backbone.extract}} to return
the backbone matrix for a given alpha value.
}
\examples{
hypergeometric_bb <- hyperg(davis)
}
\references{
\href{https://doi.org/10.1007/s13278-013-0107-y}{Neal, Zachary. 2013. “Identifying Statistically Significant Edges in One-Mode Projections.” Social Network Analysis and Mining 3 (4). Springer: 915–24. DOI:10.1007/s13278-013-0107-y.}
}
|
/man/hyperg.Rd
|
no_license
|
jcfisher/backbone
|
R
| false
| true
| 955
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hyperg.R
\name{hyperg}
\alias{hyperg}
\title{Compute hypergeometric backbone}
\usage{
hyperg(B)
}
\arguments{
\item{B}{Matrix: Bipartite network}
}
\value{
list(positive, negative).
positive gives matrix of probability of ties above the observed value.
negative gives matrix of probability of ties below the observed value.
}
\description{
`hyperg` computes the probability of observing
a higher or lower edge weight using the hypergeometric distribution.
Once computed, use \code{\link{backbone.extract}} to return
the backbone matrix for a given alpha value.
}
\examples{
hypergeometric_bb <- hyperg(davis)
}
\references{
\href{https://doi.org/10.1007/s13278-013-0107-y}{Neal, Zachary. 2013. “Identifying Statistically Significant Edges in One-Mode Projections.” Social Network Analysis and Mining 3 (4). Springer: 915–24. DOI:10.1007/s13278-013-0107-y.}
}
|
library(data.table)
setwd("/Users/vinaysesham/Documents/datasciencecoursera/ExploratoryDataAnalysis/explot_project1")
hpc <- read.table("household_power_consumption.txt",header=TRUE,sep=";",stringsAsFactors=FALSE)
hpcSubset <- hpc[hpc$Date %in% c("1/2/2007","2/2/2007") ,]
hpcSubset$datetime <- strptime(paste(subSetData$Date, subSetData$Time, sep=" "), "%d/%m/%Y %H:%M:%S")
png("plot4.png",width=480,height=480)
par(mfrow=c(2,2),mar=c(4,4,2,1),oma=c(0,0,2,0))
with(hpcSubset,{plot(datetime,Global_active_power,type="l",ylab="Global Active Power",xlab="")
plot(datetime,as.numeric(Voltage),type="l",ylab="Voltage",xlab="datetime")
plot(datetime,Sub_metering_1,type="l",ylab="Energy sub metering",xlab="")
lines(datetime,Sub_metering_2,type="l",col="red")
lines(datetime,Sub_metering_3,type="l",col="blue")
legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),lty=1,col=c("black","red","blue"))
plot(datetime,as.numeric(Global_reactive_power),type="l",ylab="Global_reactive_power",xlab="datetime")
})
dev.off()
|
/plot4.R
|
no_license
|
vsesham/ExData_Plotting1
|
R
| false
| false
| 1,034
|
r
|
library(data.table)
setwd("/Users/vinaysesham/Documents/datasciencecoursera/ExploratoryDataAnalysis/explot_project1")
hpc <- read.table("household_power_consumption.txt",header=TRUE,sep=";",stringsAsFactors=FALSE)
hpcSubset <- hpc[hpc$Date %in% c("1/2/2007","2/2/2007") ,]
hpcSubset$datetime <- strptime(paste(subSetData$Date, subSetData$Time, sep=" "), "%d/%m/%Y %H:%M:%S")
png("plot4.png",width=480,height=480)
par(mfrow=c(2,2),mar=c(4,4,2,1),oma=c(0,0,2,0))
with(hpcSubset,{plot(datetime,Global_active_power,type="l",ylab="Global Active Power",xlab="")
plot(datetime,as.numeric(Voltage),type="l",ylab="Voltage",xlab="datetime")
plot(datetime,Sub_metering_1,type="l",ylab="Energy sub metering",xlab="")
lines(datetime,Sub_metering_2,type="l",col="red")
lines(datetime,Sub_metering_3,type="l",col="blue")
legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),lty=1,col=c("black","red","blue"))
plot(datetime,as.numeric(Global_reactive_power),type="l",ylab="Global_reactive_power",xlab="datetime")
})
dev.off()
|
preprocessing_tool <- function(
data_in, # name of the input file (tab delimited text with the raw counts) or R matrix
data_type ="file", # c(file, r_matrix)
output_object ="default", # output R object (matrix)
output_file ="default", # output flat file
removeSg = TRUE, # boolean to remove singleton counts
removeSg_valueMin = 2, # lowest retained value (lower converted to 0)
removeSg_rowMin = 4, # lowest retained row sum (lower, row is removed)
log_transform = FALSE,
norm_method = "DESeq_blind", #c("standardize", "quantile", "DESeq_blind", "DESeq_per_condition", "DESeq_pooled", "DESeq_pooled_CR", "none"), # USE blind if not replicates -- use pooled to get DESeq default
pseudo_count = 1, # has to be integer for DESeq
DESeq_metadata_table = NA, # only used if method is other than "blind"
DESeq_metadata_column = 1, # only used if method is other than "blind"
DESeq_metadata_type = "file", # c( "file", "r_matrix" )
#DESeq_method = "blind", # c( "pooled", "pooled-CR", "per-condition", "blind" ) # blind, treat everything as one group
DESeq_sharingMode = "maximum", # c( "maximum", "fit-only", "gene-est-only" ) # maximum is the most conservative choice
DESeq_fitType = "local", # c( "parametric", "local" )
DESeq_image = TRUE, # create dispersion vs mean plot indicate DESeq regression
scale_0_to_1 = TRUE,
produce_boxplots = FALSE,
boxplots_file_out = "default",
boxplot_height_in = "default", # 11,
boxplot_width_in = "default", #"8.5,
boxplot_res_dpi = 300,
create_log = TRUE,
debug = FALSE
)
{
# Install DESeq
#source("https://bioconductor.org/biocLite.R")
#biocLite("DESeq")
# check for necessary packages, install if they are not there
#require(matR) || install.packages("matR", repo="http://mcs.anl.gov/~braithwaite/R", type="source")
#chooseCRANmirror()
setRepositories(ind=1:8)
#####source("http://bioconductor.org/biocLite.R")
# Install packages if they are not already installed
#if ( is.element("DESeq", installed.packages()[,1]) == FALSE ){ source("http://bioconductor.org/biocLite.R"); biocLite("DESeq") }
#if ( is.element("preprocessCore", installed.packages()[,1]) == FALSE ){ source("http://bioconductor.org/biocLite.R"); biocLite("preprocessCore") }
#if ( is.element("RColorBrewer", installed.packages()[,1]) == FALSE ){ install.packages("RColorBrewer") }
#require(preprocessCore) || install.packages("preprocessCore")
#require(DESeq) || biocLite("DESeq") # update to DESeq2 when I have a chance
#####if ( is.element("RColorBrewer", installed.packages()[,1]) == FALSE ){ install.packages("RColorBrewer") }
#####if ( is.element("preprocessCore", installed.packages()[,1]) == FALSE ){ biocLite("preprocessCore") }
#####if ( is.element("DESeq", installed.packages()[,1]) == FALSE ){ biocLite("DESeq") }
# (DESeq): www.ncbi.nlm.nih.gov/pubmed/20979621
#library(preprocessCore)
#library(DESeq)
#library(RColorBrewer)
###### MAIN
# get the name of the data object if an object is used -- use the filename if input is filename string
if ( identical( data_type, "file") ){
input_name <- data_in
}else if( identical( data_type, "r_matrix") ){
input_name <- deparse(substitute(data_in))
}else{
stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
}
# Generate names for the output file and object
if ( identical( output_object, "default") ){
output_object <- paste( input_name, ".", norm_method, ".PREPROCESSED" , sep="", collapse="")
}
if ( identical( output_file, "default") ){
output_file <- paste( input_name, ".", norm_method, ".PREPROCESSED.txt" , sep="", collapse="")
}
# Input the data
if ( identical( data_type, "file") ){
input_data <- data.matrix(read.table(data_in, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
}else if( identical( data_type, "r_matrix") ){
input_data <- data.matrix(data_in)
}else{
stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
}
# sort the data (COLUMNWISE) by id
sample_names <- order(colnames(input_data))
input_data <- input_data[,sample_names]
# make a copy of the input data that is not processed
input_data.og <- input_data
# non optional, convert "na's" to 0
input_data[is.na(input_data)] <- 0
# remove singletons
if(removeSg==TRUE){
input_data <- remove.singletons(x=input_data, lim.entry=removeSg_valueMin, lim.row=removeSg_rowMin, debug=debug)
}
# log transform log(x+1)2
if ( log_transform==TRUE ){
input_data <- log_data(input_data, pseudo_count)
}
regression_message <- "DESeq regression: NA"
# Normalize -- stadardize or quantile norm (depends on user selection)
switch(
norm_method,
standardize={
input_data <- standardize_data(input_data)
},
quantile={
input_data <- quantile_norm_data(input_data)
},
DESeq_blind={
regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method="blind", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
DESeq_per_condition={
stop( cat("The DESeq_per_condition option does not work as it should. DESeq authors advise using the pooled method (DESeq_pooled here) instead.\n
You can accomplish a normalization equivalent to per-condition if you break your data into one matrix per-condition and use the pooled option.
Given that the method athors advise using the pooled methods anyways, I don't plan to fix this unless it is requested. For future reference, it
works up through estimateDispersions(), but fails on varianceStabilizingTransformation(). I can't find examples - and would not be able to debug
quickly"
))
#if( is.na(DESeq_metadata_table) ){ stop("To DESeq_norm_by_group you must specify a DESeq_metadata_table") }
#regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
#regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
#input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
# DESeq_metadata_table, DESeq_metadata_column, sample_names,
# DESeq_method="per-condition", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
DESeq_pooled={
if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled you must specify a DESeq_metadata_table") }
regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method="pooled", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
DESeq_pooled_CR={
if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled_CR you must specify a DESeq_metadata_table") }
regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method="pooled-CR", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
none={
input_data <- input_data
},
{
stop( paste( norm_method, " is not a valid option for method", sep="", collapse=""))
}
)
# scale normalized data [max..min] to [0..1] over the entire dataset
if ( scale_0_to_1==TRUE ){
input_data <- scale_data(input_data)
}
# create object, with specified name, that contains the preprocessed data
do.call("<<-",list(output_object, input_data))
# write flat file, with specified name, that contains the preprocessed data
write.table(input_data, file=output_file, sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")
# produce boxplots
boxplot_message <- "output boxplot: NA"
if ( produce_boxplots==TRUE ) {
if( identical(boxplots_file_out, "default") ){
boxplots_file <- paste(input_name, ".boxplots.png", sep="", collapse="")
}else{
boxplots_file <- boxplots_file_out
}
if( identical(boxplot_height_in, "default") ){ boxplot_height_in <- 8.5 }
#if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- round(ncol(input_data)/14) }
if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- 11 }
png(
filename = boxplots_file,
height = boxplot_height_in,
width = boxplot_width_in,
res = boxplot_res_dpi,
units = 'in'
)
plot.new()
split.screen(c(2,1))
screen(1)
graphics::boxplot(input_data.og, main=(paste(input_name," RAW", sep="", collapse="")), las=2, cex.axis=0.5)
screen(2)
graphics::boxplot(input_data, main=(paste(input_name," PREPROCESSED (", norm_method, " norm)", sep="", collapse="")),las=2, cex.axis=0.5)
dev.off()
boxplot_message <- paste("output boxplot: ", boxplots_file, "\n", sep="", collapse="")
}
# message to send to the user after completion, given names for object and flat file outputs
#writeLines( paste("Data have been preprocessed. Proprocessed, see ", log_file, " for details", sep="", collapse=""))
if ( create_log==TRUE ){
# name log file
log_file <- paste( output_file, ".log", sep="", collapse="")
# write log
writeLines(
paste(
"##############################################################\n",
"###################### INPUT PARAMETERS ######################\n",
"data_in: ", data_in, "\n",
"data_type: ", data_type, "\n",
"output_object: ", output_object, "\n",
"output_file: ", output_file, "\n",
"removeSg: ", as.character(removeSg),
"removeSg_valueMin: ", removeSg_valueMin, "\n",
"removeSg_rowMin: ", removeSg_rowMin, "\n",
"log_transform ", as.character(log_transform), "\n",
"norm_method: ", norm_method, "\n",
"DESeq_metadata_table: ", as.character(DESeq_metadata_table), "\n",
"DESeq_metadata_column: ", DESeq_metadata_column, "\n",
"DESeq_metadata_type: ", DESeq_metadata_type, "\n",
#"DESeq_method: ", DESeq_method, "\n",
"DESeq_sharingMode: ", DESeq_sharingMode, "\n",
"DESeq_fitType: ", DESeq_fitType, "\n",
"scale_0_to_1: ", as.character(scale_0_to_1), "\n",
"produce_boxplots: ", as.character(produce_boxplots), "\n",
"boxplot_height_in: ", boxplot_height_in, "\n",
"boxplot_width_in: ", boxplot_width_in, "\n",
"debug as.character: ", as.character(debug), "\n",
"####################### OUTPUT SUMMARY #######################\n",
"output object: ", output_object, "\n",
"otuput file: ", output_file, "\n",
boxplot_message, "\n",
regression_message, "\n",
"##############################################################",
sep="", collapse=""
),
con=log_file
)
writeLines(
paste(
"##############################################################\n",
"###################### INPUT PARAMETERS ######################\n",
"data_in: ", data_in, "\n",
"data_type: ", data_type, "\n",
"output_object: ", output_object, "\n",
"output_file: ", output_file, "\n",
"removeSg: ", as.character(removeSg),
"removeSg_valueMin: ", removeSg_valueMin, "\n",
"removeSg_rowMin: ", removeSg_rowMin, "\n",
"log_transform ", as.character(log_transform), "\n",
"norm_method: ", norm_method, "\n",
"DESeq_metadata_table: ", as.character(DESeq_metadata_table), "\n",
"DESeq_metadata_column: ", DESeq_metadata_column, "\n",
"DESeq_metadata_type: ", DESeq_metadata_type, "\n",
"DESeq_sharingMode: ", DESeq_sharingMode, "\n",
"DESeq_fitType: ", DESeq_fitType, "\n",
"scale_0_to_1: ", as.character(scale_0_to_1), "\n",
"produce_boxplots: ", as.character(produce_boxplots), "\n",
"boxplot_height_in: ", boxplot_height_in, "\n",
"boxplot_width_in: ", boxplot_width_in, "\n",
"debug as.character: ", as.character(debug), "\n",
"####################### OUTPUT SUMMARY #######################\n",
"output object: ", output_object, "\n",
"otuput file: ", output_file, "\n",
boxplot_message, "\n",
regression_message, "\n",
"##############################################################",
sep="", collapse=""
)
#con=log_file
)
}
}
######################################################################
######################################################################
### SUBS
######################################################################
######################################################################
######################################################################
### Load metadata (for groupings)
######################################################################
load_metadata <- function(group_table, group_column, sample_names){
metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
read.table(
file=group_table,row.names=1,header=TRUE,sep="\t",
colClasses = "character", check.names=FALSE,
comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
)
)
#metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]
group_names <- metadata_matrix[ order(sample_names), group_column,drop=FALSE ]
return(group_names)
}
######################################################################
######################################################################
### Sub to remove singletons
######################################################################
remove.singletons <- function (x, lim.entry, lim.row, debug) {
x <- as.matrix (x)
x [is.na (x)] <- 0
x [x < lim.entry] <- 0 # less than limit changed to 0
#x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # THIS DOES NOT WORK - KEEPS ORIGINAL MATRIX
x <- x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # row sum equal to or greater than limit is retained
if (debug==TRUE){write.table(x, file="sg_removed.txt", sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")}
x
}
######################################################################
# theMatrixWithoutRow5 = theMatrix[-5,]
# t1 <- t1[-(4:6),-(7:9)]
# mm2 <- mm[mm[,1]!=2,] # delete row if first column is 2
# data[rowSums(is.na(data)) != ncol(data),] # remove rows with any NAs
######################################################################
### Sub to log transform (base two of x+1)
######################################################################
log_data <- function(x, pseudo_count){
x <- log2(x + pseudo_count)
x
}
######################################################################
######################################################################
### sub to perform quantile normalization
######################################################################
quantile_norm_data <- function (x, ...){
data_names <- dimnames(x)
x <- normalize.quantiles(x)
dimnames(x) <- data_names
x
}
######################################################################
######################################################################
### sub to perform standardization
######################################################################
standardize_data <- function (x, ...){
mu <- matrix(apply(x, 2, mean), nr = nrow(x), nc = ncol(x), byrow = TRUE)
sigm <- apply(x, 2, sd)
sigm <- matrix(ifelse(sigm == 0, 1, sigm), nr = nrow(x), nc = ncol(x), byrow = TRUE)
x <- (x - mu)/sigm
x
}
######################################################################
######################################################################
### sub to perform DESeq normalization
######################################################################
DESeq_norm_data <- function (x, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method, DESeq_sharingMode, DESeq_fitType, DESeq_image, debug, ...){
# much of the code in this function is adapted/borrowed from two sources
# Orignal DESeq publication www.ncbi.nlm.nih.gov/pubmed/20979621
# also see vignette("DESeq")
# and Paul J. McMurdie's example analysis in a later paper http://www.ncbi.nlm.nih.gov/pubmed/24699258
# with supporing material # http://joey711.github.io/waste-not-supplemental/simulation-cluster-accuracy/simulation-cluster-accuracy-server.html
if(debug==TRUE)(print("made it here DESeq (1)"))
# check that pseudo counts are integer - must for DESeq
if ( all.equal(pseudo_count, as.integer(pseudo_count)) != TRUE ){
stop(paste("DESeq requires an integer pseudo_count, (", pseudo_count, ") is not an integer" ))
}
# import metadata matrix (from object or file)
#if(!is.na(DESeq_metadata_table)){
# my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
#}
# create metdata for the "blind" case -- all samples treated as if they are in the same group
if( identical(DESeq_method,"blind") ){
my_conditions <- as.factor(rep(1,ncol(x)))
if(debug==TRUE){my_conditions.test<<-my_conditions}
}else{
my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
metadata_factors <- as.factor(my_metadata)
if(debug==TRUE){my_metadata.test<<-my_metadata}
my_conditions <- metadata_factors
if(debug==TRUE){my_conditions.test<<-my_conditions}
}
if(debug==TRUE)(print("made it here DESeq (2)"))
# add pseudocount to prevent workflow from crashing on NaNs - DESeq will crash on non integer counts
x = x + pseudo_count
# create dataset object
if(debug==TRUE){my_conditions.test<<-my_conditions}
my_dataset <- newCountDataSet( x, my_conditions )
if(debug==TRUE){my_dataset.test1 <<- my_dataset}
if(debug==TRUE)(print("made it here DESeq (3)"))
# estimate the size factors
my_dataset <- estimateSizeFactors(my_dataset)
if(debug==TRUE)(print("made it here DESeq (4)"))
if(debug==TRUE){my_dataset.test2 <<- my_dataset}
# estimate dispersions
# reproduce this: deseq_varstab(physeq, method = "blind", sharingMode = "maximum", fitType = "local")
# see https://stat.ethz.ch/pipermail/bioconductor/2012-April/044901.html
# with DESeq code directly
# my_dataset <- estimateDispersions(my_dataset, method = "blind", sharingMode = "maximum", fitType="local")
# but this is what they did in the supplemental material for the DESeq paper (I think) -- and in figure 1 of McMurdie et al.
#my_dataset <- estimateDispersions(my_dataset, method = "pooled", sharingMode = "fit-only", fitType="local") ### THIS WORKS
# This is what they suggest in the DESeq vignette for multiple replicats
my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
# in the case of per-condition, creates an envrionment called fitInfo
# ls(my_dataset.test4@fitInfo)
# my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
if(debug==TRUE){my_dataset.test3 <<- my_dataset}
if(debug==TRUE)(print("made it here DESeq (5)"))
# Determine which column(s) have the dispersion estimates
dispcol = grep("disp\\_", colnames(fData(my_dataset)))
# Enforce that there are no infinite values in the dispersion estimates
#if (any(!is.finite(fData(my_dataset)[, dispcol]))) {
# fData(cds)[which(!is.finite(fData(my_dataset)[, dispcol])), dispcol] <- 0
#}
if(debug==TRUE)(print("made it here DESeq (6)"))
# apply variance stabilization normalization
#if ( identical(DESeq_method, "per-condition") ){
# produce a plot of the regression
if(DESeq_image==TRUE){
png(
filename = regression_filename,
height = 8.5,
width = 11,
res = 300,
units = 'in'
)
#plot.new()
plotDispEsts( my_dataset )
dev.off()
}
if(debug==TRUE)(print("made it here DESeq (7)"))
my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
# ls(my_dataset.test4@fitInfo)
# my_dataset.test4@fitInfo$Kirsten$fittedDispEsts
if(debug==TRUE){my_dataset.test4 <<- my_dataset.normed}
#}else{
# my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
#}
# return matrix of normed values
x <- exprs(my_dataset.normed)
x
}
######################################################################
######################################################################
### sub to scale dataset values from [min..max] to [0..1]
######################################################################
scale_data <- function(x){
shift <- min(x, na.rm = TRUE)
scale <- max(x, na.rm = TRUE) - shift
if (scale != 0) x <- (x - shift)/scale
x
}
######################################################################
|
/preprocessing_tool.r
|
no_license
|
RonaldHShi/Ronald-and-Mert
|
R
| false
| false
| 25,225
|
r
|
preprocessing_tool <- function(
data_in, # name of the input file (tab delimited text with the raw counts) or R matrix
data_type ="file", # c(file, r_matrix)
output_object ="default", # output R object (matrix)
output_file ="default", # output flat file
removeSg = TRUE, # boolean to remove singleton counts
removeSg_valueMin = 2, # lowest retained value (lower converted to 0)
removeSg_rowMin = 4, # lowest retained row sum (lower, row is removed)
log_transform = FALSE,
norm_method = "DESeq_blind", #c("standardize", "quantile", "DESeq_blind", "DESeq_per_condition", "DESeq_pooled", "DESeq_pooled_CR", "none"), # USE blind if not replicates -- use pooled to get DESeq default
pseudo_count = 1, # has to be integer for DESeq
DESeq_metadata_table = NA, # only used if method is other than "blind"
DESeq_metadata_column = 1, # only used if method is other than "blind"
DESeq_metadata_type = "file", # c( "file", "r_matrix" )
#DESeq_method = "blind", # c( "pooled", "pooled-CR", "per-condition", "blind" ) # blind, treat everything as one group
DESeq_sharingMode = "maximum", # c( "maximum", "fit-only", "gene-est-only" ) # maximum is the most conservative choice
DESeq_fitType = "local", # c( "parametric", "local" )
DESeq_image = TRUE, # create dispersion vs mean plot indicate DESeq regression
scale_0_to_1 = TRUE,
produce_boxplots = FALSE,
boxplots_file_out = "default",
boxplot_height_in = "default", # 11,
boxplot_width_in = "default", #"8.5,
boxplot_res_dpi = 300,
create_log = TRUE,
debug = FALSE
)
{
# Install DESeq
#source("https://bioconductor.org/biocLite.R")
#biocLite("DESeq")
# check for necessary packages, install if they are not there
#require(matR) || install.packages("matR", repo="http://mcs.anl.gov/~braithwaite/R", type="source")
#chooseCRANmirror()
setRepositories(ind=1:8)
#####source("http://bioconductor.org/biocLite.R")
# Install packages if they are not already installed
#if ( is.element("DESeq", installed.packages()[,1]) == FALSE ){ source("http://bioconductor.org/biocLite.R"); biocLite("DESeq") }
#if ( is.element("preprocessCore", installed.packages()[,1]) == FALSE ){ source("http://bioconductor.org/biocLite.R"); biocLite("preprocessCore") }
#if ( is.element("RColorBrewer", installed.packages()[,1]) == FALSE ){ install.packages("RColorBrewer") }
#require(preprocessCore) || install.packages("preprocessCore")
#require(DESeq) || biocLite("DESeq") # update to DESeq2 when I have a chance
#####if ( is.element("RColorBrewer", installed.packages()[,1]) == FALSE ){ install.packages("RColorBrewer") }
#####if ( is.element("preprocessCore", installed.packages()[,1]) == FALSE ){ biocLite("preprocessCore") }
#####if ( is.element("DESeq", installed.packages()[,1]) == FALSE ){ biocLite("DESeq") }
# (DESeq): www.ncbi.nlm.nih.gov/pubmed/20979621
#library(preprocessCore)
#library(DESeq)
#library(RColorBrewer)
###### MAIN
# get the name of the data object if an object is used -- use the filename if input is filename string
if ( identical( data_type, "file") ){
input_name <- data_in
}else if( identical( data_type, "r_matrix") ){
input_name <- deparse(substitute(data_in))
}else{
stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
}
# Generate names for the output file and object
if ( identical( output_object, "default") ){
output_object <- paste( input_name, ".", norm_method, ".PREPROCESSED" , sep="", collapse="")
}
if ( identical( output_file, "default") ){
output_file <- paste( input_name, ".", norm_method, ".PREPROCESSED.txt" , sep="", collapse="")
}
# Input the data
if ( identical( data_type, "file") ){
input_data <- data.matrix(read.table(data_in, row.names=1, header=TRUE, sep="\t", comment.char="", quote="", check.names=FALSE))
}else if( identical( data_type, "r_matrix") ){
input_data <- data.matrix(data_in)
}else{
stop( paste( data_type, " is not a valid option for data_type", sep="", collapse=""))
}
# sort the data (COLUMNWISE) by id
sample_names <- order(colnames(input_data))
input_data <- input_data[,sample_names]
# make a copy of the input data that is not processed
input_data.og <- input_data
# non optional, convert "na's" to 0
input_data[is.na(input_data)] <- 0
# remove singletons
if(removeSg==TRUE){
input_data <- remove.singletons(x=input_data, lim.entry=removeSg_valueMin, lim.row=removeSg_rowMin, debug=debug)
}
# log transform log(x+1)2
if ( log_transform==TRUE ){
input_data <- log_data(input_data, pseudo_count)
}
regression_message <- "DESeq regression: NA"
# Normalize -- stadardize or quantile norm (depends on user selection)
switch(
norm_method,
standardize={
input_data <- standardize_data(input_data)
},
quantile={
input_data <- quantile_norm_data(input_data)
},
DESeq_blind={
regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method="blind", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
DESeq_per_condition={
stop( cat("The DESeq_per_condition option does not work as it should. DESeq authors advise using the pooled method (DESeq_pooled here) instead.\n
You can accomplish a normalization equivalent to per-condition if you break your data into one matrix per-condition and use the pooled option.
Given that the method athors advise using the pooled methods anyways, I don't plan to fix this unless it is requested. For future reference, it
works up through estimateDispersions(), but fails on varianceStabilizingTransformation(). I can't find examples - and would not be able to debug
quickly"
))
#if( is.na(DESeq_metadata_table) ){ stop("To DESeq_norm_by_group you must specify a DESeq_metadata_table") }
#regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
#regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
#input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
# DESeq_metadata_table, DESeq_metadata_column, sample_names,
# DESeq_method="per-condition", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
DESeq_pooled={
if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled you must specify a DESeq_metadata_table") }
regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method="pooled", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
DESeq_pooled_CR={
if( is.na(DESeq_metadata_table) ){ stop("To DESeq_pooled_CR you must specify a DESeq_metadata_table") }
regression_filename = paste( input_name, ".DESeq_regression.png", sep="", collapse="" )
regression_message <- paste("DESeq regression: ", regression_filename, sep="", collapse="" )
input_data <- DESeq_norm_data(input_data, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method="pooled-CR", DESeq_sharingMode, DESeq_fitType, DESeq_image, debug)
},
none={
input_data <- input_data
},
{
stop( paste( norm_method, " is not a valid option for method", sep="", collapse=""))
}
)
# scale normalized data [max..min] to [0..1] over the entire dataset
if ( scale_0_to_1==TRUE ){
input_data <- scale_data(input_data)
}
# create object, with specified name, that contains the preprocessed data
do.call("<<-",list(output_object, input_data))
# write flat file, with specified name, that contains the preprocessed data
write.table(input_data, file=output_file, sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")
# produce boxplots
boxplot_message <- "output boxplot: NA"
if ( produce_boxplots==TRUE ) {
if( identical(boxplots_file_out, "default") ){
boxplots_file <- paste(input_name, ".boxplots.png", sep="", collapse="")
}else{
boxplots_file <- boxplots_file_out
}
if( identical(boxplot_height_in, "default") ){ boxplot_height_in <- 8.5 }
#if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- round(ncol(input_data)/14) }
if( identical(boxplot_width_in, "default") ){ boxplot_width_in <- 11 }
png(
filename = boxplots_file,
height = boxplot_height_in,
width = boxplot_width_in,
res = boxplot_res_dpi,
units = 'in'
)
plot.new()
split.screen(c(2,1))
screen(1)
graphics::boxplot(input_data.og, main=(paste(input_name," RAW", sep="", collapse="")), las=2, cex.axis=0.5)
screen(2)
graphics::boxplot(input_data, main=(paste(input_name," PREPROCESSED (", norm_method, " norm)", sep="", collapse="")),las=2, cex.axis=0.5)
dev.off()
boxplot_message <- paste("output boxplot: ", boxplots_file, "\n", sep="", collapse="")
}
# message to send to the user after completion, given names for object and flat file outputs
#writeLines( paste("Data have been preprocessed. Proprocessed, see ", log_file, " for details", sep="", collapse=""))
if ( create_log==TRUE ){
# name log file
log_file <- paste( output_file, ".log", sep="", collapse="")
# write log
writeLines(
paste(
"##############################################################\n",
"###################### INPUT PARAMETERS ######################\n",
"data_in: ", data_in, "\n",
"data_type: ", data_type, "\n",
"output_object: ", output_object, "\n",
"output_file: ", output_file, "\n",
"removeSg: ", as.character(removeSg),
"removeSg_valueMin: ", removeSg_valueMin, "\n",
"removeSg_rowMin: ", removeSg_rowMin, "\n",
"log_transform ", as.character(log_transform), "\n",
"norm_method: ", norm_method, "\n",
"DESeq_metadata_table: ", as.character(DESeq_metadata_table), "\n",
"DESeq_metadata_column: ", DESeq_metadata_column, "\n",
"DESeq_metadata_type: ", DESeq_metadata_type, "\n",
#"DESeq_method: ", DESeq_method, "\n",
"DESeq_sharingMode: ", DESeq_sharingMode, "\n",
"DESeq_fitType: ", DESeq_fitType, "\n",
"scale_0_to_1: ", as.character(scale_0_to_1), "\n",
"produce_boxplots: ", as.character(produce_boxplots), "\n",
"boxplot_height_in: ", boxplot_height_in, "\n",
"boxplot_width_in: ", boxplot_width_in, "\n",
"debug as.character: ", as.character(debug), "\n",
"####################### OUTPUT SUMMARY #######################\n",
"output object: ", output_object, "\n",
"otuput file: ", output_file, "\n",
boxplot_message, "\n",
regression_message, "\n",
"##############################################################",
sep="", collapse=""
),
con=log_file
)
writeLines(
paste(
"##############################################################\n",
"###################### INPUT PARAMETERS ######################\n",
"data_in: ", data_in, "\n",
"data_type: ", data_type, "\n",
"output_object: ", output_object, "\n",
"output_file: ", output_file, "\n",
"removeSg: ", as.character(removeSg),
"removeSg_valueMin: ", removeSg_valueMin, "\n",
"removeSg_rowMin: ", removeSg_rowMin, "\n",
"log_transform ", as.character(log_transform), "\n",
"norm_method: ", norm_method, "\n",
"DESeq_metadata_table: ", as.character(DESeq_metadata_table), "\n",
"DESeq_metadata_column: ", DESeq_metadata_column, "\n",
"DESeq_metadata_type: ", DESeq_metadata_type, "\n",
"DESeq_sharingMode: ", DESeq_sharingMode, "\n",
"DESeq_fitType: ", DESeq_fitType, "\n",
"scale_0_to_1: ", as.character(scale_0_to_1), "\n",
"produce_boxplots: ", as.character(produce_boxplots), "\n",
"boxplot_height_in: ", boxplot_height_in, "\n",
"boxplot_width_in: ", boxplot_width_in, "\n",
"debug as.character: ", as.character(debug), "\n",
"####################### OUTPUT SUMMARY #######################\n",
"output object: ", output_object, "\n",
"otuput file: ", output_file, "\n",
boxplot_message, "\n",
regression_message, "\n",
"##############################################################",
sep="", collapse=""
)
#con=log_file
)
}
}
######################################################################
######################################################################
### SUBS
######################################################################
######################################################################
######################################################################
### Load metadata (for groupings)
######################################################################
load_metadata <- function(group_table, group_column, sample_names){
metadata_matrix <- as.matrix( # Load the metadata table (same if you use one or all columns)
read.table(
file=group_table,row.names=1,header=TRUE,sep="\t",
colClasses = "character", check.names=FALSE,
comment.char = "",quote="",fill=TRUE,blank.lines.skip=FALSE
)
)
#metadata_matrix <- metadata_matrix[ order(sample_names),,drop=FALSE ]
group_names <- metadata_matrix[ order(sample_names), group_column,drop=FALSE ]
return(group_names)
}
######################################################################
######################################################################
### Sub to remove singletons
######################################################################
remove.singletons <- function (x, lim.entry, lim.row, debug) {
x <- as.matrix (x)
x [is.na (x)] <- 0
x [x < lim.entry] <- 0 # less than limit changed to 0
#x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # THIS DOES NOT WORK - KEEPS ORIGINAL MATRIX
x <- x [ apply(x, MARGIN = 1, sum) >= lim.row, ] # row sum equal to or greater than limit is retained
if (debug==TRUE){write.table(x, file="sg_removed.txt", sep="\t", col.names = NA, row.names = TRUE, quote = FALSE, eol="\n")}
x
}
######################################################################
# theMatrixWithoutRow5 = theMatrix[-5,]
# t1 <- t1[-(4:6),-(7:9)]
# mm2 <- mm[mm[,1]!=2,] # delete row if first column is 2
# data[rowSums(is.na(data)) != ncol(data),] # remove rows with any NAs
######################################################################
### Sub to log transform (base two of x+1)
######################################################################
log_data <- function(x, pseudo_count){
x <- log2(x + pseudo_count)
x
}
######################################################################
######################################################################
### sub to perform quantile normalization
######################################################################
quantile_norm_data <- function (x, ...){
data_names <- dimnames(x)
x <- normalize.quantiles(x)
dimnames(x) <- data_names
x
}
######################################################################
######################################################################
### sub to perform standardization
######################################################################
standardize_data <- function (x, ...){
mu <- matrix(apply(x, 2, mean), nr = nrow(x), nc = ncol(x), byrow = TRUE)
sigm <- apply(x, 2, sd)
sigm <- matrix(ifelse(sigm == 0, 1, sigm), nr = nrow(x), nc = ncol(x), byrow = TRUE)
x <- (x - mu)/sigm
x
}
######################################################################
######################################################################
### sub to perform DESeq normalization
######################################################################
DESeq_norm_data <- function (x, regression_filename, pseudo_count,
DESeq_metadata_table, DESeq_metadata_column, sample_names,
DESeq_method, DESeq_sharingMode, DESeq_fitType, DESeq_image, debug, ...){
# much of the code in this function is adapted/borrowed from two sources
# Orignal DESeq publication www.ncbi.nlm.nih.gov/pubmed/20979621
# also see vignette("DESeq")
# and Paul J. McMurdie's example analysis in a later paper http://www.ncbi.nlm.nih.gov/pubmed/24699258
# with supporing material # http://joey711.github.io/waste-not-supplemental/simulation-cluster-accuracy/simulation-cluster-accuracy-server.html
if(debug==TRUE)(print("made it here DESeq (1)"))
# check that pseudo counts are integer - must for DESeq
if ( all.equal(pseudo_count, as.integer(pseudo_count)) != TRUE ){
stop(paste("DESeq requires an integer pseudo_count, (", pseudo_count, ") is not an integer" ))
}
# import metadata matrix (from object or file)
#if(!is.na(DESeq_metadata_table)){
# my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
#}
# create metdata for the "blind" case -- all samples treated as if they are in the same group
if( identical(DESeq_method,"blind") ){
my_conditions <- as.factor(rep(1,ncol(x)))
if(debug==TRUE){my_conditions.test<<-my_conditions}
}else{
my_metadata <- load_metadata(DESeq_metadata_table, DESeq_metadata_column, sample_names)
metadata_factors <- as.factor(my_metadata)
if(debug==TRUE){my_metadata.test<<-my_metadata}
my_conditions <- metadata_factors
if(debug==TRUE){my_conditions.test<<-my_conditions}
}
if(debug==TRUE)(print("made it here DESeq (2)"))
# add pseudocount to prevent workflow from crashing on NaNs - DESeq will crash on non integer counts
x = x + pseudo_count
# create dataset object
if(debug==TRUE){my_conditions.test<<-my_conditions}
my_dataset <- newCountDataSet( x, my_conditions )
if(debug==TRUE){my_dataset.test1 <<- my_dataset}
if(debug==TRUE)(print("made it here DESeq (3)"))
# estimate the size factors
my_dataset <- estimateSizeFactors(my_dataset)
if(debug==TRUE)(print("made it here DESeq (4)"))
if(debug==TRUE){my_dataset.test2 <<- my_dataset}
# estimate dispersions
# reproduce this: deseq_varstab(physeq, method = "blind", sharingMode = "maximum", fitType = "local")
# see https://stat.ethz.ch/pipermail/bioconductor/2012-April/044901.html
# with DESeq code directly
# my_dataset <- estimateDispersions(my_dataset, method = "blind", sharingMode = "maximum", fitType="local")
# but this is what they did in the supplemental material for the DESeq paper (I think) -- and in figure 1 of McMurdie et al.
#my_dataset <- estimateDispersions(my_dataset, method = "pooled", sharingMode = "fit-only", fitType="local") ### THIS WORKS
# This is what they suggest in the DESeq vignette for multiple replicats
my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
# in the case of per-condition, creates an envrionment called fitInfo
# ls(my_dataset.test4@fitInfo)
# my_dataset <- estimateDispersions(my_dataset, method = DESeq_method, sharingMode = DESeq_sharingMode, fitType = DESeq_fitType)
if(debug==TRUE){my_dataset.test3 <<- my_dataset}
if(debug==TRUE)(print("made it here DESeq (5)"))
# Determine which column(s) have the dispersion estimates
dispcol = grep("disp\\_", colnames(fData(my_dataset)))
# Enforce that there are no infinite values in the dispersion estimates
#if (any(!is.finite(fData(my_dataset)[, dispcol]))) {
# fData(cds)[which(!is.finite(fData(my_dataset)[, dispcol])), dispcol] <- 0
#}
if(debug==TRUE)(print("made it here DESeq (6)"))
# apply variance stabilization normalization
#if ( identical(DESeq_method, "per-condition") ){
# produce a plot of the regression
if(DESeq_image==TRUE){
png(
filename = regression_filename,
height = 8.5,
width = 11,
res = 300,
units = 'in'
)
#plot.new()
plotDispEsts( my_dataset )
dev.off()
}
if(debug==TRUE)(print("made it here DESeq (7)"))
my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
# ls(my_dataset.test4@fitInfo)
# my_dataset.test4@fitInfo$Kirsten$fittedDispEsts
if(debug==TRUE){my_dataset.test4 <<- my_dataset.normed}
#}else{
# my_dataset.normed <- varianceStabilizingTransformation(my_dataset)
#}
# return matrix of normed values
x <- exprs(my_dataset.normed)
x
}
######################################################################
######################################################################
### sub to scale dataset values from [min..max] to [0..1]
######################################################################
scale_data <- function(x){
shift <- min(x, na.rm = TRUE)
scale <- max(x, na.rm = TRUE) - shift
if (scale != 0) x <- (x - shift)/scale
x
}
######################################################################
|
time<-as.character(Sys.time()-60*60*24)
options(stringsAsFactors = FALSE)
library("RCurl")
library("XML")
library("plyr")
url<-"http://www.vnukovo.ru/flights/online-timetable/#tab-sortie"
html <- getURL(url, followlocation = TRUE,encoding="gzip",httpheader = c(`Accept-Encoding` = "gzip"),.encoding="UTF-8")
doc = htmlParse(html, asText=TRUE)
# now take basic info in common table
flights<- xpathSApply(doc, "//tr", xmlValue)
flights<-gsub("\n","",flights)
flights<-gsub("\r","",flights)
info<-list(1)
for (i in 1:length(flights)){
t<-strsplit(flights[i],split=" ")[[1]]
t<-unique(t[!t==""])
info[[i]]<-paste0(t,collapse=";")
}
df<- data.frame(matrix(unlist(info), nrow=length(flights), byrow=T))
file<-as.character(paste("vko_D",time,sep="_"))
file_name<-paste(file,"csv",sep=".")
write.csv(df,file_name)
q(save="no")
|
/vko_today.R
|
no_license
|
pavlov-aa/Parsing-aeroflights-table
|
R
| false
| false
| 831
|
r
|
time<-as.character(Sys.time()-60*60*24)
options(stringsAsFactors = FALSE)
library("RCurl")
library("XML")
library("plyr")
url<-"http://www.vnukovo.ru/flights/online-timetable/#tab-sortie"
html <- getURL(url, followlocation = TRUE,encoding="gzip",httpheader = c(`Accept-Encoding` = "gzip"),.encoding="UTF-8")
doc = htmlParse(html, asText=TRUE)
# now take basic info in common table
flights<- xpathSApply(doc, "//tr", xmlValue)
flights<-gsub("\n","",flights)
flights<-gsub("\r","",flights)
info<-list(1)
for (i in 1:length(flights)){
t<-strsplit(flights[i],split=" ")[[1]]
t<-unique(t[!t==""])
info[[i]]<-paste0(t,collapse=";")
}
df<- data.frame(matrix(unlist(info), nrow=length(flights), byrow=T))
file<-as.character(paste("vko_D",time,sep="_"))
file_name<-paste(file,"csv",sep=".")
write.csv(df,file_name)
q(save="no")
|
/newpostKnit.R
|
no_license
|
R-adas/R-adas-source
|
R
| false
| false
| 7,493
|
r
| ||
#' The application User-Interface
#'
#' @param request Internal parameter for `{shiny}`.
#' DO NOT REMOVE.
#' @import shiny
#' @noRd
app_ui <- function(request) {
tagList(
# Leave this function for adding external resources
golem_add_external_resources(),
# List the first level UI elements here
fluidPage(
h1("BTM")
)
)
}
#' Add external Resources to the Application
#'
#' This function is internally used to add external
#' resources inside the Shiny application.
#'
#' @import shiny
#' @importFrom golem add_resource_path activate_js favicon bundle_resources
#' @noRd
golem_add_external_resources <- function(){
add_resource_path(
'www', app_sys('app/www')
)
tags$head(
favicon(),
bundle_resources(
path = app_sys('app/www'),
app_title = 'BTM'
)
# Add here other external resources
# for example, you can add shinyalert::useShinyalert()
)
}
|
/BTM/R/app_ui.R
|
no_license
|
MaryleneH/prez_dataquitaine
|
R
| false
| false
| 937
|
r
|
#' The application User-Interface
#'
#' @param request Internal parameter for `{shiny}`.
#' DO NOT REMOVE.
#' @import shiny
#' @noRd
app_ui <- function(request) {
tagList(
# Leave this function for adding external resources
golem_add_external_resources(),
# List the first level UI elements here
fluidPage(
h1("BTM")
)
)
}
#' Add external Resources to the Application
#'
#' This function is internally used to add external
#' resources inside the Shiny application.
#'
#' @import shiny
#' @importFrom golem add_resource_path activate_js favicon bundle_resources
#' @noRd
golem_add_external_resources <- function(){
add_resource_path(
'www', app_sys('app/www')
)
tags$head(
favicon(),
bundle_resources(
path = app_sys('app/www'),
app_title = 'BTM'
)
# Add here other external resources
# for example, you can add shinyalert::useShinyalert()
)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/interpolate.R
\name{fun_xy}
\alias{fun_xy}
\title{Interpolation between curve points}
\usage{
fun_xy(df_mtp, x_out, x_name = "hours", y_name = "fit",
feat_name = x_name)
}
\arguments{
\item{df_mtp}{The data frame containing \code{x} and \code{y} to interpolate}
\item{x_out}{the \code{x} to evaluate \code{y}}
\item{x_name}{the name of \code{x} (chr) in the data frame}
\item{y_name}{the name of \code{y} (chr) in the data frame}
\item{feat_name}{the root name of the feature, defaults to \code{x_name}}
}
\value{
returns a data frame with \code{feature} and \code{value}
}
\description{
The function will currently find the mean \code{y} for a given \code{x}. Only
works for monotonic functions. A future enhancement could be to loop through
\code{y} segments to find \code{y} for a given \code{x} within each segment.
This would be equivalent to rough root finding function. Such segments could
be found using: \code{rlen(x > x_out)}
}
\examples{
# An example
df <- dplyr::data_frame(hours = 1:10, fit = 2*hours)
class(df) <- c("mtp", "data.frame", "tbl_df")
ggplot2::qplot(x= hours, y = fit, data = df, geom = "line")
fun_xy(df, c(2.5, 3.2, 4.1))
}
\seealso{
\code{\link{mtp_feature}}
}
|
/man/fun_xy.Rd
|
no_license
|
JannikVindeloev/RAPr
|
R
| false
| true
| 1,276
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/interpolate.R
\name{fun_xy}
\alias{fun_xy}
\title{Interpolation between curve points}
\usage{
fun_xy(df_mtp, x_out, x_name = "hours", y_name = "fit",
feat_name = x_name)
}
\arguments{
\item{df_mtp}{The data frame containing \code{x} and \code{y} to interpolate}
\item{x_out}{the \code{x} to evaluate \code{y}}
\item{x_name}{the name of \code{x} (chr) in the data frame}
\item{y_name}{the name of \code{y} (chr) in the data frame}
\item{feat_name}{the root name of the feature, defaults to \code{x_name}}
}
\value{
returns a data frame with \code{feature} and \code{value}
}
\description{
The function will currently find the mean \code{y} for a given \code{x}. Only
works for monotonic functions. A future enhancement could be to loop through
\code{y} segments to find \code{y} for a given \code{x} within each segment.
This would be equivalent to rough root finding function. Such segments could
be found using: \code{rlen(x > x_out)}
}
\examples{
# An example
df <- dplyr::data_frame(hours = 1:10, fit = 2*hours)
class(df) <- c("mtp", "data.frame", "tbl_df")
ggplot2::qplot(x= hours, y = fit, data = df, geom = "line")
fun_xy(df, c(2.5, 3.2, 4.1))
}
\seealso{
\code{\link{mtp_feature}}
}
|
#' Plot grouped or hierarchical time series
#'
#' Method for plotting grouped or hierarchical time series and their forecasts.
#'
#'
#' @param x An object of class \code{\link[hts]{gts}}.
#' @param include Number of values from historical time series to include in
#' the plot of forecasted group/hierarchical time series.
#' @param levels Integer(s) or string(s) giving the specified levels(s) to be
#' plotted
#' @param labels If \code{TRUE}, plot the labels next to each series
#' @param col Vector of colours, passed to \code{plot.ts} and to \code{lines}
#' @param color_lab If \code{TRUE}, colour the direct labels to match line
#' colours. If \code{FALSE} will be as per \code{par()$fg}.
#' @param \dots Other arguments passing to \code{\link[graphics]{plot.default}}
#' @author Rob J Hyndman and Earo Wang
#' @seealso \code{\link[hts]{aggts}}
#' @references R. J. Hyndman, R. A. Ahmed, G. Athanasopoulos and H.L. Shang
#' (2011) Optimal combination forecasts for hierarchical time series.
#' \emph{Computational Statistics and Data Analysis}, \bold{55}(9), 2579--2589.
#' \url{http://robjhyndman.com/papers/hierarchical/}
#' @keywords hplot
#' @method plot gts
#' @examples
#'
#' plot(htseg1, levels = c(0, 2))
#' plot(infantgts, include = 10, levels = "State")
#' plot(infantgts, include = 10, levels = "State",
#' col = colours()[100:107], lty = 1:8, color_lab = TRUE)
#'
#' @export
#' @export plot.gts
plot.gts <- function(x, include, levels, labels = TRUE,
col = NULL, color_lab = FALSE, ...) {
# Do plotting
#
# Args:
# x: hts or gts
# include: No. of historical data included in the plot.
# levels: which level or group to display.
# labels: text labels
#
# Return:
# hts or gts plots
#
# Error Handling:
if (!is.gts(x)) {
stop("Argument x must be either hts or gts object.", call. = FALSE)
}
if (!is.null(x$histy)) {
histx <- aggts(x, levels, forecasts = FALSE)
fcasts <- aggts(x, levels, forecasts = TRUE)
} else {
histx <- aggts(x, levels)
}
if (missing(include)) {
histx <- histx
include <- nrow(histx)
} else {
tspx <- stats::tsp(histx)
histx <- stats::window(histx, start = tspx[2L] - include/tspx[3L] + 1L/tspx[3L])
}
if (missing(levels)) {
if (is.hts(x)) {
levels <- 0L:length(x$nodes)
} else {
levels <- 0L:(nrow(x$groups) - 1L)
}
}
l.levels <- length(levels)
if (is.character(levels)) {
levels <- which(names(x$labels) %in% levels)
}
levels <- as.integer(levels) + 1L
dots.list <- match.call(expand.dots = FALSE)$`...`
opar <- par(mfrow = c(l.levels, 1L), mar = c(3, 4, 4, 2))
on.exit(par(opar))
if (is.hts(x)) {
m <- Mnodes(x$nodes)[levels]
} else {
m <- Mlevel(x$groups)[levels]
x$labels <- c(Total = "Total", x$labels, Bottom = list(colnames(x$bts)))
}
cs <- c(0L, cumsum(m))
for (i in 1L:l.levels) {
end <- cs[i + 1L]
start <- cs[i] + 1L
series <- seq(start, end)
if(is.null(col)){
cols <- grDevices::rainbow(length(series))
} else {
cols <- col
}
if(!is.null(x$histy)) {
ylim <- range(histx[, series], fcasts[, series], na.rm = TRUE)
if (labels) {
strlabels <- max(strwidth(x$labels[levels], units = "figure"))
xlim <- range(time(histx)[1L] - strlabels, time(fcasts),
na.rm = TRUE)
} else {
xlim <- range(time(histx), time(fcasts), na.rm = TRUE)
}
} else {
ylim <- range(histx[, series], na.rm = TRUE)
if (labels) {
strlabels <- max(strwidth(x$labels[levels], units = "figure"))
timex <- time(histx)
xlim <- range(timex[1L] - strlabels, timex, na.rm = TRUE)
} else {
xlim <- range(time(histx), na.rm = TRUE)
}
}
if (is.null(dots.list$xlim)) {
plot(histx[, series, drop = FALSE], col = cols, xlim = xlim, ylim = ylim,
xlab = "", ylab = "", main = names(x$labels)[levels][i],
plot.type = "single",
type = ifelse(length(1:include) == 1L, "p", "l"),
...)
} else {
plot(histx[, series, drop = FALSE], col = cols, ylim = ylim,
xlab = "", ylab = "", main = names(x$labels)[levels][i],
plot.type = "single",
type = ifelse(length(1:include) == 1L, "p", "l"),
...)
}
if (!is.null(x$histy)) {
for (j in 1L:length(series)) {
lines(fcasts[, series[j], drop = FALSE], lty = 2, col = cols[j],
type = ifelse(nrow(fcasts) == 1L, "p", "l"))
}
}
if (labels) {
if(color_lab){
lab_col <- cols
} else {
lab_col <- par()$fg
}
text(x = stats::tsp(histx)[1L] + 0.1, y = histx[1L, series] + 0.2,
labels = unlist(x$labels[levels][i]),
cex = 0.9, adj = 1, col = lab_col)
}
}
}
|
/R/plot-gts.R
|
no_license
|
VaughanR0/Streamline-R
|
R
| false
| false
| 5,023
|
r
|
#' Plot grouped or hierarchical time series
#'
#' Method for plotting grouped or hierarchical time series and their forecasts.
#'
#'
#' @param x An object of class \code{\link[hts]{gts}}.
#' @param include Number of values from historical time series to include in
#' the plot of forecasted group/hierarchical time series.
#' @param levels Integer(s) or string(s) giving the specified levels(s) to be
#' plotted
#' @param labels If \code{TRUE}, plot the labels next to each series
#' @param col Vector of colours, passed to \code{plot.ts} and to \code{lines}
#' @param color_lab If \code{TRUE}, colour the direct labels to match line
#' colours. If \code{FALSE} will be as per \code{par()$fg}.
#' @param \dots Other arguments passing to \code{\link[graphics]{plot.default}}
#' @author Rob J Hyndman and Earo Wang
#' @seealso \code{\link[hts]{aggts}}
#' @references R. J. Hyndman, R. A. Ahmed, G. Athanasopoulos and H.L. Shang
#' (2011) Optimal combination forecasts for hierarchical time series.
#' \emph{Computational Statistics and Data Analysis}, \bold{55}(9), 2579--2589.
#' \url{http://robjhyndman.com/papers/hierarchical/}
#' @keywords hplot
#' @method plot gts
#' @examples
#'
#' plot(htseg1, levels = c(0, 2))
#' plot(infantgts, include = 10, levels = "State")
#' plot(infantgts, include = 10, levels = "State",
#' col = colours()[100:107], lty = 1:8, color_lab = TRUE)
#'
#' @export
#' @export plot.gts
plot.gts <- function(x, include, levels, labels = TRUE,
col = NULL, color_lab = FALSE, ...) {
# Do plotting
#
# Args:
# x: hts or gts
# include: No. of historical data included in the plot.
# levels: which level or group to display.
# labels: text labels
#
# Return:
# hts or gts plots
#
# Error Handling:
if (!is.gts(x)) {
stop("Argument x must be either hts or gts object.", call. = FALSE)
}
if (!is.null(x$histy)) {
histx <- aggts(x, levels, forecasts = FALSE)
fcasts <- aggts(x, levels, forecasts = TRUE)
} else {
histx <- aggts(x, levels)
}
if (missing(include)) {
histx <- histx
include <- nrow(histx)
} else {
tspx <- stats::tsp(histx)
histx <- stats::window(histx, start = tspx[2L] - include/tspx[3L] + 1L/tspx[3L])
}
if (missing(levels)) {
if (is.hts(x)) {
levels <- 0L:length(x$nodes)
} else {
levels <- 0L:(nrow(x$groups) - 1L)
}
}
l.levels <- length(levels)
if (is.character(levels)) {
levels <- which(names(x$labels) %in% levels)
}
levels <- as.integer(levels) + 1L
dots.list <- match.call(expand.dots = FALSE)$`...`
opar <- par(mfrow = c(l.levels, 1L), mar = c(3, 4, 4, 2))
on.exit(par(opar))
if (is.hts(x)) {
m <- Mnodes(x$nodes)[levels]
} else {
m <- Mlevel(x$groups)[levels]
x$labels <- c(Total = "Total", x$labels, Bottom = list(colnames(x$bts)))
}
cs <- c(0L, cumsum(m))
for (i in 1L:l.levels) {
end <- cs[i + 1L]
start <- cs[i] + 1L
series <- seq(start, end)
if(is.null(col)){
cols <- grDevices::rainbow(length(series))
} else {
cols <- col
}
if(!is.null(x$histy)) {
ylim <- range(histx[, series], fcasts[, series], na.rm = TRUE)
if (labels) {
strlabels <- max(strwidth(x$labels[levels], units = "figure"))
xlim <- range(time(histx)[1L] - strlabels, time(fcasts),
na.rm = TRUE)
} else {
xlim <- range(time(histx), time(fcasts), na.rm = TRUE)
}
} else {
ylim <- range(histx[, series], na.rm = TRUE)
if (labels) {
strlabels <- max(strwidth(x$labels[levels], units = "figure"))
timex <- time(histx)
xlim <- range(timex[1L] - strlabels, timex, na.rm = TRUE)
} else {
xlim <- range(time(histx), na.rm = TRUE)
}
}
if (is.null(dots.list$xlim)) {
plot(histx[, series, drop = FALSE], col = cols, xlim = xlim, ylim = ylim,
xlab = "", ylab = "", main = names(x$labels)[levels][i],
plot.type = "single",
type = ifelse(length(1:include) == 1L, "p", "l"),
...)
} else {
plot(histx[, series, drop = FALSE], col = cols, ylim = ylim,
xlab = "", ylab = "", main = names(x$labels)[levels][i],
plot.type = "single",
type = ifelse(length(1:include) == 1L, "p", "l"),
...)
}
if (!is.null(x$histy)) {
for (j in 1L:length(series)) {
lines(fcasts[, series[j], drop = FALSE], lty = 2, col = cols[j],
type = ifelse(nrow(fcasts) == 1L, "p", "l"))
}
}
if (labels) {
if(color_lab){
lab_col <- cols
} else {
lab_col <- par()$fg
}
text(x = stats::tsp(histx)[1L] + 0.1, y = histx[1L, series] + 0.2,
labels = unlist(x$labels[levels][i]),
cex = 0.9, adj = 1, col = lab_col)
}
}
}
|
setwd("~/Documents/github/headr/dev")
library(glue)
library(yaml)
meta <- yaml.load_file("_metadata.yaml")
helper_glue <- function(...) glue::glue_data(..., .open = "<<", .close = ">>")
hdr_abstract <- function(meta){
helper_glue(.x = meta, "<<abstract>>")
}
helper_author <- function(x) {
# format name
name <- helper_glue(.x = x, "\\\\author{<<name>>}")
# format affiliation(s)
aff <- helper_glue(.x = x, "\\\\affiliation{<<affiliation>>}")
if(length(x) > 1) aff[-1] <- gsub("affiliation", "alsoaffiliation", aff[-1])
# email (if corresponding author)
email <- if(x$corresponding) helper_glue(x, "\\\\email{<<email>>}") else ""
glue::collapse(c(name, aff, email), "\n")
}
fun_title <- function(meta) helper_glue(meta, "\\\\title{<<title>>}")
fun_authors <- function(meta) glue::collapse(unlist(lapply(meta$authors, helper_author)), "\n")
fun_extra <- function(meta) helper_glue(meta, "\n\\\\abbreviations{<<glue::collapse(abbreviations,',')>>}\n\\\\keywords{<<glue::collapse(keywords,',')>>}")
fun_date <- function(meta) helper_glue(meta, "\\\\date{<<date>>}")
fun_title(meta)
fun_authors(meta)
fun_extra(meta)
fun_date(meta)
hdr_abstract(meta)
|
/dev/testing_acs.r
|
no_license
|
tpall/headr
|
R
| false
| false
| 1,185
|
r
|
setwd("~/Documents/github/headr/dev")
library(glue)
library(yaml)
meta <- yaml.load_file("_metadata.yaml")
helper_glue <- function(...) glue::glue_data(..., .open = "<<", .close = ">>")
hdr_abstract <- function(meta){
helper_glue(.x = meta, "<<abstract>>")
}
helper_author <- function(x) {
# format name
name <- helper_glue(.x = x, "\\\\author{<<name>>}")
# format affiliation(s)
aff <- helper_glue(.x = x, "\\\\affiliation{<<affiliation>>}")
if(length(x) > 1) aff[-1] <- gsub("affiliation", "alsoaffiliation", aff[-1])
# email (if corresponding author)
email <- if(x$corresponding) helper_glue(x, "\\\\email{<<email>>}") else ""
glue::collapse(c(name, aff, email), "\n")
}
fun_title <- function(meta) helper_glue(meta, "\\\\title{<<title>>}")
fun_authors <- function(meta) glue::collapse(unlist(lapply(meta$authors, helper_author)), "\n")
fun_extra <- function(meta) helper_glue(meta, "\n\\\\abbreviations{<<glue::collapse(abbreviations,',')>>}\n\\\\keywords{<<glue::collapse(keywords,',')>>}")
fun_date <- function(meta) helper_glue(meta, "\\\\date{<<date>>}")
fun_title(meta)
fun_authors(meta)
fun_extra(meta)
fun_date(meta)
hdr_abstract(meta)
|
library(glmnet)
mydata = read.table("./TrainingSet/ReliefF/breast.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.65,family="gaussian",standardize=TRUE)
sink('./Model/EN/ReliefF/breast/breast_069.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
|
/Model/EN/ReliefF/breast/breast_069.R
|
no_license
|
leon1003/QSMART
|
R
| false
| false
| 352
|
r
|
library(glmnet)
mydata = read.table("./TrainingSet/ReliefF/breast.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.65,family="gaussian",standardize=TRUE)
sink('./Model/EN/ReliefF/breast/breast_069.txt',append=TRUE)
print(glm$glmnet.fit)
sink()
|
##' AlignmentPairsList
##'
##' @export
##' @rdname AlignmentPairsList-class
##'
##' @importFrom methods new
##'
setMethod("AlignmentPairsList", "list",
function(obj) new("AlignmentPairsList", listData = obj))
##' as.data.frame
##'
##' @description Convert AlignmentPairsList to data.frame.
##'
##' @param x AlignmentPairsList object
##' @param ... additional parameters to lapply
##' @param .id name of id column added by dplyr::bind_rows
##'
##' @return data.frame
##'
##' @importFrom dplyr bind_rows
##'
##' @export
##'
setMethod("as.data.frame", signature = "AlignmentPairsList",
function(x, ..., .id="id") {
dplyr::bind_rows(lapply(x, as.data.frame, ...), .id=.id)
})
##' autoplot.AlignmentPairsList
##'
##' @importFrom ggplot2 autoplot ggplot geom_point geom_boxplot
##' geom_violin geom_density facet_wrap
##'
##' @param object AlignmentPairsList
##' @param aes aes mapping
##' @param vars variable mapping to facet plots
##' @param ... additional parameters to ggplot function
##' @param which which plot to make. 'grid' option makes a scatter
##' plot with marginal densities
##'
##' @export
##'
autoplot.AlignmentPairsList <- function(object, aes, vars, ..., which="point") {
data <- as.data.frame(object)
p <- ggplot(data, {{ aes }})
which <- match.arg(which, c("point", "boxplot", "violin", "density"))
if (which == "point")
p <- p + geom_point(...)
else if (which == "boxplot")
p <- p + geom_boxplot(...)
else if (which == "violin")
p <- p + geom_violin(...)
else if (which == "density")
p <- p + geom_density(...)
if (!missing(vars))
p <- p + facet_wrap( {{ vars }} )
p
}
##' plot
##'
##' @description plot an AlignmentPairsList
##'
##' @param x object to plot
##' @param ... additional arguments for autoplot
##'
##' @export
##' @importFrom graphics plot
##'
plot.AlignmentPairsList <- function(x, ...) {
print(autoplot(x, ...))
}
|
/R/methods-AlignmentPairsList-class.R
|
permissive
|
NBISweden/ripr
|
R
| false
| false
| 1,964
|
r
|
##' AlignmentPairsList
##'
##' @export
##' @rdname AlignmentPairsList-class
##'
##' @importFrom methods new
##'
setMethod("AlignmentPairsList", "list",
function(obj) new("AlignmentPairsList", listData = obj))
##' as.data.frame
##'
##' @description Convert AlignmentPairsList to data.frame.
##'
##' @param x AlignmentPairsList object
##' @param ... additional parameters to lapply
##' @param .id name of id column added by dplyr::bind_rows
##'
##' @return data.frame
##'
##' @importFrom dplyr bind_rows
##'
##' @export
##'
setMethod("as.data.frame", signature = "AlignmentPairsList",
function(x, ..., .id="id") {
dplyr::bind_rows(lapply(x, as.data.frame, ...), .id=.id)
})
##' autoplot.AlignmentPairsList
##'
##' @importFrom ggplot2 autoplot ggplot geom_point geom_boxplot
##' geom_violin geom_density facet_wrap
##'
##' @param object AlignmentPairsList
##' @param aes aes mapping
##' @param vars variable mapping to facet plots
##' @param ... additional parameters to ggplot function
##' @param which which plot to make. 'grid' option makes a scatter
##' plot with marginal densities
##'
##' @export
##'
autoplot.AlignmentPairsList <- function(object, aes, vars, ..., which="point") {
data <- as.data.frame(object)
p <- ggplot(data, {{ aes }})
which <- match.arg(which, c("point", "boxplot", "violin", "density"))
if (which == "point")
p <- p + geom_point(...)
else if (which == "boxplot")
p <- p + geom_boxplot(...)
else if (which == "violin")
p <- p + geom_violin(...)
else if (which == "density")
p <- p + geom_density(...)
if (!missing(vars))
p <- p + facet_wrap( {{ vars }} )
p
}
##' plot
##'
##' @description plot an AlignmentPairsList
##'
##' @param x object to plot
##' @param ... additional arguments for autoplot
##'
##' @export
##' @importFrom graphics plot
##'
plot.AlignmentPairsList <- function(x, ...) {
print(autoplot(x, ...))
}
|
#' Plot shapefiles
#'
#' Plot geography shapefiles using geom_sf
#'
#' @import sf
#' @import tmap
#' @import ggplot2
#' @param data An sf object that contains the geometries
#' @param method Plotting method. Can be "sf" or "tmap"
#' @param fill_with (Optional) The variable from the sf object to fill the polygons.
#' @param tmap_mode Map mode if tmap is chosen as the mapping method.
#' @param alpha Transparency
#' @param ... Other arguments passed on to `geom_sf`, `tmap_polygons`, and `tmap_dots`
#'
#' @return A ggplot or tmap object.
#' @export
#'
#'
plot_map <- function(data, method = "tmap", fill_with, tmap_mode = "view", alpha = 0.5, ...){
if(!method %in% c("sf", "tmap")){
stop("Method should be `sf` or `tmap`")
}
if(method != "tmap" & tmap_mode == "plot"){
stop("Set method to `tmap`.")
}
if(!"sf" %in% class(data) & !"sfc" %in% class(data)){
n1 <- nrow(data)
data <- data %>%
dplyr::filter(!is.na(.data$lat) & !is.na(.data$lon)) %>%
sf::st_as_sf(coords = c("lon", "lat"),
crs = 4326)
n2 <- nrow(data)
if(n2 < n1){
warning(paste0(n1 - n2, " observation(s) have been dropped due to missing lat/lon."))
}
}
if(method == "sf"){
if("sfc_POINT" %in% class(data$geometry)){
if(missing(fill_with)){
p <- ggplot(data) +
geom_sf(...) +
theme_void()
} else {
p <- ggplot(data) +
geom_sf(aes(color = {{fill_with}}), ...) +
theme_void()
}
}
if("sfc_MULTIPOLYGON" %in% class(data$geometry) | "sfc_POLYGON" %in% class(data$geometry) | "sfc_GEOMETRY" %in% class(data)){
if(missing(fill_with)){
p <- ggplot(data) +
geom_sf(alpha = alpha) +
theme_void()
} else {
p <- ggplot(data) +
geom_sf(aes(fill = {{fill_with}}), alpha = alpha) +
theme_void()
}
}
}
if(method == "tmap"){
if(!tmap_mode %in% c("view", "plot")){
stop("`tmap_mode` should be `view` or `plot`.")
}
if(tmap_mode == "view"){
tmap::tmap_mode("view")
}
if(tmap_mode == "plot"){
tmap::tmap_mode("plot")
}
if("sfc_POINT" %in% class(data$geometry)){
if(missing(fill_with)){
p <- tm_shape(data) +
tm_dots(...) +
tm_layout(frame = FALSE)
} else {
p <- tm_shape(data) +
tm_dots(col = quo_name(enquo(fill_with)), ...) +
tm_layout(frame = FALSE, legend.position = c("right","bottom"), legend.outside = TRUE)
}
}
if("sfc_MULTIPOLYGON" %in% class(data$geometry) | "sfc_POLYGON" %in% class(data$geometry) | "sfc_GEOMETRY" %in% class(data) | "sfc_POLYGON" %in% class(data)){
if(missing(fill_with)){
p <- tm_shape(data) +
tm_polygons(alpha = alpha, ...) +
tm_layout(frame = FALSE)
} else {
p <- tm_shape(data) +
tm_polygons(col = quo_name(enquo(fill_with)), alpha = alpha, ...) +
tm_layout(frame = FALSE, legend.position = c("right","bottom"), legend.outside = TRUE)
}
}
}
p
}
|
/R/plot_map.R
|
no_license
|
franc703/minnccaccess
|
R
| false
| false
| 2,868
|
r
|
#' Plot shapefiles
#'
#' Plot geography shapefiles using geom_sf
#'
#' @import sf
#' @import tmap
#' @import ggplot2
#' @param data An sf object that contains the geometries
#' @param method Plotting method. Can be "sf" or "tmap"
#' @param fill_with (Optional) The variable from the sf object to fill the polygons.
#' @param tmap_mode Map mode if tmap is chosen as the mapping method.
#' @param alpha Transparency
#' @param ... Other arguments passed on to `geom_sf`, `tmap_polygons`, and `tmap_dots`
#'
#' @return A ggplot or tmap object.
#' @export
#'
#'
plot_map <- function(data, method = "tmap", fill_with, tmap_mode = "view", alpha = 0.5, ...){
if(!method %in% c("sf", "tmap")){
stop("Method should be `sf` or `tmap`")
}
if(method != "tmap" & tmap_mode == "plot"){
stop("Set method to `tmap`.")
}
if(!"sf" %in% class(data) & !"sfc" %in% class(data)){
n1 <- nrow(data)
data <- data %>%
dplyr::filter(!is.na(.data$lat) & !is.na(.data$lon)) %>%
sf::st_as_sf(coords = c("lon", "lat"),
crs = 4326)
n2 <- nrow(data)
if(n2 < n1){
warning(paste0(n1 - n2, " observation(s) have been dropped due to missing lat/lon."))
}
}
if(method == "sf"){
if("sfc_POINT" %in% class(data$geometry)){
if(missing(fill_with)){
p <- ggplot(data) +
geom_sf(...) +
theme_void()
} else {
p <- ggplot(data) +
geom_sf(aes(color = {{fill_with}}), ...) +
theme_void()
}
}
if("sfc_MULTIPOLYGON" %in% class(data$geometry) | "sfc_POLYGON" %in% class(data$geometry) | "sfc_GEOMETRY" %in% class(data)){
if(missing(fill_with)){
p <- ggplot(data) +
geom_sf(alpha = alpha) +
theme_void()
} else {
p <- ggplot(data) +
geom_sf(aes(fill = {{fill_with}}), alpha = alpha) +
theme_void()
}
}
}
if(method == "tmap"){
if(!tmap_mode %in% c("view", "plot")){
stop("`tmap_mode` should be `view` or `plot`.")
}
if(tmap_mode == "view"){
tmap::tmap_mode("view")
}
if(tmap_mode == "plot"){
tmap::tmap_mode("plot")
}
if("sfc_POINT" %in% class(data$geometry)){
if(missing(fill_with)){
p <- tm_shape(data) +
tm_dots(...) +
tm_layout(frame = FALSE)
} else {
p <- tm_shape(data) +
tm_dots(col = quo_name(enquo(fill_with)), ...) +
tm_layout(frame = FALSE, legend.position = c("right","bottom"), legend.outside = TRUE)
}
}
if("sfc_MULTIPOLYGON" %in% class(data$geometry) | "sfc_POLYGON" %in% class(data$geometry) | "sfc_GEOMETRY" %in% class(data) | "sfc_POLYGON" %in% class(data)){
if(missing(fill_with)){
p <- tm_shape(data) +
tm_polygons(alpha = alpha, ...) +
tm_layout(frame = FALSE)
} else {
p <- tm_shape(data) +
tm_polygons(col = quo_name(enquo(fill_with)), alpha = alpha, ...) +
tm_layout(frame = FALSE, legend.position = c("right","bottom"), legend.outside = TRUE)
}
}
}
p
}
|
lefftpack::lazy_setup()
source("FG12_funcs.r")
# words that could be used
words <- c("blue","green","fun", "square","dog","owl","emu")
# objects that could be referred to
objects <- c("blue_square","blue_owl","blue_dog","blue_emu",
"green_square","green_emu", "green_dog",
"fun_dog", "fun_emu",
"square_owl")
# get a random obj and a random utt
# obj <- random_referent(objects) # --> "square_owl"
# utt <- random_utterance(words) # --> "square"
# LETS JUST DECIDE TO USE THIS EXAMPLE INSTEAD:
obj <- "square_owl"
utt <- "square"
sapply(words, function(w) length(extension(w, objects=objects)))
c(`using object:` = obj, ` using utterance:` = utt)
#####################
# ten objects, so object prior is 1/10 = .1
(sq_owl_prior <- prior_obj(obj, objects))
# seven words, so utterance prior is 1/7 = .143
(sq_prior <- prior_word(utt, words))
# probability of choosing 'square' to refer to the square owl
(likhood <- eqn2(utt, obj, objects, words))
# the normalizing constant we use to get a probability for the posterior
(norm_constant <- sum(sapply(objects, function(o) eqn2(utt,o,objects,words))))
# now we can calculate the posterior prob of referring to the square owl
# by saying 'square' in the context via bayes rule:
(sq_owl_posterior <- (sq_owl_prior * likhood) / norm_constant)
# this is the same thing as just using equation 1:
eqn1(obj, utt, objects, words)
# which is wrapped by
prob_ref_given_word_in_context(obj, utt, objects, words) # .0714
square_owl_prior <- prior_obj(obj, objects)
the_likhood <- eqn2(utt, obj, objects, words)
norm_constant <- sum(sapply(objects, function(o) eqn2(utt,o,objects,words)))
square_owl_prior * the_likhood / norm_constant
prob_word_given_ref_in_context("square", "square_owl", objects, words)
# just applies equation 2:
# >> say we have "square owl", call it SO
# >> there are ten words, and eight objects
# >> two objects are owls ("blue_owl", "square_owl")
# >> three things are square ("blue_square", "green_square", "square_owl")
# >> two words apply to SO ("square", "owl")
# >> then we have:
# (1 / 3) / ((1/3) + (1/2))
# ANOTHER EXAMPLE
# words <- c("blue","green","red", "owl","dog")
# objects <- c("blue_dog","green_dog","red_dog","green_owl","red_owl")
# utt <- "owl"; obj <- "green_owl"
# sapply(words, function(w) length(extension(w, objects=objects)))
|
/paper03_goodman_frank2012/FG12_sandbox.r
|
no_license
|
lefft/UoC_ling_comp_modeling
|
R
| false
| false
| 2,440
|
r
|
lefftpack::lazy_setup()
source("FG12_funcs.r")
# words that could be used
words <- c("blue","green","fun", "square","dog","owl","emu")
# objects that could be referred to
objects <- c("blue_square","blue_owl","blue_dog","blue_emu",
"green_square","green_emu", "green_dog",
"fun_dog", "fun_emu",
"square_owl")
# get a random obj and a random utt
# obj <- random_referent(objects) # --> "square_owl"
# utt <- random_utterance(words) # --> "square"
# LETS JUST DECIDE TO USE THIS EXAMPLE INSTEAD:
obj <- "square_owl"
utt <- "square"
sapply(words, function(w) length(extension(w, objects=objects)))
c(`using object:` = obj, ` using utterance:` = utt)
#####################
# ten objects, so object prior is 1/10 = .1
(sq_owl_prior <- prior_obj(obj, objects))
# seven words, so utterance prior is 1/7 = .143
(sq_prior <- prior_word(utt, words))
# probability of choosing 'square' to refer to the square owl
(likhood <- eqn2(utt, obj, objects, words))
# the normalizing constant we use to get a probability for the posterior
(norm_constant <- sum(sapply(objects, function(o) eqn2(utt,o,objects,words))))
# now we can calculate the posterior prob of referring to the square owl
# by saying 'square' in the context via bayes rule:
(sq_owl_posterior <- (sq_owl_prior * likhood) / norm_constant)
# this is the same thing as just using equation 1:
eqn1(obj, utt, objects, words)
# which is wrapped by
prob_ref_given_word_in_context(obj, utt, objects, words) # .0714
square_owl_prior <- prior_obj(obj, objects)
the_likhood <- eqn2(utt, obj, objects, words)
norm_constant <- sum(sapply(objects, function(o) eqn2(utt,o,objects,words)))
square_owl_prior * the_likhood / norm_constant
prob_word_given_ref_in_context("square", "square_owl", objects, words)
# just applies equation 2:
# >> say we have "square owl", call it SO
# >> there are ten words, and eight objects
# >> two objects are owls ("blue_owl", "square_owl")
# >> three things are square ("blue_square", "green_square", "square_owl")
# >> two words apply to SO ("square", "owl")
# >> then we have:
# (1 / 3) / ((1/3) + (1/2))
# ANOTHER EXAMPLE
# words <- c("blue","green","red", "owl","dog")
# objects <- c("blue_dog","green_dog","red_dog","green_owl","red_owl")
# utt <- "owl"; obj <- "green_owl"
# sapply(words, function(w) length(extension(w, objects=objects)))
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/datasets.R
\docType{data}
\name{clean.goa}
\alias{clean.goa}
\title{Clean Gulf of Alaska
Clean data set for the Gulf of Alaska bottom trawl survey}
\format{A dim = 197026 x 48 data.table data.frame:
\tabular{rlll}{
[,1] \tab ref \tab character \tab reference taxonomic ID from raw data\cr
[,2] \tab stratum \tab character \tab the statistical stratum of the haul\cr
[,3] \tab lat \tab numeric \tab latitude of the haul\cr
[,4] \tab lon \tab numeric \tab longitude of the haul, in western hemisphere degrees (for lon > 0, do lon-360)\cr
[,5] \tab station \tab character \tab the station ID for the haul\cr
[,6] \tab year \tab integer \tab year of haul\cr
[,7] \tab datetime \tab c("POSIXct", "POSIXt") \tab the day and time of the haul\cr
[,8] \tab wtcpue \tab numeric \tab weight (mass) of the catch\cr
[,9] \tab cntcpue \tab numeric \tab number of individuals caught per hectare in the haul\cr
[,10] \tab SID \tab character \tab species identification number\cr
[,11] \tab depth \tab numeric \tab the maximum depth of the water at the location of the haul\cr
[,12] \tab btemp \tab numeric \tab water temperature at the bottom at the location of the haul\cr
[,13] \tab stemp \tab numeric \tab water temperature at the surface at the location of the haul\cr
[,14] \tab vessel \tab character \tab vessel ID\cr
[,15] \tab cruise \tab character \tab cruise ID\cr
[,16] \tab haul \tab character \tab the integer haul number within a cruise\cr
[,17] \tab stratumarea \tab numeric \tab the area of the statistical stratum (km2)\cr
[,18] \tab haulid \tab character \tab a unique identifier for the haul; vessel ID - cruise ID - haul number\cr
[,19] \tab season \tab character \tab insert_description_here\cr
[,20] \tab reg \tab character \tab survey region\cr
[,21] \tab val.src \tab character \tab indicates the degree of 'fuzziness' required to find a match to ref in a data.base of taxonomic information; m1 indicates perfect match, m2 indicates that capitalization, whitespace, etc (see \code{\link{cull}}) needed to be adjusted, m3 indicates that \code{\link{agrep}} was used, and m4 means that measures in both m2 and m3 were taken to find the match. See \code{\link{match.tbl}}.\cr
[,22] \tab tbl.row \tab integer \tab the row in the taxonomic data base where a match was found. See \code{\link{match.tbl}}.\cr
[,23] \tab mtch.src \tab integer \tab the database containing the match; 1 is taxInfo, 2 is spp.corr1, 3 is getSppData; if matches are found in multiple sources, a match to 1 takes precedence over 1 & 2, and 2 over 3. See \code{\link{match.tbl}}.\cr
[,24] \tab tax.src \tab character \tab informs source of taxonomic correction of ref to spp and other tax info; is taxInfo if found from manually checked spreadsheet\cr
[,25] \tab spp \tab character \tab species scientific name; Genus species\cr
[,26] \tab common \tab character \tab the common name of the organism sampled\cr
[,27] \tab taxLvl \tab character \tab the most specific level of classification indicated by spp\cr
[,28] \tab species \tab character \tab the species name of the species\cr
[,29] \tab genus \tab character \tab the genus of the species\cr
[,30] \tab family \tab character \tab taxonomic family\cr
[,31] \tab order \tab character \tab taxonomic order\cr
[,32] \tab class \tab character \tab taxonomic class\cr
[,33] \tab superclass \tab character \tab taxonomic superclass\cr
[,34] \tab subphylum \tab character \tab taxonomic subphylum\cr
[,35] \tab phylum \tab character \tab insert_description_here\cr
[,36] \tab kingdom \tab character \tab taxonomic kingdom\cr
[,37] \tab trophicDiet \tab character \tab source of trophic level from Fish Base or Sea Life Base; 'y' means it was from this source\cr
[,38] \tab trophicOrig \tab character \tab from Fish Base or Sea Life Base; was the trophic level estimated from an 'Original sample'?\cr
[,39] \tab Picture \tab character \tab Is there a picture of this critter assoicated with the package? Note: this isn't always accurate\cr
[,40] \tab trophicLevel \tab numeric \tab the trophic level from Fish Base or Sea Life Base\cr
[,41] \tab trophicLevel.se \tab numeric \tab the standard error of the trophic level\cr
[,42] \tab tax.src2 \tab character \tab informs source of taxonomic correct; the name of a source of taxonomic information other than taxInfo (other than manual entries)\cr
[,43] \tab conflict \tab logical \tab for a given 'spp' value in spp.key, was there a conflict in the other taxonomic columns? E.g., a single spp corresponding to multiple common names; also TRUE if different ref values were found in different databases (affecting the val.src, tbl.row, mtch.src, tax.src, etc columns), but then the refs converged to same spp -- that would not necessarily be an error, but might deserve checking\cr
[,44] \tab flag \tab character \tab flag related to correcting taxonomic information; relates to automated input, potential errors, and signature of people or methods that have made corrections to spp.key\cr
[,45] \tab website \tab character \tab URL reference for taxonomic information\cr
[,46] \tab website2 \tab character \tab secondary URL reference for taxonomic information; often used when website finds the name for a spp name as entered, but website2 points to the most up-to-date scientific name\cr
[,47] \tab keep.row \tab logical \tab Column indicating whether or not the row show likely be excluded\cr
[,48] \tab row_flag \tab character \tab if keep.row is TRUE, why was this row flagged to be dropped?\cr
}}
\usage{
clean.goa
}
\description{
Clean Gulf of Alaska
Clean data set for the Gulf of Alaska bottom trawl survey
}
\keyword{datasets}
|
/man/clean.goa.Rd
|
no_license
|
rBatt/trawlData
|
R
| false
| true
| 5,701
|
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/datasets.R
\docType{data}
\name{clean.goa}
\alias{clean.goa}
\title{Clean Gulf of Alaska
Clean data set for the Gulf of Alaska bottom trawl survey}
\format{A dim = 197026 x 48 data.table data.frame:
\tabular{rlll}{
[,1] \tab ref \tab character \tab reference taxonomic ID from raw data\cr
[,2] \tab stratum \tab character \tab the statistical stratum of the haul\cr
[,3] \tab lat \tab numeric \tab latitude of the haul\cr
[,4] \tab lon \tab numeric \tab longitude of the haul, in western hemisphere degrees (for lon > 0, do lon-360)\cr
[,5] \tab station \tab character \tab the station ID for the haul\cr
[,6] \tab year \tab integer \tab year of haul\cr
[,7] \tab datetime \tab c("POSIXct", "POSIXt") \tab the day and time of the haul\cr
[,8] \tab wtcpue \tab numeric \tab weight (mass) of the catch\cr
[,9] \tab cntcpue \tab numeric \tab number of individuals caught per hectare in the haul\cr
[,10] \tab SID \tab character \tab species identification number\cr
[,11] \tab depth \tab numeric \tab the maximum depth of the water at the location of the haul\cr
[,12] \tab btemp \tab numeric \tab water temperature at the bottom at the location of the haul\cr
[,13] \tab stemp \tab numeric \tab water temperature at the surface at the location of the haul\cr
[,14] \tab vessel \tab character \tab vessel ID\cr
[,15] \tab cruise \tab character \tab cruise ID\cr
[,16] \tab haul \tab character \tab the integer haul number within a cruise\cr
[,17] \tab stratumarea \tab numeric \tab the area of the statistical stratum (km2)\cr
[,18] \tab haulid \tab character \tab a unique identifier for the haul; vessel ID - cruise ID - haul number\cr
[,19] \tab season \tab character \tab insert_description_here\cr
[,20] \tab reg \tab character \tab survey region\cr
[,21] \tab val.src \tab character \tab indicates the degree of 'fuzziness' required to find a match to ref in a data.base of taxonomic information; m1 indicates perfect match, m2 indicates that capitalization, whitespace, etc (see \code{\link{cull}}) needed to be adjusted, m3 indicates that \code{\link{agrep}} was used, and m4 means that measures in both m2 and m3 were taken to find the match. See \code{\link{match.tbl}}.\cr
[,22] \tab tbl.row \tab integer \tab the row in the taxonomic data base where a match was found. See \code{\link{match.tbl}}.\cr
[,23] \tab mtch.src \tab integer \tab the database containing the match; 1 is taxInfo, 2 is spp.corr1, 3 is getSppData; if matches are found in multiple sources, a match to 1 takes precedence over 1 & 2, and 2 over 3. See \code{\link{match.tbl}}.\cr
[,24] \tab tax.src \tab character \tab informs source of taxonomic correction of ref to spp and other tax info; is taxInfo if found from manually checked spreadsheet\cr
[,25] \tab spp \tab character \tab species scientific name; Genus species\cr
[,26] \tab common \tab character \tab the common name of the organism sampled\cr
[,27] \tab taxLvl \tab character \tab the most specific level of classification indicated by spp\cr
[,28] \tab species \tab character \tab the species name of the species\cr
[,29] \tab genus \tab character \tab the genus of the species\cr
[,30] \tab family \tab character \tab taxonomic family\cr
[,31] \tab order \tab character \tab taxonomic order\cr
[,32] \tab class \tab character \tab taxonomic class\cr
[,33] \tab superclass \tab character \tab taxonomic superclass\cr
[,34] \tab subphylum \tab character \tab taxonomic subphylum\cr
[,35] \tab phylum \tab character \tab insert_description_here\cr
[,36] \tab kingdom \tab character \tab taxonomic kingdom\cr
[,37] \tab trophicDiet \tab character \tab source of trophic level from Fish Base or Sea Life Base; 'y' means it was from this source\cr
[,38] \tab trophicOrig \tab character \tab from Fish Base or Sea Life Base; was the trophic level estimated from an 'Original sample'?\cr
[,39] \tab Picture \tab character \tab Is there a picture of this critter assoicated with the package? Note: this isn't always accurate\cr
[,40] \tab trophicLevel \tab numeric \tab the trophic level from Fish Base or Sea Life Base\cr
[,41] \tab trophicLevel.se \tab numeric \tab the standard error of the trophic level\cr
[,42] \tab tax.src2 \tab character \tab informs source of taxonomic correct; the name of a source of taxonomic information other than taxInfo (other than manual entries)\cr
[,43] \tab conflict \tab logical \tab for a given 'spp' value in spp.key, was there a conflict in the other taxonomic columns? E.g., a single spp corresponding to multiple common names; also TRUE if different ref values were found in different databases (affecting the val.src, tbl.row, mtch.src, tax.src, etc columns), but then the refs converged to same spp -- that would not necessarily be an error, but might deserve checking\cr
[,44] \tab flag \tab character \tab flag related to correcting taxonomic information; relates to automated input, potential errors, and signature of people or methods that have made corrections to spp.key\cr
[,45] \tab website \tab character \tab URL reference for taxonomic information\cr
[,46] \tab website2 \tab character \tab secondary URL reference for taxonomic information; often used when website finds the name for a spp name as entered, but website2 points to the most up-to-date scientific name\cr
[,47] \tab keep.row \tab logical \tab Column indicating whether or not the row show likely be excluded\cr
[,48] \tab row_flag \tab character \tab if keep.row is TRUE, why was this row flagged to be dropped?\cr
}}
\usage{
clean.goa
}
\description{
Clean Gulf of Alaska
Clean data set for the Gulf of Alaska bottom trawl survey
}
\keyword{datasets}
|
library(mixOmics)
# Get some test data
dataset<-as.matrix(data(linnerud))
X <- as.matrix(as.data.frame(linnerud$exercise))
Y <- as.matrix(as.data.frame(linnerud$physiological))
## Create folds
kfolds <- 10
folds <- sample(cut(seq(1,nrow(X)),breaks=kfolds,labels=1:kfolds),size=nrow(X))
ncomp<-c(1:min(ncol(X),nrow(X)))
Q2.matrix<-NULL
Q2.total<-c()
MSEP.total<-c()
#Perform 10 fold cross validation
for(k in 1:kfolds) {
#Segement your data by fold using the which() function
testIndeces <- which(folds==k,arr.ind=TRUE)
x_train <- X[-testIndeces,, drop=FALSE]
y_train <- Y[-testIndeces,, drop=FALSE]
x_test <- X[testIndeces,,drop=FALSE]
y_test <- Y[testIndeces,, drop=FALSE]
model<-pls(x_train,y_train, ncomp=max(ncomp))
pred <- predict(model,x_test)
MSEP<-seq(1:max(ncomp))
Q2<-seq(1:max(ncomp))
for (j in 1:max(ncomp)) {
MSEP[j]<-mean((y_test-pred$predict[,,j])^2)
Q2[j]<-1-sum((y_test-pred$predict[,,j])^2)/(sum((y_test-mean(y_test))^2))
}
Q2.matrix<-rbind(Q2.matrix,Q2)
MSEP.matrix<-rbind(MSEP.matrix, MSEP)
}
Q2.total<-apply(Q2.matrix, 2, mean)
MSEP.total<-apply(MSEP.matrix, 2, mean)
modelPLS <- pls(X,Y, ncomp=1)
## Run PLS on all the folds
for (j in 1:i) {
pls_train <- pls(trainData$X,trainData$Y, ncomp=1, scale=TRUE,mode='regression') #(fit on the train data)
pls_test <- predict(pls_train,newdata=testData) #Get the predicitons for the validation set (from the model just fit on the train data)
}
# For each fold
for(j in 1:k){
# Fit the model with each subset of predictors on the training part of the fold
best.fit=regsubsets(Salary~.,data=Hitters[folds!=j,], nvmax=19)
# For each subset
for(i in 1:19){
# Predict on the hold out part of the fold for that subset
pred=predict(best.fit, Hitters[folds==j,],id=i)
# Get the mean squared error for the model trained on the fold with the subset
cv.errors[j,i]=mean((Hitters$Salary[folds==j]-pred)^2)
}
}
######################
## Predict values on test set
predict(test)
## compute RMSEP
MSEP<-mean((Y-y_pred)^2/nrow(Y))
## take the average of MSEP
### Go over all number of components and return MSEP values for every comp
fitted_models <- lapply(ncomp,FUN=function(k) { model<-pls(x_train,y_train, ncomp=k)
pred <- predict(model,x_test)
MSEP<-seq(1:k)
for (j in 1:k) { MSEP[j]<-mean((y_test-pred$predict[,,j])^2)}
return(MSEP)})
|
/Code/Test_environment/Calib/calibration_cross_validate_PLS.R
|
no_license
|
puczilka/PLS
|
R
| false
| false
| 2,378
|
r
|
library(mixOmics)
# Get some test data
dataset<-as.matrix(data(linnerud))
X <- as.matrix(as.data.frame(linnerud$exercise))
Y <- as.matrix(as.data.frame(linnerud$physiological))
## Create folds
kfolds <- 10
folds <- sample(cut(seq(1,nrow(X)),breaks=kfolds,labels=1:kfolds),size=nrow(X))
ncomp<-c(1:min(ncol(X),nrow(X)))
Q2.matrix<-NULL
Q2.total<-c()
MSEP.total<-c()
#Perform 10 fold cross validation
for(k in 1:kfolds) {
#Segement your data by fold using the which() function
testIndeces <- which(folds==k,arr.ind=TRUE)
x_train <- X[-testIndeces,, drop=FALSE]
y_train <- Y[-testIndeces,, drop=FALSE]
x_test <- X[testIndeces,,drop=FALSE]
y_test <- Y[testIndeces,, drop=FALSE]
model<-pls(x_train,y_train, ncomp=max(ncomp))
pred <- predict(model,x_test)
MSEP<-seq(1:max(ncomp))
Q2<-seq(1:max(ncomp))
for (j in 1:max(ncomp)) {
MSEP[j]<-mean((y_test-pred$predict[,,j])^2)
Q2[j]<-1-sum((y_test-pred$predict[,,j])^2)/(sum((y_test-mean(y_test))^2))
}
Q2.matrix<-rbind(Q2.matrix,Q2)
MSEP.matrix<-rbind(MSEP.matrix, MSEP)
}
Q2.total<-apply(Q2.matrix, 2, mean)
MSEP.total<-apply(MSEP.matrix, 2, mean)
modelPLS <- pls(X,Y, ncomp=1)
## Run PLS on all the folds
for (j in 1:i) {
pls_train <- pls(trainData$X,trainData$Y, ncomp=1, scale=TRUE,mode='regression') #(fit on the train data)
pls_test <- predict(pls_train,newdata=testData) #Get the predicitons for the validation set (from the model just fit on the train data)
}
# For each fold
for(j in 1:k){
# Fit the model with each subset of predictors on the training part of the fold
best.fit=regsubsets(Salary~.,data=Hitters[folds!=j,], nvmax=19)
# For each subset
for(i in 1:19){
# Predict on the hold out part of the fold for that subset
pred=predict(best.fit, Hitters[folds==j,],id=i)
# Get the mean squared error for the model trained on the fold with the subset
cv.errors[j,i]=mean((Hitters$Salary[folds==j]-pred)^2)
}
}
######################
## Predict values on test set
predict(test)
## compute RMSEP
MSEP<-mean((Y-y_pred)^2/nrow(Y))
## take the average of MSEP
### Go over all number of components and return MSEP values for every comp
fitted_models <- lapply(ncomp,FUN=function(k) { model<-pls(x_train,y_train, ncomp=k)
pred <- predict(model,x_test)
MSEP<-seq(1:k)
for (j in 1:k) { MSEP[j]<-mean((y_test-pred$predict[,,j])^2)}
return(MSEP)})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.