blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
327
content_id
stringlengths
40
40
detected_licenses
listlengths
0
91
license_type
stringclasses
2 values
repo_name
stringlengths
5
134
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
46 values
visit_date
timestamp[us]date
2016-08-02 22:44:29
2023-09-06 08:39:28
revision_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
committer_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
github_id
int64
19.4k
671M
star_events_count
int64
0
40k
fork_events_count
int64
0
32.4k
gha_license_id
stringclasses
14 values
gha_event_created_at
timestamp[us]date
2012-06-21 16:39:19
2023-09-14 21:52:42
gha_created_at
timestamp[us]date
2008-05-25 01:21:32
2023-06-28 13:19:12
gha_language
stringclasses
60 values
src_encoding
stringclasses
24 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
9.18M
extension
stringclasses
20 values
filename
stringlengths
1
141
content
stringlengths
7
9.18M
8f3615f123fe149b8fed8ef4f1ec63a165df5d4e
34228cca7152d4e9b586d447ad744db7195a6e2f
/plot3.R
57ac13244c04db83fde045522198932298e24512
[]
no_license
dborisog/ExData_Plotting1
2401f7ea2685487b525ed0fc069164bd0807439d
30e375441207cd9e0cd2ec3a2e2efee4d6a01f77
refs/heads/master
2020-04-05T18:55:51.866294
2014-05-11T20:08:27
2014-05-11T20:08:27
null
0
0
null
null
null
null
UTF-8
R
false
false
747
r
plot3.R
setwd("C:/Users/user/gitrep/ExData_Plotting1") source("preprocessedData.R") ################## # make plot ################## ##### input ###### # NA ################## ##### output ##### # NA makePlot3 <- function() { dataSet <- importData() png(filename = "plot3.png", width = 480, height = 480, units = "px") cols = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3") plot(dataSet$DateTime, dataSet$Sub_metering_1, type="l", xlab="", ylab="Energy sub metering") lines(dataSet$DateTime, dataSet$Sub_metering_2, type="l", col="red") lines(dataSet$DateTime, dataSet$Sub_metering_3, type="l", col="blue") legend("topright", lty=1, lwd=1, col=c("black","blue","red"), legend=cols) dev.off() } makePlot3()
5313c58527a16ffd0626ef2e41beb424dd26662a
b9b74b11bd45b2a81566406576ebd9bfae9dc755
/R/plots/f_F_plots.R
0e448d5623996fd97679d4cae4bbd4d72068c027
[ "MIT" ]
permissive
zejiang-unsw/nowcasting
de79f9fa90fef1affed01ca0830f1d4756854cfc
fd783618d35b0026f81f3fc7e04c6593d03d7ed0
refs/heads/master
2022-11-23T03:56:16.834661
2020-05-19T16:02:57
2020-05-19T16:02:57
null
0
0
null
null
null
null
UTF-8
R
false
false
13,044
r
f_F_plots.R
#################################################################### ### Load Libraries #################################################################### library(fields) library(ncdf4) library(RNetCDF) library(xtable) library(forecast) library(plot3D) library(ggplot2) library(MASS) library(mvtnorm) #################################################################### ### Souce Functions #################################################################### # source('/Users/joshuanorth/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/Load_netCDF_Data.R', chdir = TRUE) # source('/Users/joshuanorth/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/Nowcasting_Function.R', chdir = TRUE) # source('/Users/joshuanorth/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/Finite_Difference_Function.R', chdir = TRUE) # source('/Users/joshuanorth/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/Move_Functions.R', chdir = TRUE) # source('/Users/joshuanorth/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/Error_Function.R', chdir = TRUE) # source('/Users/joshuanorth/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/Prediction_Functions.R', chdir = TRUE) source('R/Load_netCDF_Data.R', chdir = TRUE) source('R/Nowcasting_Function.R', chdir = TRUE) source('R/Finite_Difference_Function.R', chdir = TRUE) source('R/Move_Functions.R', chdir = TRUE) source('R/Error_Function.R', chdir = TRUE) source('R/Prediction_Functions.R', chdir = TRUE) #################################################################### ### Compile Data #################################################################### # bigD <- load.netCDF.data(filepath = '~/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/lightning_data') # # run <- read.csv('~/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/Movement_Data.csv') # mac # run <- run[,2:5] # drop first column # # move.perc <- read.csv('~/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/data/predict_data.csv', header = TRUE) # col.prec <- read.csv('~/Dropbox/Nowcasting/FDAWLM_USE_THIS_ONE/Final/data/column_predict.csv', header = TRUE) bigD <- load.netCDF.data(filepath = 'data') run <- read.csv('movement_data/Movement_Data.csv') run <- run[,2:5] # drop first column move.perc <- read.csv('movement_data/predict_data.csv', header = TRUE) col.prec <- read.csv('movement_data/column_predict.csv', header = TRUE) # get nowcasts ---------------------------------------------------------------- # timestep 10 begin = 10 # With Q q <- bigD[,,begin] - bigD[,,(begin-1)] q <- q/100 est <- nowcast(bigD = bigD, tolerance = 0, iteration = 10, number = 10, timestep = begin, num = 10, nframes = 20, Q = q, r = 0.15) est10 <- ifelse(est < 0.0, 0, est) est10 <- ifelse(est10 > 1.6, 1.6, est10) # timestep 20 begin = 20 # With Q q <- bigD[,,begin] - bigD[,,(begin-1)] q <- q/100 est <- nowcast(bigD = bigD, tolerance = 0, iteration = 10, number = 10, timestep = begin, num = 10, nframes = 20, Q = q, r = 0.15) est20 <- ifelse(est < 0.0, 0, est) est20 <- ifelse(est20 > 1.6, 1.6, est20) # timestep 30 begin = 30 # With Q q <- bigD[,,begin] - bigD[,,(begin-1)] q <- q/100 est <- nowcast(bigD = bigD, tolerance = 0, iteration = 10, number = 10, timestep = begin, num = 10, nframes = 20, Q = q, r = 0.15) est30 <- ifelse(est < 0.0, 0, est) est30 <- ifelse(est30 > 1.6, 1.6, est30) # timestep 40 begin = 40 # With Q q <- bigD[,,begin] - bigD[,,(begin-1)] q <- q/100 est <- nowcast(bigD = bigD, tolerance = 0, iteration = 10, number = 10, timestep = begin, num = 10, nframes = 20, Q = q, r = 0.15) est40 <- ifelse(est < 0.0, 0, est) est40 <- ifelse(est40 > 1.6, 1.6, est40) # timestep 50 begin = 50 # With Q q <- bigD[,,begin] - bigD[,,(begin-1)] q <- q/100 est <- nowcast(bigD = bigD, tolerance = 0, iteration = 10, number = 10, timestep = begin, num = 10, nframes = 20, Q = q, r = 0.15) est50 <- ifelse(est < 0.0, 0, est) est50 <- ifelse(est50 > 1.6, 1.6, est50) # plot nowcasts one ----------------------------------------------------------- mid_col = 'gray97' png("/Users/joshuanorth/Desktop/f_vs_F.png", height = 2500, width = 1250) layout.matrix <- matrix(c(1:10, 11, 11), nrow = 6, ncol = 2, byrow = T) layout(mat = layout.matrix, heights = c(rep(1.5, 5), 0.5), # Heights of the two rows widths = rep(1.5, 2)) # Widths of the two columns # layout.show(11) par(mar = c(4,8,6,4), oma = c(4,1,1,1)) # first row # 10 # par(mfrow = c(1,2)) image(est10[,,1] - bigD[,,10], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), main = "F(s,t) - f(s,t-1)", ylab = 't = 11', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,11] - bigD[,,10], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), main = "f(s,t) - f(s,t-1)", axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # par(mfrow = c(1,2)) # image.plot(est10[,,1] - bigD[,,10], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # image.plot(bigD[,,10] - bigD[,,9], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # second row # 20 # par(mfrow = c(1,2)) image(est20[,,1] - bigD[,,20], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 21', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,21] - bigD[,,20], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # par(mfrow = c(1,2)) # image.plot(est20[,,1] - bigD[,,20], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # image.plot(bigD[,,20] - bigD[,,19], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # third row # 30 # par(mfrow = c(1,2)) image(est30[,,1] - bigD[,,30], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 31', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,31] - bigD[,,30], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # par(mfrow = c(1,2)) # image.plot(est30[,,1] - bigD[,,30], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # image.plot(bigD[,,30] - bigD[,,29], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # fourth row # 40 # par(mfrow = c(1,2)) image(est40[,,1] - bigD[,,40], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 41', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,41] - bigD[,,40], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # par(mfrow = c(1,2)) # image.plot(est40[,,1] - bigD[,,40], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # image.plot(bigD[,,40] - bigD[,,39], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # fifth row # 50 # par(mfrow = c(1,2)) image(est50[,,1] - bigD[,,50], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 51', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,51] - bigD[,,50], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # par(mfrow = c(1,2)) # image.plot(est50[,,1] - bigD[,,50], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # image.plot(bigD[,,50] - bigD[,,49], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue')) # sixth row image(x = seq(-1.6, 1.6, length.out = 256), z = t(t(seq(-1.6, 1.6, length.out = 256))), col = two.colors(start = 'blue', mid = mid_col), xlab='', axes = F) axis(1, at = seq(-1.6, 1.6, 0.4), cex.axis = 4, outer = T, col = NA) dev.off() # plot nowcasts two ----------------------------------------------------------- mid_col = 'gray97' png("/Users/joshuanorth/Desktop/f_vs_F_two.png", height = 2500, width = 1250) layout.matrix <- matrix(c(1:10, 11, 11), nrow = 6, ncol = 2, byrow = T) layout(mat = layout.matrix, heights = c(rep(1.5, 5), 0.5), # Heights of the two rows widths = rep(1.5, 2)) # Widths of the two columns # layout.show(11) par(mar = c(4,8,6,4), oma = c(4,1,1,1)) # first row # 10 # par(mfrow = c(1,2)) image(est10[,,1] - bigD[,,10], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), main = "F(s,t+1) - f(s,t)", ylab = 't = 10', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,10] - bigD[,,9], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), main = "f(s,t) - f(s,t-1)", axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # second row # 20 # par(mfrow = c(1,2)) image(est20[,,1] - bigD[,,20], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 20', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,20] - bigD[,,19], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # third row # 30 # par(mfrow = c(1,2)) image(est30[,,1] - bigD[,,30], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 30', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,30] - bigD[,,29], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # fourth row # 40 # par(mfrow = c(1,2)) image(est40[,,1] - bigD[,,40], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 40', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,40] - bigD[,,39], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # fifth row # 50 # par(mfrow = c(1,2)) image(est50[,,1] - bigD[,,50], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 50', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,50] - bigD[,,49], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # sixth row image(x = seq(-1.6, 1.6, length.out = 256), z = t(t(seq(-1.6, 1.6, length.out = 256))), col = two.colors(start = 'blue', mid = mid_col), xlab='', axes = F) axis(1, at = seq(-1.6, 1.6, 0.4), cex.axis = 4, outer = T, col = NA) dev.off() # plot nowcasts three ----------------------------------------------------------- mid_col = 'gray97' png("/Users/joshuanorth/Desktop/f_vs_F_three.png", height = 2500, width = 1250) layout.matrix <- matrix(c(1:10, 11, 11), nrow = 6, ncol = 2, byrow = T) layout(mat = layout.matrix, heights = c(rep(1.5, 5), 0.5), # Heights of the two rows widths = rep(1.5, 2)) # Widths of the two columns # layout.show(11) par(mar = c(4,8,6,4), oma = c(4,1,1,1)) # first row # 10 # par(mfrow = c(1,2)) image(bigD[,,11] - est10[,,1], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), main = "f(s,t) - F(s,t)", ylab = 't = 11', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,11] - bigD[,,10], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), main = "f(s,t) - f(s,t-1)", axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # second row # 20 # par(mfrow = c(1,2)) image(bigD[,,21] - est20[,,1], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 21', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,21] - bigD[,,20], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # third row # 30 # par(mfrow = c(1,2)) image(bigD[,,31] - est30[,,1], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 31', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,31] - bigD[,,30], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # fourth row # 40 # par(mfrow = c(1,2)) image(bigD[,,41] - est40[,,1], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 41', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,41] - bigD[,,40], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # fifth row # 50 # par(mfrow = c(1,2)) image(bigD[,,51] - est50[,,1], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), ylab = 't = 51', axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) image(bigD[,,51] - bigD[,,50], zlim = c(-1.6, 1.6), col = two.colors(start = 'blue', mid = mid_col), axes = F, cex.lab = 5, cex.main = 5, font.lab = 2) # sixth row image(x = seq(-1.6, 1.6, length.out = 256), z = t(t(seq(-1.6, 1.6, length.out = 256))), col = two.colors(start = 'blue', mid = mid_col), xlab='', axes = F) axis(1, at = seq(-1.6, 1.6, 0.4), cex.axis = 4, outer = T, col = NA) dev.off()
7314afb225b9d474d851b52087debe7f91a85706
3da2b08ad47a140738bbb484a1429b523caa54b6
/Sim2ClusterPS.R
73487549419de6606011246728dad139326dbb92
[]
no_license
knickodem/AggCovsForPS
f83d4156562dcbcb89eea53b67ef5e220a4b1178
7e97520b95532fedc6af893e529fdf423672352f
refs/heads/master
2022-10-16T07:56:44.001412
2020-06-08T18:21:54
2020-06-08T18:21:54
245,267,187
0
1
null
null
null
null
UTF-8
R
false
false
23,314
r
Sim2ClusterPS.R
################################################################################## # # # Simulation 2 - Cluster-Level Treatment Exposure and Subject-Level Outcome # # # ################################################################################## ## Loading Packages library(simstudy) library(tictoc) library(dplyr) library(tidyr) library(MatchIt) library(cobalt) library(lme4) ########################################## #### Defining Conditions and Outcomes #### ## Study Conditions DataGenConds <- crossing(nsub = c(20, 60, 100), # number of subjects per cluster nclus = c(60, 100, 140), # number of clusters icc = c(.05, .1, .2), # intraclass correlation [ICC(1)] for outcome, Y, and reflective L2 aggregations aggvar = c(.1, .3, .5, 1), # error/1-% sampled in observed L2 covariates psmod = c("Cluster","Subject"), # PS estimation and conditioning at cluster or subject level mw = c("Matching", "Weighting")) # PS conditioning method nreps <- 1000 # number of replications ## Simulation dependent variables DVnames <- c("Prop_Treated", "PS_Converged", "Baseline_True.Agg_L2_Cor", # Proportion in treatment group and Yes/No for PS model convergence "PS_Bias", "PS_MAE", "PS_RMSE", "Logit_Bias", "Logit_MAE", "Logit_RMSE", # Bias and Error in estimation of PS and logit of PS "Analytic_Subjects", "Analytic_Clusters", "True.Agg_L2_Cor", # Num subjects & clusters and correlation b/t true and obs L2 in sample used in outcome model "Y_ICC1", "X_ICC1", "X_ICC2", # Characteristics of sample used in outcome analysis "Un.ASD", "Un.VR", "Un.ASD_Balanced_Count", "Un.VR_Balanced_Count", # For unadjusted sample - mean Absolute standardized difference & Variance ratio; Count of the 30 covariates balanced (on ASD or VR) at subject level "Adj.ASD", "Adj.VR", "Adj.ASD_Balanced_Count", "Adj.VR_Balanced_Count", # For adjusted sample - mean ASD & VR; Count of the 30 covariates balanced (on ASD or VR) at subject level "Y_Converged", "TE_Bias", "TE_MAE", "TE_RMSE", # Yes/No for Outcome model convergence; If yes, Bias, MAE and RMSE for estimation of the treatment effect "Baseline_Converged", "Baseline_Bias", "Baseline_MAE", "Baseline_RMSE") # TE estimation from full (unadjusted) sample ## Creating blank matrix for summary statistics for each data generation condition DVSummaryStats <- matrix(-999, ncol = length(DVnames), nrow = nrow(DataGenConds)) # Summary stats for generated datasets ## Variables consistent across all conditions delta <- .50 # Average Treatment Effect ($\delta$) marg <- -1.386294 # marginal probability of treatment;intercept of -1.0986 produces a marginal probability of .25; stats::plogis(-1.0986); -1.386294 = .2 L1names <- paste0("x", 1:20) # names of Level 1 covariates trueL2names <- paste(L1names[1:10], "c", sep = "_") # names of true level 2 covariates obsL2names <- paste(trueL2names, "o", sep = "_") # names of aggregated level 2 covariates ############################ ############################# #### Running Simulation #### set.seed(1213611) # Seed for reproducing results tic("Total") for(con in 1:nrow(DataGenConds)){ tic(as.character(con)) # Record time to run all replications for each condition ## Defining characteristics of the simulation condition nsub <- DataGenConds[con,][[1]] # Number of Level 1 units (i.e., subjects) nclus <- DataGenConds[con,][[2]] # Number of Level 2 units (i.e., clusters) ntot <- nclus*nsub # Total sample size tau00 <- DataGenConds[con,][[3]] # between cluster (L2) variance ($\tau_{00}$) sigma2 <- 1 - tau00 # within cluster (L1) variance ($\sigma^2$) aggvar <- DataGenConds[con,][[4]] # error for creating observed L2 covariates psmod <- DataGenConds[con,][[5]] # PS estimation and equating at cluster or subject level mw <- DataGenConds[con,][[6]] # PS equating method ## Dependent Variable (DV) values for each replication of a condition DVReplicationStats <- matrix(-999, ncol = length(DVnames), nrow = nreps) for(r in 1:nreps){ ########################## #### Generating data #### #### Formative-RE: Generate L1, aggregate true L2, then add random error for observed L2 #### ## Level 1 covariates - 20 continuous covariates from a standard normal distribution with correlation of .2 GenData <- genCorData(n = ntot, mu = rep(0, 20), sigma = sqrt(sigma2), rho = 0.2, corstr = "cs", cnames = L1names, idname = "sid") %>% mutate(rij = rnorm(n = ntot, mean = 0, sd = sqrt(sigma2)), # random error for outcome model from normal distribution (i.e, $\mu$ = 0, $\sigma^2$ = 1) cid = as.character(rep(1:nclus, each = nsub))) %>% # creating cluster ID group_by(cid) %>% mutate_at(vars(x1:x20), ~. + rnorm(n = 1, mean = 0, sd = sqrt(tau00))) %>% # Adding cluster variation to maintain ICC(1) mutate_at(vars(x1:x10), list(c = ~mean(.))) %>% # aggregating L1 to true L2 value mutate_at(vars(x1_c:x10_c), list(o = ~. + rnorm(n = 1, mean = 0, sd = aggvar))) %>% # Adding random variation to true cluster mean; selects a random number for each cluster for each covariate mutate(zuj = rlogis(n = 1, location = 0, scale = 1), # random error for PS model (probability of treatment) from logistic distribution with mean = 0 and variance of $\pi^2 / 3$ uj = rnorm(n = 1, mean = 0, sd = sqrt(tau00))) %>% # random error for outcome model from normal distribution (i.e, $\mu$ = 0, $\tau_{00} depends on condition) ungroup() %>% mutate(TrueLogit = marg + 5*x1_c + .5*x2_c + .5*x3_c + .5*x4_c + .5*x5_c + # True logit of the probability of treatment exposure (i.e. propensity score) .5*x6_c + .5*x7_c + .5*x8_c + .5*x9_c + .5*x10_c + zuj, TruePS = stats::plogis(TrueLogit), # true PS z = ifelse(TrueLogit > 0, 1, 0), # Determining treatment exposure Yij = .5*x1 + .5*x2 + .5*x3 + .5*x4 + .5*x5 + .5*x6 + .5*x7 + .5*x8 + .5*x9 + .5*x10 + # Generating outcome values .5*x11 + .5*x12 + .5*x13 + .5*x14 + .5*x15 + .5*x16 + .5*x17 + .5*x18 + .5*x19 + .5*x20 + rij + # Level 1 covariates .5*x1_c + .5*x2_c + .5*x3_c + .5*x4_c + .5*x5_c + .5*x6_c + .5*x7_c + .5*x8_c + .5*x9_c + .5*x10_c + delta*z + uj, # Level 2 covariates cid = factor(cid)) # converting cluster id from character to factor #### Estimating PS #### if(psmod == "Cluster"){ ## Model appraises treatment at the cluster-level and only uses L2 covariates ThePSModel <- paste0("z ~ 1 + ", paste(obsL2names, collapse = " + ")) PS.mod <- glm(as.formula(ThePSModel), data = GenData, family = binomial("logit")) } else if(psmod == "Subject"){ ## Model ignores clusters and uses L1 and L2 covariates, the latter conceptually treated as L1 covariates ThePSModel <- paste0("z ~ 1 + ", paste(L1names, collapse = " + "), " + ", paste(obsL2names, collapse = " + ")) PS.mod <- glm(as.formula(ThePSModel), data = GenData, family = binomial("logit")) } else {stop("something went wrong")} ## Did the PS model converge? PSModConverge <- ifelse(PS.mod$converged == TRUE, 1, 0) ## Adding estimated PS to dataframe GenData$PS <- fitted(PS.mod) GenData$Logit <- predict(PS.mod) # observed logit of the PS GenData$LogitDiff <- GenData$Logit - GenData$TrueLogit # Error in observed (estimated) and true logit of the PS GenData$PSDiff <- GenData$PS - GenData$TruePS # Error in observed and true PS ## Saving DVs DVReplicationStats[r,1] <- mean(GenData$z) # proportion with treatment exposure DVReplicationStats[r,2] <- PSModConverge # PS model convergence #### Checking Overlap assumption #### ## Removing cases where PS is equal to 1 or 0 AnalyticSample <- GenData %>% filter(PS > .001 & PS < .999) if(PSModConverge == 0 | nrow(AnalyticSample) == 0){ ## Don't run conditioning and outcome model. Make remaining DV values NA DVReplicationStats[r,3:31] <- NA } else { #### Calculating the pre-conditioning DVs that utilize the full sample #### DVReplicationStats[r,3] <- purrr::map2_dbl(.x = trueL2names, .y = obsL2names, ~cor(GenData[,.x],GenData[,.y])) %>% # correlation b/t true and observed L2 covariates in full sample psych::fisherz() %>% ifelse(. > 7.3, 7.3, .) %>% ifelse(. < -7.3, -7.3, .) %>% mean() # z = +- 7.3 is equivalent to r = .9999991; when r = 1, z = Inf which throws of calculation of mean correlation DVReplicationStats[r,4] <- mean(GenData$PSDiff) # bias of PS DVReplicationStats[r,5] <- mean(abs(GenData$PSDiff)) # mae of PS DVReplicationStats[r,6] <- sqrt(mean(GenData$PSDiff^2)) # rmse of PS DVReplicationStats[r,7] <- mean(GenData$LogitDiff) # bias of logit DVReplicationStats[r,8] <- mean(abs(GenData$LogitDiff)) # mae of logit DVReplicationStats[r,9] <- sqrt(mean(GenData$LogitDiff^2)) # rmse of logit ################################# ###################################### #### Analyzing Generated Datasets #### #### Conditioning on the PS #### if(mw == "Matching"){ if(psmod == "Cluster"){ ## Extracting cluster-level data for matching; i.e., if nclus = 100, nrow(ClusterData) = 100 unless a cluster had a PS == 0|1 ClusterData <- AnalyticSample %>% select(cid, one_of(obsL2names), z, PS, Logit) %>% unique() ## Running matching algorithm - 1:1 nearest neighbor w/o replacement with caliper of .2 SD of the logit of the PS tryCatch(expr = {TheMatches <- matchit(as.formula(ThePSModel), data = ClusterData, method = "nearest", replace = FALSE, caliper = .2, distance = ClusterData$Logit)}, error = function(e){TheMatches <<- TRUE; return(TheMatches)}) ## Extracting the weights or assigning weights to 0 if no matches if(class(TheMatches) == "matchit"){ ClusterData$weight <- TheMatches$weights } else { ClusterData$weight <- 0 } ## Adding weight to subject-level data AnalyticSample <- inner_join(AnalyticSample, ClusterData %>% select(cid,weight), by = "cid") } else if(psmod == "Subject"){ ## Running matching algorithm - 1:1 nearest neighbor w/o replacement with caliper of .2 SD of the logit of the PS # Catch error if one should occur tryCatch(expr = {TheMatches <- matchit(as.formula(ThePSModel), data = AnalyticSample, method = "nearest", replace = FALSE, caliper = .2, distance = AnalyticSample$Logit)}, error = function(e){TheMatches <<- TRUE; return(TheMatches)}) ## Extracting the weights or assigning weights to 0 if no matches if(class(TheMatches) == "matchit"){ AnalyticSample$weight <- TheMatches$weights } else { AnalyticSample$weight <- 0 } } else {stop("something went wrong")} } else if(mw == "Weighting"){ AnalyticSample$weight <- WeightIt::get_w_from_ps(ps = AnalyticSample$PS, estimand = "ATE", treat = AnalyticSample$z, treated = 1) } else {stop("something went wrong")} ## If no matches occured if(sum(AnalyticSample$weight) == 0){ ## Don't run conditioning and outcome model. Make remaining DV values NA DVReplicationStats[r,2] <- 0 # Change PS convergence code to 0 DVReplicationStats[r,3:31] <- NA # make remaining DV values NA } else { ## With weighting or when matching was successful #### Assessing Balance #### ## Balance is only evaluated at the subject-level in accordance with WWC guidelines, but includes all covariates TheBalance <- bal.tab(formula = as.formula(paste0("z ~ 1 + ", paste(L1names, collapse = " + "), " + ", paste(obsL2names, collapse = " + "))), data = AnalyticSample, continuous = "std", binary = "std", s.d.denom = "pooled", abs = TRUE, un = TRUE, quick = TRUE, disp.means = FALSE, disp.sd = FALSE, disp.v.ratio = TRUE, weights = AnalyticSample$weight, method = tolower(mw)) ## Calculating ICC(1) and (2) of 10 aggregated covariates ICC1 <- purrr::map_dbl(paste0("x",1:10), ~ICC::ICCbare(factor(cid), quo_name(.x), AnalyticSample[AnalyticSample$weight != 0,])) %>% # ICC(1) of aggregated covariates ifelse(. < 0, 0, .) # negatives constrained to 0 ICC2 <- (nsub*ICC1) / (1 + (nsub - 1)*ICC1) #### Calculating the post-conditioning DVs for each replication #### DVReplicationStats[r,10] <- nrow(AnalyticSample[AnalyticSample$weight != 0,]) # Number of subjects in analytic sample DVReplicationStats[r,11] <- unique(AnalyticSample[AnalyticSample$weight != 0,]$cid) %>% length() # Number of clusters in analytic sample DVReplicationStats[r,12] <- purrr::map2_dbl(.x = trueL2names, .y = obsL2names, ~cor(AnalyticSample[AnalyticSample$weight != 0, .x], AnalyticSample[AnalyticSample$weight != 0, .y])) %>% # correlation b/t true and observed L2 covariates psych::fisherz() %>% ifelse(. > 7.3, 7.3, .) %>% ifelse(. < -7.3, -7.3, .) %>% mean() # z = +- 7.3 is equivalent to r = .9999991; when r = 1, z = Inf which throws of calculation of mean correlation DVReplicationStats[r,13] <- ICC::ICCbare(factor(cid), Yij, AnalyticSample[AnalyticSample$weight != 0,]) %>% ifelse(. < 0, 0, .) # ICC(1) of outcome Yij (negatives constrained to 0) DVReplicationStats[r,14] <- mean(ICC1) # mean ICC(1) of L1 X covariates DVReplicationStats[r,15] <- mean(ICC2) # mean ICC(2) of L2 X covariates DVReplicationStats[r,16] <- mean(TheBalance[[1]]$Diff.Un) # mean Absolute Standardized Difference (ASD) before conditioning (Unadjusted) DVReplicationStats[r,17] <- mean(TheBalance[[1]]$V.Ratio.Un) # mean Variance Ration (VR) before conditioning (Unadjusted) DVReplicationStats[r,18] <- sum(TheBalance[[1]]$Diff.Un < .10) # Unadjusted count of covariates (out of 30) that were balanced at L1 based on ASD DVReplicationStats[r,19] <- sum(TheBalance[[1]]$V.Ratio.Un < 2) # Unadjusted count of covariates (out of 30) that were balanced at L1 based on VR DVReplicationStats[r,20] <- mean(TheBalance[[1]]$Diff.Adj) # mean ASD after conditioning (Adjusted) DVReplicationStats[r,21] <- mean(TheBalance[[1]]$V.Ratio.Adj) # mean VR after conditioning (Adjusted) DVReplicationStats[r,22] <- sum(TheBalance[[1]]$Diff.Adj < .10) # Adjusted count of covariates (out of 30) that were balanced at L1 based on ASD DVReplicationStats[r,23] <- sum(TheBalance[[1]]$V.Ratio.Adj < 2) # Adjusted count of covariates (out of 30) that were balanced at L1 based on VR #### Estimating Treatment Effect #### ## The Outcome Model TheOutcomeModel <- paste0("Yij ~ 1 + z + ", paste(L1names, collapse = " + "), " + ", paste(obsL2names, collapse = " + "), " + (1|cid)") # Running model and catching errors if necessary tryCatch(expr = {Out.mod <- lmer(as.formula(TheOutcomeModel), data = AnalyticSample[AnalyticSample$weight != 0, ], # removes observations where weight = 0 (these were the unmatched observations) weights = AnalyticSample[AnalyticSample$weight != 0, ]$weight)}, error = function(e){Out.mod <<- TRUE; return(Out.mod)}) if(class(Out.mod) == "lmerMod"){ ## Did the Outcome model converge? OutModConverge <- ifelse(is.null(Out.mod@optinfo$conv$lme4$code), 1, 0) } else{ ## Did the Outcome model converge? OutModConverge <- 0 } ## Recording Outcome model convergence DVReplicationStats[r,24] <- OutModConverge if(is.logical(Out.mod)){ ## Don't calculate TE and make remaining DV values NA DVReplicationStats[r,25:31] <- NA } else if(OutModConverge == 0 | !("z" %in% attr(fixef(Out.mod), "names"))){ ## Don't calculate TE and make remaining DV values NA DVReplicationStats[r,25:31] <- NA } else { ## Difference between treatment effect estimate and true delta (i.e. bias) TEDiff <- fixef(Out.mod)[["z"]] - delta #### Treatment Effect DVs for each replication from outcome model #### DVReplicationStats[r,25] <- TEDiff # bias of TE DVReplicationStats[r,26] <- abs(TEDiff) # mae of TE DVReplicationStats[r,27] <- TEDiff^2 # rmse of TE #### Estimating Treatment Effect with full sample #### ## Establishes baseline to which the PS methods can be compared # (i.e, is the PS even worth it) Base.mod <- lmer(as.formula(TheOutcomeModel), data = GenData) ## Did the Baseline model converge? BaseModConverge <- ifelse(is.null(Base.mod@optinfo$conv$lme4$code), 1, 0) DVReplicationStats[r,28] <- BaseModConverge # Baseline model convergence if(BaseModConverge == 0 | !("z" %in% attr(fixef(Base.mod), "names"))){ ## Don't calculate TE DVReplicationStats[r,29:31] <- NA } else { ## Difference between treatment effect estimate from baseline model and the true delta (i.e. bias) BaseTEDiff <- fixef(Base.mod)[["z"]] - delta #### Treatment Effect DVs for each replication #### DVReplicationStats[r,29] <- BaseTEDiff # bias of TE from baseline model DVReplicationStats[r,30] <- abs(BaseTEDiff) # mae of TE from baseline model DVReplicationStats[r,31] <- BaseTEDiff^2 # rmse of TE from baseline model } # ends BaseModConverge evaluation } # ends OutModConverge evaluation } # ends TheMatches evaluation (i.e., when no matches, skip remaining analysis) } # ends PSModConverge evaluation } # ends replication ## logging time to run condition toc(quiet = TRUE, log = TRUE) #### DVs averaged across replications #### DVSummaryStats[con, ] <- colMeans(DVReplicationStats, na.rm = TRUE) if(con == 1){ Con1GenDatP <- GenData # saves dataset from the 1000th rep Con1AnalyticSampleP <- AnalyticSample # saves dataset from the 1000th rep Con1DVReplicationStatsP <- DVReplicationStats } } toc() ################################# #### Saving Initial Results #### save(DVSummaryStats, file = "Sim2_ThousandRep_DVSummaryOnly_Pooled.RData") colnames(DVSummaryStats) <- DVnames Sim2DVsbyCondPooled <- data.frame(DVSummaryStats, stringsAsFactors = FALSE) %>% mutate_all(as.numeric) %>% # Converting from character to numeric mutate(Logit_RMSE = sqrt(Logit_RMSE), TE_RMSE = sqrt(TE_RMSE), Baseline_RMSE = sqrt(Baseline_RMSE), True.Agg_L2_Cor = psych::fisherz2r(True.Agg_L2_Cor), # Converting z-scores to correlations Baseline_True.Agg_L2_Cor = psych::fisherz2r(Baseline_True.Agg_L2_Cor)) %>% # Converting z-scores to correlations tibble::rownames_to_column("Con") %>% left_join(DataGenConds %>% tibble::rownames_to_column("Con"), by = "Con") %>% select(-Con) #### Extracting timing #### # Character vector Sim2TimingLog <- tic.log(format = TRUE) %>% unlist() # Converted to dataframe and cleaned for analysis Sim2TLogDFPooled <- data.frame(temp = Sim2TimingLog, stringsAsFactors = FALSE) %>% separate(temp, c("Row", "Time"), sep = ": ") %>% mutate(Time = as.numeric(gsub(" sec elapsed", "", Time, fixed = TRUE))) # Total time (in min) to run the simulation sum(Sim2TLogDFPooled$Time) / 60 # Clearing time log tic.clearlog() #### Saving Simulation Results #### ## Intermediate information from condition 432 Con432GenDatP <- GenData # saved sample data from last rep of condition 432 Con432AnalyticSampleP <- AnalyticSample # saved summary statistics for each rep of condition 432 Con432DVReplicationStatsP <- data.frame(DVReplicationStats, stringsAsFactors = FALSE) save(Con432GenDatP, Con432AnalyticSampleP, Con432DVReplicationStatsP, Con1GenDatP, Con1AnalyticSampleP, Con1DVReplicationStatsP, DVSummaryStats, Sim2DVsbyCondPooled, Sim2TLogDFPooled, DVnames, file = "Sim2_ThousandRep_Pooled.RData") ##################################################
4ef3a25c4270b6d0ef49b9ff79f8b0618a48ad4f
b48ea7f06b12d71fe597adefa5da35e81d08caf8
/inst/examples/20-api/server.R
16cc51dee182452bb5852c247e33d130b10b7cab
[ "MIT" ]
permissive
shinyTree/shinyTree
c840dd94af787e15cce6b7c0d4b73b2537123b8a
110b49970d117d0638746d47b074e955287abed0
refs/heads/master
2023-08-30T22:50:33.875203
2023-08-07T15:53:07
2023-08-07T15:53:07
22,565,116
75
42
NOASSERTION
2023-02-08T10:37:30
2014-08-03T02:44:13
JavaScript
UTF-8
R
false
false
543
r
server.R
library(shiny) library(shinyjs) library(shinyTree) #' Define custom JS functions to implement jsTree core functionality #' @author McClelland Legge \email{McClelland.Legge@@gmail.com} shinyServer(function(input, output, session) { observeEvent(input$reset, { js$resetTree("tree") }) output$tree <- renderTree({ list( root1 = "123", root2 = list( SubListA = list(leaf1 = "", leaf2 = "", leaf3 = ""), SubListB = structure(list(leafA = "", leafB = ""), stselected = TRUE) ) ) }) })
8d19eb8ca5e94c0fed3d7f9f156b663c3a3f2d2f
e8fdbae58c34c896736babebcf93048a0969d619
/src/R/experiments/bootstrapping.R
b6865bf64c5bed036d1db196b0cc37549d0e8960
[]
no_license
emilysturdivant/biomass-espanola
cb8c71433bab50f4a9f447005e5654e680e9add1
3cc020614b2bdaf53eddaf3f4eef92ac12e03436
refs/heads/master
2021-12-23T23:34:29.977417
2021-11-25T19:56:37
2021-11-25T19:56:37
225,423,106
1
0
null
null
null
null
UTF-8
R
false
false
16,605
r
bootstrapping.R
# Script where I experiment with cross-validation and bootstrapping to measure the regression fit library(readr) library(BIOMASS) library(tidyverse) require(boot) require(MASS) # Load data g0.agb <- readRDS("results/R_out/plots_g0agb_dfslim.rds") # Pairs Bootstrap ---- ########################################################### # OLS set.seed(45) boot.ols.100k <- boot(g0.agb, function(data=g0.agb, index) { data <- data[index,] # we sample along rows of the data frame model.boot <- lm(AGB ~ backscatter, data=data) coef(model.boot) }, R=100000) # Results boot.ols.100k plot(boot.ols.100k, index=1) cis <- list() ci <- boot.ci(boot.ols.100k, conf=0.95, type=c("basic", "bca", "perc"), index=1) cis[['b']] <- ci$bca[4:5] ci <- boot.ci(boot.ols.100k, conf=0.95, type=c("basic", "bca", "perc"), index=2) cis[['m']] <- ci$bca[4:5] cis <- as.data.frame(cis, row.names = c('lwr', 'upr')) # Save/Load outputs from before creating AGB raster boot.ols.100k %>% saveRDS("results/R_out/boot_g0nu_100k.rds") # Experimentation, old ---- ########################################################### # Load data - Desktop # Load data - Mac g0_AGB <- read_csv("~/GitHub/biomass-espanola/data/plots_g0nu_AGB.csv") # just get the two columns we care about g0.agb <- as.data.frame(cbind(g0_AGB$AGB_ha, g0_AGB$'2018mean')) %>% rename(AGB = V1, backscatter =V2) #---- # Scatterplot p <- ggplot(g0.agb, aes(x=backscatter, y=AGB)) + geom_point() + labs(y = expression(paste("Aboveground biomass (MgC ha"^"-1", ")")), x = expression(paste("Radar backscatter, ",sigma['HV']^0," (m"^2, "/m"^2, ")"))) p p2 <- p + geom_smooth(method="lm", se=TRUE, fullrange=TRUE, level=0.95, col='black') p2 + labs(caption = 'OLS regression') p2 p1 + geom_smooth(method="rlm", col='red', se=TRUE, fullrange=TRUE, level=0.95) + labs(caption = 'RLM regression') p2 + geom_smooth(method="lm", col='red', fill='red', se=TRUE, fullrange=TRUE, level=0.95) + geom_smooth(method="rlm", col='blue', fill='blue', se=TRUE, fullrange=TRUE, level=0.95) # Manually construct confidence bands around OLS regression line mm <- model.matrix(~ backscatter, data = g0.agb) vars <- mm %*% vcov(ols) %*% t(mm) sds <- sqrt(diag(vars)) t.val <- qt(1 - (1 - 0.95)/2, ols$df.residual) t.val g0.agb$LoCI.man <- ols$fitted.values - t.val * sds g0.agb$HiCI.man <- ols$fitted.values + t.val * sds p + geom_ribbon(aes(ymin=g0.agb$LoCI.man, ymax=g0.agb$HiCI.man), linetype=2, alpha=0.1) ols.ci95 <- predict(ols, newdata = g0.agb, interval = 'confidence') ols.pi95 <- predict(ols, newdata = g0.agb, interval = 'prediction') p2 <- p + geom_ribbon(aes(ymin=ols.ci95[,2], ymax=ols.ci95[,3]), linetype=2, alpha=0.1) p2 + geom_ribbon(aes(ymin=ols.pi95[,2], ymax=ols.pi95[,3]), linetype=2, alpha=0.1) # plot BCa CI from bootstrapping - not sure if this is appropriate g0.agb$loCI <- -6.96 + 799*g0.agb$backscatter g0.agb$hiCI <- 9.63 + 1358*g0.agb$backscatter p2 + geom_ribbon(aes(ymin=g0.agb$loCI, ymax=g0.agb$hiCI), linetype=2, alpha=0.1) # plot parameter CI from OLS - not sure if this is appropriate g0.agb$loCI <- -14.6454 + 713.18*g0.agb$backscatter g0.agb$hiCI <- 14.64934 + 1349.83*g0.agb$backscatter p2 + geom_ribbon(aes(ymin=g0.agb$loCI, ymax=g0.agb$hiCI), linetype=2, alpha=0.1) # plot parameter CI from OLS - not sure if this is appropriate g0.agb$loCI <- 14.64934 + 713.18*g0.agb$backscatter g0.agb$hiCI <- -14.6454 + 1349.83*g0.agb$backscatter p2 + geom_ribbon(aes(ymin=g0.agb$loCI, ymax=g0.agb$hiCI), linetype=2, alpha=0.1) # boot.ols.100k$t0 confint(ols)[2,2] - ols$coefficients[2] ols$model # Bias g0.agb$resids <- ols$residuals p <- ggplot(g0.agb, aes(x=backscatter, y=resids)) + geom_point() + labs(y = expression(paste("Aboveground biomass (MgC ha"^"-1", ")")), x = expression(paste("Radar backscatter, ",sigma['HV']^0," (m"^2, "/m"^2, ")"))) p mean(abs(ols$residuals)) model.10000x5$results model.10000x5 # Basic OLS regression ols <- lm(g0.agb$AGB ~ g0.agb$backscatter, x=TRUE, y=TRUE) summary(ols) confint(ols) cov2cor(vcov(ols)) anova(ols) coef(ols)[2]*10000 coef(ols)[1]*100000000 opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0)) plot(ols, las = 1) ols$residuals rmse <- sqrt(var(ols$residuals)) # RMSE rmse <- sd(ols$residuals) mse <- mean((residuals(ols))^2) mse rss <- sum(residuals(ols)^2) rss rse <- sqrt(rss / ols$df.residual) rse mean(abs(residuals(ols))) summary(ols)$adj.r.squared sigma(ols) # OLS with intercept=0 ols.0 <- lm(g0.agb$AGB ~ 0+g0.agb$backscatter, x=TRUE, y=TRUE) abline(ols.0, col='cyan') summary(ols.0) confint(ols.0) cov2cor(vcov(ols)) anova(ols) coef(ols) opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0)) plot(ols, las = 1) #---- # Robust Linear Model regression, # with parameters set based on optimization performed by cross-validation below rr <- rlm(AGB ~ backscatter, g0.agb, psi=psi.hampel) rr$coefficients abline(rr, col='red') rr anova(rr) summary(rr) opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0)) plot(rr, las = 1) View(rr$w) rr.int0 <- rlm(AGB ~ 0 + backscatter, g0.agb, psi=psi.hampel) rr.int0$coefficients abline(rr, col='pink') anova(rr.int0) summary(rr.int0) opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0)) plot(rr.int0, las = 1) View(rr.int0$w) #---- # Cross-validation set.seed(45) # LOOCV # Train the model and summarize results model.loocv <- train(AGB ~ backscatter, data = g0.agb, method = "lm", trControl = trainControl(method = "LOOCV")) print(model.loocv) model.loocv$finalModel # K-fold # Train model and summarize results model.5fold <- train(AGB ~ backscatter, data = g0.agb, method = "lm", trControl = trainControl(method = "cv", number = 5)) print(model.5fold) model.5fold$finalModel # Repeated K-fold # Define training control, train model, and summarize results # OLS w/ int=0, 10,000 x 10-fold fxn.bias <- function(data, lev = NULL, model = NULL) { resids <- data$pred - data$obs rss <- sum(resids^2) n <- length(resids) df <- n-2 mse <- rss / n c(RMSE=sqrt(mse), Rsquared=summary(lm(pred ~ obs, data))$r.squared, MAE=sum(abs(resids)) / n, MSE=mse, B=sum(resids) / n, RSS=rss, MSS=rss/df, RSE=sqrt(rss / df)) } set.seed(45) model.10000x10 <- train(AGB ~ backscatter, data = g0.agb, method = "lm", trControl = trainControl(method = "repeatedcv", number = 10, repeats = 10000, summaryFunction = fxn.bias)) model.10000x10$results head(model.10000x10$resample) set.seed(3) model.2x5 <- train(AGB ~ backscatter, data = g0.agb, method = "lm", trControl = trainControl(method = "repeatedcv", number = 5, repeats = 2, summaryFunction = fxn.bias)) model.2x5$results set.seed(3) model.2x5.rmse <- train(AGB ~ backscatter, data = g0.agb, method = "lm", trControl = trainControl(method = "repeatedcv", number = 5, repeats = 2)) model.2x5.rmse$results model.10000x10 <- train(AGB ~ backscatter, data = g0.agb, method = "lm", trControl = trainControl(method = "repeatedcv", number = 10, repeats = 10000, returnResamp='all', trim=FALSE)) print(model.10000x10) model.10000x10$results model.10000x10$finalModel head(model.10000x10$resample) head(model.10000x10$metric) # OLS w/ int=0, 10,000 x 10-fold model.boot100k <- train(AGB ~ backscatter, data = g0.agb, method = "lm", trControl = trainControl(method = "boot", number = 100000)) print(model.boot100k) model.boot100k$results model.boot100k$finalModel # 5,000 x10-fold model.5000x10.int0$results model.5000x10.int0$finalModel # Repeated K-fold with Robust Linear Regression # RLM, 10,000 x 5-fold model.5000x10.rlmI <- train(AGB ~ backscatter, data = g0.agb, method = "rlm", tuneGrid = expand.grid(intercept = TRUE, psi = 'psi.hampel'), trControl = trainControl(method = "repeatedcv", number = 10, repeats = 5000)) print(model.5000x10.rlmI) model.5000x10.rlmI$results model.5000x10.rlmI$finalModel abline(model.5000x10.rlmI$finalModel, col='red') model.10000x10.rlmI #---- # Pairs Bootstrap with the boot library set.seed(45) # OLS boot.ols.100k <- boot(g0.agb, function(data=g0.agb, index) { data <- data[index,] # we sample along rows of the data frame model.boot <- lm(AGB ~ backscatter, data=data) coef(model.boot) }, R=100000) # Results boot.ols.100k plot(boot.ols.100k, index=1) boot.ci(boot.ols.100k, conf=0.95, type=c("basic", "bca", "perc"), index=1) boot.ci(boot.ols.100k, conf=0.95, type=c("basic", "bca", "perc"), index=2) # OLS with int=0 boot.ols.int0.100k <- boot(g0.agb, function(data=g0.agb, index) { data <- data[index,] # we sample along rows of the data frame model.boot <- lm(AGB ~ 0 + backscatter, data=data) coef(model.boot) }, R=100000) # Results boot.ols.int0.100k plot(boot.ols.int0.100k, index=1) boot.ci(boot.ols.int0.100k, conf=0.95, type=c("basic", "bca", "perc"), index=1) boot.ci(boot.ols.int0.100k, conf=0.95, type=c("basic", "bca", "perc"), index=2) # Pairs bootstrap with RLM boot.rlm.int0.100k <- boot(g0.agb, function(data=g0.agb, index) { data <- data[index,] # we sample along rows of the data frame model.boot <- rlm(AGB ~ 0 + backscatter, data=data, psi=psi.hampel) coef(model.boot) }, R=100000) # Results boot.rlm.int0.100k plot(boot.rlm.int0.100k, index=1) boot.ci(boot.rlm.int0.100k, conf=0.95, type=c("basic", "bca", "perc"), index=1) plot(boot.rlm.int0.100k$t[,1], boot.rlm.int0.100k$t[,2], xlab="t1", ylab="t2", pch=1) # Pairs bootstrap with RLM w/ intercept boot.rlm.100k <- boot(g0.agb, function(data=g0.agb, index) { data <- data[index,] # we sample along rows of the data frame model.boot <- rlm(AGB ~ backscatter, data=data, psi=psi.hampel) coef(model.boot) }, R=100000) # Results boot.rlm.100k plot(boot.rlm.100k, index=1) boot.ci(boot.rlm.100k, conf=0.95, type=c("basic", "bca", "perc"), index=1) boot.ci(boot.rlm.100k, conf=0.95, type=c("basic", "bca", "perc"), index=2) plot(boot.rlm.100k$t[,1], boot.rlm.100k$t[,2], xlab="t1", ylab="t2", pch=1) #---- # Save save(boot.ols.100k, boot.ols.30k, boot.rlm.100k, boot.rlm.int0.100k, model.10000x10, model.10000x10.rlm, model.10000x10.rlmI, model.10000x10.int0, model.10000x5, model.10000x5.boot, model.10000x5.rlm, model.10000x5.rlmI, model.boot100k, file = "~/PROJECTS/Haiti_biomass/R_out/model_trains.RData") #---- # Residuals bootstrap BootstrapFunctionRegression <- function(data=g0.agb, index) { mod.object <- lm(AGB ~ backscatter, data=data) resids = mod.object$resid fittedValues = mod.object$fitted matr <- model.matrix(mod.object) # generating new values for each y[i], by adding bootstrapped resids to fitted values. Y <- fittedValues + resids[index] # we sample along rows of the data frame # Using model.matrix for the predictors model.boot <- lm(Y ~ 0 + matr, data=data) coef(model.boot) } bootstrappedModel <- boot(g0.agb, BootstrapFunctionRegression, R=10000) bootstrappedModel plot(bootstrappedModel, index=1) boot.ci(bootstrappedModel, conf=0.95, type=c("basic", "bca", "perc"), index=1) boot.ci(bootstrappedModel, conf=0.95, type=c("basic", "bca", "perc"), index=2) # Bootstrap options - manual # from "Using the non-parametric bootstrap for regression models in R" by Ian Dworkin # Non-parametric bootstrap: Pairs (Random x) approach N = 10000 # Perform N bootstrap iterations BootstrapRandomX <- function(dat=g0.agb, mod.formula=formula(AGB ~ backscatter)){ dat.boot <- dat[sample(x = nrow(dat), size = nrow(dat), replace=T),] # samples along index boot.lm <- lm(mod.formula, data=dat.boot) coef(boot.lm) } vector.boot <- t(replicate(N, BootstrapRandomX())) # standard error of the estimates via bootstrap # (standard deviations of those distributions) apply(vector.boot, MARGIN = 2, sd) # Percentile CIs (transposed to compare to simple confints) t(apply(vector.boot, MARGIN = 2, quantile, probs=c(0.025, 0.975))) # Histogram of distributions from Pairs bootstrap par(mfrow=c(1,2)) MultipleHistograms <- function(X=vector.boot){ for (i in 1:ncol(X)){ hist(X[,i], freq=F, main=colnames(X)[i], xlab=colnames(X)[i]) } } MultipleHistograms() pairs(vector.boot) # Use Bias-Corrected (BC) and accelerated (a) non-parametric bootstrap # confidence intervals (BCa) to adjust for biases in the Percentile Confidence # Intervals. We can calculate them with boot() in the boot library. # Non-parametric bootstrap: Residual (Fixed effect / Experimental) approach # Analogous analysis to Monte Carlo simulations to generate confidence intervals # 1) fit model as normal and 2) get residuals, # 3) bootstrap the residuals from the model (r*) # 4) add r* back onto fitted component of the model (i.e. b*x[i] + r*[i]) resid.model.1 <- resid(linreg) par(mfrow=c(2,1)) plot(density(resid.model.1, bw=0.5)) plot(density(resid.model.1, bw=1)) par(mfrow=c(1,2)) plot(resid.model.1 ~ g0.agb$AGB) plot(resid.model.1 ~ g0.agb$backscatter) BootstrapFromResiduals <- function(mod.object = linreg, dat = g0.agb) { resids = mod.object$resid fittedValues = mod.object$fitted matr <- model.matrix(mod.object) # generating new values for each y[i], by adding bootstrapped resids to fitted values. Y <- fittedValues + sample(resids, length(resids), replace=T) # Using model.matrix for the predictors model.boot <- lm(Y ~ 0 + matr, data=dat) coef(model.boot) # Extract coefficients } # Run and look at it. residual.boot.N <- t(replicate(N, BootstrapFromResiduals())) par(mfrow=c(1,2)) MultipleHistograms(X=residual.boot.N) pairs(residual.boot.N) apply(residual.boot.N, MARGIN = 2, sd) t(apply(residual.boot.N, MARGIN=2, quantile, probs=c(0.025, 0.975))) # Monte Carlo bootstrap (parametric) - simulating values in the response SimulationUnderModel <- function(model = linreg) { # extract design matrix matr <- model.matrix(model) rse = summary(model)$sigma df = model$df # incorporate uncertainty in RSE rse.sim <- rse*sqrt(df/rchisq(1, df=df)) # Simulate data (response) conditional on the simulated RSE. y.sim <- rnorm(n = nrow(matr), mean=matr%*%coef(model), sd=rse.sim) # 0 + design matrix (since the intercept is already in the design matrix) lm.sim <- lm(y.sim ~ 0 + matr) # fit model with simulated response coef(lm.sim) } # Run and look at it sim.coef <- t(replicate(N, SimulationUnderModel())) apply(sim.coef, MARGIN = 2, sd) t(apply(sim.coef, MARGIN=2, quantile, probs=c(0.025, 0.975))) par(mfrow=c(1,2)) MultipleHistograms(X=sim.coef) # Compare par(mfrow=c(2,1)) plot(density(residual.boot.N[,2], bw=10), main="Comparing bootstrap methods for parameter uncertainty: backscatter", lwd=2, lty=1) lines(density(vector.boot[,2], bw=10), col='red', lwd=2, lty=1) lines(density(sim.coef[,2], bw=10), col='purple', lwd=2, lty=1) #legend('topright', legend=c("Residual Boot", "Pairs Boot", "Monte Carlo Normal"), # col=c("black", "red", "purple"), lty=c(1,1,1), lwd=2, bg=NULL) # Compare #par(mfrow=c(1,1)) plot(density(residual.boot.N[,1], bw=0.5), main="Comparing bootstrap methods for parameter uncertainty: AGB", lwd=2, lty=1) lines(density(vector.boot[,1], bw=0.5), col='red', lwd=2, lty=1) lines(density(sim.coef[,1], bw=0.5), col='purple', lwd=2, lty=1) #legend('topright', legend=c("Residual Boot", "Pairs Boot", "Monte Carlo Normal"), # col=c("black", "red", "purple"), lty=c(1,1,1), lwd=2, bg=NULL) # ---- sqrt(var(linreg$residuals)) library(normwhn.test) DHtest <- normality.test1(cbind(g0_AGB$AGB_ha, g0_AGB$`2018mean`)) normality.test1(cbind(g0_AGB$AGB_ha)) # Use Model II regression library(lmodel2) lm2 <- lmodel2(AGB_ha ~ `2018mean`, g0_AGB, range.y='interval', range.x='relative') summary(lm2) lm2$regression.results lm2$confidence.intervals lm2$rsquare lm2$H lm2$r lm2$P.param lm2$eigenvalues # 4 figures arranged in 2 rows and 2 columns par(mfrow=c(2,2)) plot.lmodel2(lm2, 'OLS') plot.lmodel2(lm2, 'MA') plot.lmodel2(lm2, 'SMA') plot.lmodel2(lm2, 'RMA') # Get Spearman's rank correlation coefficient corr <- cor.test(x=g0_AGB$`2018mean`, y=g0_AGB$AGB_ha, method = 'spearman') corr$estimate
ee6080c4155c4f9d624c1548f84b5d453aecb4c0
bcbef153e26ebb86bd78ffbcacdb2e31046e168f
/man/subset-dendrogram.Rd
7290479329e91ec938f6b2dd34eff85bad0529d3
[]
no_license
npcooley/SynExtend
5f40f841a4cf609c47127850f5c583a6819b6f06
bd899be4365463884096d74d27411a26b0ac6d7a
refs/heads/master
2023-08-04T04:31:20.644818
2023-07-25T13:21:18
2023-07-25T13:21:18
240,341,045
2
0
null
2023-07-24T15:38:33
2020-02-13T19:14:36
R
UTF-8
R
false
false
1,429
rd
subset-dendrogram.Rd
\name{subset.dendrogram} \alias{subset.dendrogram} \title{ Subsetting dendrogram objects } \description{ Subsets dendrogram objects based on leaf labels. Subsetting can either be by leaves to keep, or leaves to remove. NOTE: This man page is specifically for \code{subset.dendogram}, see \code{?base::subset} for the generic \code{subset} function defined for vectors, matrices, and data frames. } \usage{ \method{subset}{dendrogram}(x, subset, invert=FALSE, ...) } \arguments{ \item{x}{ An object of class \code{'dendogram'} } \item{subset}{ A vector of labels to keep (see \code{invert}). } \item{invert}{ If set to \code{TRUE}, subset to only the leaves \emph{not} in \code{subset}. } \item{...}{ Additional arguments for consistency with generic. } } \value{ An object of class \code{'dendrogram'} corresponding to the subsetted tree. } \author{ Aidan Lakshman \email{ahl27@pitt.edu} } \note{ If none of the labels specified in the \code{subset} argument appear in the tree (or if all do when \code{invert=TRUE}), a warning is thrown and an empty object of class \code{'dendrogram'} is returned. } \seealso{ \code{\link[base]{subset}} } \examples{ d <- as.dendrogram(hclust(dist(USArrests), "ave")) # Show original dendrogram plot(d) # Subset to first 10 labels d1 <- subset(d, labels(d)[1:10]) plot(d1) # Subset d1 to all except the first 2 labels d2 <- subset(d1, labels(d1)[1:2], invert=TRUE) plot(d2) }
d356440f5a68eaf8d2c86070aba1665f8bb54e0c
8284b1b45303414dc77a233ea644488b91d9f649
/man/dbListFields-JDBCQueryResult-missing-method.Rd
99121ca4a8b9ef9e3d8f56b9e2636c8058f79541
[]
no_license
hoesler/dbj
b243eaa14bd18e493ba06e154f02034296969c47
c5a4c81624f5212a3e188bd6102ef61d6057af0b
refs/heads/master
2020-04-06T06:59:06.471743
2016-07-14T10:16:04
2016-07-14T10:16:04
40,183,942
1
0
null
null
null
null
UTF-8
R
false
true
597
rd
dbListFields-JDBCQueryResult-missing-method.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/JDBCQueryResult.R \docType{methods} \name{dbListFields,JDBCQueryResult,missing-method} \alias{dbListFields,JDBCQueryResult,missing-method} \title{List fields in specified table.} \usage{ \S4method{dbListFields}{JDBCQueryResult,missing}(conn, name, ...) } \arguments{ \item{conn}{an \code{\linkS4class{JDBCQueryResult}} object.} \item{name}{Ignored. Needed for compatiblity with generic.} \item{...}{Ignored. Needed for compatiblity with generic.} } \description{ List fields in specified table. } \keyword{internal}
881a0cffca9335c5bcb95075860dbdf7a31db9de
33200c34185918b4490a9fb28b0c2ae9c4d47808
/R/fonctions.R
b6a910ff6f5ea78a11a18492ca1be6f749214322
[]
no_license
timmimohamed/carteMaroc
7c4e3ff45f4fdaf2518988fc6a5a2982e2037cf4
361de1ca6af45ee8952b8cadfd1868fa3fdfa5a2
refs/heads/master
2020-03-28T18:55:50.828041
2018-09-22T06:44:42
2018-09-22T06:44:42
148,927,924
0
0
null
null
null
null
UTF-8
R
false
false
9,809
r
fonctions.R
#' uploadSHP #' #' Cette fonction permet de charger les fichiers shapefile, ou « fichier de formes » est un format de fichier pour les systèmes d'informations géographiques (SIG) pour les régions du Maroc #' @param sans parametres #' @examples #' uploadSHP() #' @export uploadSHP <- function() { print("Chargement des fichiers shp - regions du Maroc....") dir.create("data") download.file("https://raw.githubusercontent.com/timmimohamed/carteMaroc/master/regions/regions.shp", destfile =paste0(getwd(),"/data/","regions.shp"),method="wininet") download.file("https://raw.githubusercontent.com/timmimohamed/carteMaroc/master/regions/regions.prj", destfile =paste0(getwd(),"/data/","regions.prj"),method="wininet") download.file("https://raw.githubusercontent.com/timmimohamed/carteMaroc/master/regions/regions.qpj", destfile =paste0(getwd(),"/data/","regions.qpj"),method="wininet") download.file("https://raw.githubusercontent.com/timmimohamed/carteMaroc/master/regions/regions.dbf", destfile =paste0(getwd(),"/data/","regions.dbf"),method="wininet") download.file("https://raw.githubusercontent.com/timmimohamed/carteMaroc/master/regions/regions.shx", destfile =paste0(getwd(),"/data/","regions.shx"),method="wininet") } #' plotSHP #' #' Cette fonction permet de ploter la carte des regions du Maroc #' @param chemin valeur de chemin : l'eplacement ou ce trouve le fichier shapefile #' @examples #' plotSHP("data/shp_nouveau_decoupage_territorial_2015") #' @export plotSHP <- function(chemin) { print("ploting - regions du Maroc....") shp <- readOGR(dsn=chemin,layer = 'region') plot(shp) } #' dataShpReg #' #' Cette fonction permet de récupérer le contenu (data) du fichier shapefile de regions du Maroc #' @param chemin valeur de chemin : l'eplacement ou ce trouve le fichier shapefile #' @return data shapefile #' @examples #' dataShpReg("data/shp_nouveau_decoupage_territorial_2015") #' @export dataShpReg <- function(chemin) { shp <-readOGR(dsn=chemin,layer = 'region') return(shp) } dataShpBas <- function(chemin) { shp <-readOGR(dsn=chemin,layer = 'bassins') return(shp) } #' mapShpRegs0 #' #' Creation d'une carte interactive avec LEAFLET #' @param shp valeur de data du fichier shapefile #' @param density valeur de density (nombre d'ahibitants par km) #' @param lab valeur de label #' @examples #' shp <- dataShpReg("data/shp_nouveau_decoupage_territorial_2015") #' reg <- read.csv("data/regions.csv", stringsAsFactors = FALSE) #' lab<- sprintf( #' "<strong>%s</strong><br>%s Hab/Km2", #' reg$name,reg$density #' ) %>% lapply(htmltools::HTML) #' mapShpRegs0(shp,density,lab) #' @export mapShpRegs0<- function(shp,density,lab) { bins <- c(0, 5, 10, 20, 40, 100, 200, 250, 300, Inf) pall <- colorBin("BuGn", domain = density, bins = bins) leaflet() %>%addTiles() %>% setView(lng = -7.092620000000011, lat=31.791702,zoom=6) %>% addPolygons( data= spTransform(shp, CRS("+proj=longlat +ellps=GRS80")), weight = 2, opacity = 1, fillColor = ~pall(density), color = "white", dashArray = "3", fillOpacity = 0.7, highlight = highlightOptions( weight = 3, color = "#666", dashArray = "", fillOpacity = 0.7, bringToFront = TRUE), label = lab, labelOptions = labelOptions( style = list("font-weight" = "normal", padding = "3px 8px"), textsize = "15px", direction = "auto") )%>% addLegend(pal = pall, values = density, opacity = 0.7, title = NULL, position = "bottomright") } #' mapShpReg #' #' Cette fonction permet de selectionner la region dont son nom passe au parametre #' @param shp valeur de data du fichier shapefile #' @param reg valeur de la region a afficher #' @param coul valeur de la couleur de la region choisis #' @examples #' shp <- dataShpReg("data/shp_nouveau_decoupage_territorial_2015") #' reg = "Fes-Meknes" #' mapShpReg(shp,reg,"green") #' @export mapShpReg<- function(shp,reg,coul) { shp <- subset(shp, shp$name %in% c(reg)) leaflet() %>%addTiles() %>% setView(lng = -7.092620000000011, lat=31.791702,zoom=6) %>% addPolygons( data= spTransform(shp, CRS("+proj=longlat +ellps=GRS80")), weight = 2, opacity = 1, color = coul, dashArray = "3", fillOpacity = 0.7, label = reg ) } #' mapShpDensPop #' #' Cette fonction permet de selectionner la region dont son nom passe au parametre #' @param shp valeur de data du fichier shapefile #' @param reg valeur de la region a afficher #' @param coul valeur de la couleur de la region choisis #' @examples #' shp <- dataShpReg("data/shp_nouveau_decoupage_territorial_2015") #' reg = "Fes-Meknes" #' mapShpDensPop(shp,reg,"green") #' @export mapShpDensPop<- function(shp,reg,coul,dens) { shp <- subset(shp, shp$name %in% c(reg)) leaflet() %>%addTiles() %>% setView(lng = -7.092620000000011, lat=31.791702,zoom=6) %>% addPolygons( data= spTransform(shp, CRS("+proj=longlat +ellps=GRS80")), weight = 2, opacity = 1, color = coul, dashArray = "3", fillOpacity = 0.7, label = reg )%>% addCircles(long,etab$lat, weight = 1,radius = sqrt(etab$nbr_eleve) * 50, popup = lab, fillOpacity = 0.5) } #' mapShpRegs #' #' Creation d'une carte interactive avec LEAFLET #' @param couleur valeur de couleur degradee selon la densite de la region #' Toutes ces palettes peuvent être utilisées conjointement avec colorRamp () et colorRampPalette (). #' Voici un affichage de toutes les palettes de couleurs disponibles dans le package RColorBrewer. #' > library(RColorBrewer) #' > display.brewer.all() #' Permet d'afficher une liste de combinaisons de couleurs. #' @examples #' mapShpRegs("YlOrRd") #' @export mapShpRegs<- function(couleur) { bins <- c(0, 5, 10, 20, 40, 100, 200, 250, 300, Inf) pall <- colorBin(couleur, domain = shpMaroc@data$density, bins = bins) lab<- sprintf( "<strong>%s</strong><br>%s Hab/Km2", shpMaroc@data$name,shpMaroc@data$density ) %>% lapply(htmltools::HTML) leaflet() %>%addTiles() %>% setView(lng = -7.092620000000011, lat=31.791702,zoom=6) %>% addPolygons( data= shpMaroc, weight = 2, opacity = 1, fillColor = ~pall(shpMaroc@data$density), color = "white", dashArray = "3", fillOpacity = 0.7, highlight = highlightOptions( weight = 3, color = "#666", dashArray = "", fillOpacity = 0.7, bringToFront = TRUE), label = lab, labelOptions = labelOptions( style = list("font-weight" = "normal", padding = "3px 8px"), textsize = "15px", direction = "auto") )%>% addLegend(pal = pall, values = shpMaroc@data$density, opacity = 0.7, title = NULL, position = "bottomright") } #' mapCsvRegs #' #' Cette fonction permet de tracer la carte du Maroc - regions #' @param col valeur de la couleur des frontieres des regions #' @param we valeur de l'paisseur es frontieres des regions #' @examples #' output$regions <- renderLeaflet({ #' mapCsvRegs("red",1.25) #' }) #' @export mapCsvRegs<- function(col,we) { # turn into SpatialLines split_data = lapply(unique(gpsMaroc$group), function(x) { df = as.matrix(gpsMaroc[gpsMaroc$group == x, c("Longitude", "Latitude")]) lns = Lines(Line(df), ID = x) return(lns) }) data_lines = SpatialLines(split_data) leaflet(data_lines) %>% addTiles() %>% addPolylines(color = col, weight=we) } #' mapCsvReg #' #' Cette fonction permet de tracer une region choisis du Maroc #' @param num de la region a afficher #' @param col valeur de la couleur des frontieres des regions #' @param we valeur de l'paisseur es frontieres des regions #' @examples #' output$regions <- renderLeaflet({ #' mapCsvReg(6,"red",1.25) #' }) #' @export mapCsvReg<- function(num,col,we) { gpsMaroc <- subset(gpsMaroc, gpsMaroc$group %in% c(num)) # turn into SpatialLines split_data = lapply(unique(gpsMaroc$group), function(x) { df = as.matrix(gpsMaroc[gpsMaroc$group == x, c("Longitude", "Latitude")]) lns = Lines(Line(df), ID = x) return(lns) }) data_lines = SpatialLines(split_data) leaflet(data_lines) %>% addTiles() %>% addPolylines(color = col, weight=we) %>% addMarkers(lng = -7.092620000000011, lat=31.791702) } #' mapCsvRegMark #' #' Cette fonction permet de tracer une region choisis du Maroc et d'ajouter des Markers selon le choix d'utilisateur #' @param num valeur de la region a afficher #' @param col valeur de la couleur des frontieres des regions #' @param we valeur de l'paisseur des frontieres des regions #' @param long valeur d'un vecteur de longitudes #' @param lat valeur d'un vecteur de latitudes #' @param pop valeur de popup #' @examples #' etab <- read.csv("data/population_Fes_Meknes/etab_meknes.csv", stringsAsFactors = FALSE) #' mapCsvRegMark(3,"green",1.25,etab$long,etab$lat,etab$nbr_eleve) #' @export mapCsvRegMark<- function(num,col,we,long,lat,pop) { gpsMaroc <- subset(gpsMaroc, gpsMaroc$group %in% c(num)) # turn into SpatialLines split_data = lapply(unique(gpsMaroc$group), function(x) { df = as.matrix(gpsMaroc[gpsMaroc$group == x, c("Longitude", "Latitude")]) lns = Lines(Line(df), ID = x) return(lns) }) data_lines = SpatialLines(split_data) leaflet(data_lines) %>% addTiles() %>% addPolylines(color = col, weight=we) %>% addMarkers(lng = long, lat=lat,popup = pop) }
6088ee267e611d865506f6afaf9ac6b0bbf56d61
da9b15a6d555b3c9540705e69f0c4d7baa39a1b3
/scripts/alt_run_2_parse_pdfs_ABBYY_outputs/run_6_fix_spelling.R
704451a4531a09a054a807f540fc27b25d0fba1f
[]
no_license
RohanAlexander/hansard
0be2c6b43b053a048896d3d8d98fc633dde323fa
300fac35e8714871dcf0a6225db3e4a1f33754d2
refs/heads/master
2022-03-11T00:08:03.183499
2019-11-25T10:53:18
2019-11-25T10:53:18
138,767,582
2
0
null
null
null
null
UTF-8
R
false
false
4,047
r
run_6_fix_spelling.R
# !diagnostics off #### Preamble #### # Purpose: This file takes Australian Hansard CSV files that are all in one column and one row and applies a brutal, replacement-based, custom-dictionary, spell-checker. # Author: Rohan Alexander # Email: rohan.alexander@anu.edu.au # Last updated: 11 October 2018 # Prerequisites: You need to have done all the other parsing steps. For testing purposes there should be some in the /outputs/hansard folder. # To do: #### Set up workspace #### # devtools::install_github("DavisVaughan/furrr") library(furrr) library(lubridate) # library(pdftools) library(stringi) library(tidyverse) library(tictoc) library(tm) # update.packages() # Set up furrr plan(multiprocess) # Get the spell checker fix_wrong_spellings <- read_csv2("inputs/misc/misspelt_words_with_corrections.csv") %>% mutate(numberOfCharacters = nchar(original)) %>% arrange(desc(numberOfCharacters)) %>% select(-numberOfCharacters) #### Create lists of CSVs to read #### # Change the path as required: # use_this_path_to_get_csvs <- "outputs/hansard/run_5_output" # use_this_path_to_get_csvs <- "/Volumes/Hansard/parsed/federal/for_zoe/run_5_output" # use_this_path_to_get_csvs <- "/Volumes/Hansard/parsed/federal/senate/run_5_output" use_this_path_to_get_csvs <- "/Volumes/Hansard/parsed/federal/hor/run_5_output" # use_this_path_to_get_csvs <- "/Volumes/Hansard/parsed/federal/hortest" # Get list of Hansard csvs that have been parsed from PDFs and had front matter removed file_names <- list.files( path = use_this_path_to_get_csvs, pattern = "*.csv", recursive = FALSE, full.names = TRUE ) file_names <- file_names %>% sample() # Randomise the order # Just use this to filter if needed file_tibble <- tibble(filename = file_names) file_tibble <- file_tibble %>% mutate(the_year = filename, the_year = str_replace(the_year, "/Volumes/Hansard/parsed/federal/senate/run_5_output/", ""), the_year = str_replace(the_year, "/Volumes/Hansard/parsed/federal/hor/run_5_output/", ""), the_year = str_replace(the_year, ".csv", ""), the_year = ymd(the_year)) %>% # filter(year(the_year) < 1981) %>% filter(year(the_year) == 2015) file_names <- file_tibble$filename rm(file_tibble) # use_this_path_to_save_csvs <- "outputs/hansard/run_6_output" # use_this_path_to_save_csvs <- "/Volumes/Hansard/parsed/federal/for_zoe/run_6_output" # use_this_path_to_save_csvs <- "/Volumes/Hansard/parsed/federal/senate/run_6_output" use_this_path_to_save_csvs <- "/Volumes/Hansard/parsed/federal/hor/run_6_output" # use_this_path_to_save_csvs <- "/Volumes/Hansard/parsed/federal/hortest" save_names <- file_names %>% str_replace(use_this_path_to_get_csvs, use_this_path_to_save_csvs) #### Create the function that will be applied to the files #### fix_spelling <- function(name_of_input_csv_file, name_of_output_csv_file) { # Read in the csv, based on the filename list # name_of_input_csv_file <- "/Volumes/Backup/temp/1971-10-05.csv" # uncomment for testing csv_to_clean <- read_csv(name_of_input_csv_file, trim_ws = FALSE, col_types = cols()) #Fix the spelling csv_to_clean$text <- stri_replace_all_regex( csv_to_clean$text, "\\b" %s+% fix_wrong_spellings$original %s+% "\\b", fix_wrong_spellings$corrected, vectorize_all = FALSE ) # Save file write_csv(csv_to_clean, name_of_output_csv_file) print(paste0("Done with ", name_of_output_csv_file, " at ", Sys.time())) } safely_fix_spelling <- safely(fix_spelling) #### Walk through the lists and parse the PDFs #### # Normal walk2 # tic("Normal walk2") # walk2(file_names, # save_names, # ~ safely_fix_spelling(.x, .y) # ) # toc() # file_names_d <- file_names[1:3] # save_names_d <- save_names[1:3] # Furrr walk2 tic("Furrr walk2") future_walk2(file_names, save_names, ~ safely_fix_spelling(.x, .y), .progress = TRUE) toc()
c3ef4c400cef880ee18959db4cd6b06126f43318
f6721eb9594039cc2743b83a0737ffdf6e726970
/res_tol_ad_manual_setup.R
242222e651c9a1d18f7e6cf42cfdb5e0dbeeb1cf
[]
no_license
morgankain/Stochastic_Virulence_Evolution
a8ff25a7cce60ad56f74b29ba1072c7cb950c57c
397dc3358e0296b576769b6f2f08261fd7e86611
refs/heads/master
2020-05-30T23:45:30.666215
2020-03-16T23:21:34
2020-03-16T23:21:34
190,020,966
0
1
null
null
null
null
UTF-8
R
false
false
4,900
r
res_tol_ad_manual_setup.R
######################################################################### ## Setup AD runs with similar parameter values to the stochastic model ## ######################################################################### nt <- 5e5 num_points <- 1500 rptfreq <- max(nt / num_points, 1) nrpt <- nt %/% rptfreq num_runs <- 250 deterministic <- FALSE mut_link_h <- make.link("log") mut_link_p <- make.link("logit") #alpha0 <- c(seq(0.01, 0.99, by = 0.01), 0.999) #tuning <- c(seq(0.01, 0.99, by = 0.01), 0.999) alpha0 <- c(seq( mut_link_p$linkfun(0.01), mut_link_p$linkfun(0.99) , length = 100)) tuning <- c(seq( mut_link_p$linkfun(0.01), mut_link_p$linkfun(0.99) , length = 100)) ## For the AD model all we really care about is the shpae of the surface, parameters such as ## mu, mut_sd, N don't mean anything params <- data.frame( nt = nt , rptfreq = rptfreq , nrpt = nrpt , mut_var = "beta" , d = 0.01 , mu = 1 , mut_mean = 1 , mut_sd = 1 , tol0 = 1 , res0 = 1 , mut_host_mean_shift = 1 , mut_host_sd_shift = 1 , mut_host_mu_shift = 100000000000 , mut_host_res_bias = 0 , host_dyn_only = FALSE , power_c = 2 , power_exp = 2 , b_decay = 2.3 , b = 0.5 , N = 1 , balance_birth = FALSE , stochastic_birth = TRUE , fill_birth = TRUE , agg_eff_adjust = TRUE , parasite_tuning = TRUE , eff_scale = 3 # rep(c(10, 30, 50), 3) , R0_init = 2 , determ_length = 1000 , determ_timestep = 2 , lsoda_hini = 1 , Imat_seed1 = 13 # rep(c(13, 87, 13), each = 3) , Imat_seed2 = 87 # rep(c(87, 13, 13), each = 3) , numbins = 1000 , deterministic = deterministic) ###### ## Run the sims ###### for (i in 1:nrow(params)) { print(i / nrow(params)) ## Gradient Ascent ## Need power c and power exp? grad_ascent <- with(params , par_evo_AD( c = power_c[i] , curv = power_exp[i] , eff_scale = eff_scale[i] , mut_link = mut_link_p , numbins = numbins[i] ## same parameter as in the RD model, but used a bit differently , Iseed = c(Imat_seed1[i], Imat_seed2[i]) * (numbins[i] / length(alpha0)) , simul_mut = TRUE , max_range = FALSE , debug1 = FALSE , debug1_val = 759 )) grad_ascent <- transform( grad_ascent , param_num = i , eff_scale = params$eff_scale[i] , numbins = params$numbins[i] , Imat_seed1 = params$Imat_seed1[i] , Imat_seed2 = params$Imat_seed2[i]) ## Maximum range in which a postive R0 can be obtained grad_ascent_sing <- with(params , par_evo_AD( c = power_c[i] , curv = power_exp[i] , eff_scale = eff_scale[i] , mut_link = mut_link_p , numbins = numbins[i] ## same parameter as in the RD model, but used a bit differently , Iseed = c(Imat_seed1[i], Imat_seed2[i]) * (numbins[i] / length(alpha0)) , simul_mut = FALSE , max_range = FALSE , debug1 = FALSE , debug1_val = 360 )) grad_ascent_sing <- transform( grad_ascent_sing , param_num = i , eff_scale = params$eff_scale[i] , numbins = params$numbins[i] , Imat_seed1 = params$Imat_seed1[i] , Imat_seed2 = params$Imat_seed2[i]) if (i == 1) { grad_ascent_tot <- grad_ascent grad_ascent_sing_tot <- grad_ascent_sing } else { grad_ascent_tot <- rbind(grad_ascent_tot, grad_ascent) grad_ascent_sing_tot <- rbind(grad_ascent_sing_tot, grad_ascent_sing) } } saveRDS(grad_ascent_tot, "res_out/res_out_AD/AD_grad_ascent.Rds") saveRDS(grad_ascent_sing_tot, "res_out/res_out_AD/AD_grad_ascent_sing.Rds") ###### ## Stochastic AD version for thesis defense ###### i = 1 ## just for single parameter set for (j in 1:10) { print(j / nrow(params)) ## Gradient Ascent ## Need power c and power exp? grad_ascent3 <- with(params , par_evo_AD_rand( c = power_c[i] , curv = power_exp[i] , eff_scale = eff_scale[i] , mut_link = mut_link_p , numbins = numbins[i] ## same parameter as in the RD model, but used a bit differently , Iseed = c(Imat_seed1[i], Imat_seed2[i]) * (numbins[i] / length(alpha0)) , simul_mut = TRUE , max_range = FALSE , debug1 = FALSE , debug1_val = 759 )) grad_ascent3 <- transform( grad_ascent3 , param_num = i , run_num = j , eff_scale = params$eff_scale[i] , numbins = params$numbins[i] , Imat_seed1 = params$Imat_seed1[i] , Imat_seed2 = params$Imat_seed2[i]) if (j == 1) { grad_ascent_tot3 <- grad_ascent3 } else { grad_ascent_tot3 <- rbind(grad_ascent_tot3, grad_ascent3) } } saveRDS(grad_ascent_tot, "res_out/res_out_AD/AD_grad_ascent_stochas.Rds")
7dba8d5b7c05b4f6c38128f221ac6ab25e6b29f3
cf91ca9b31f1a5e6601a4d763175536d425ac66f
/misc/FigS2.R
c7fad0f61f5b6b02a6f7cdd20bbbc82d1e8305e9
[]
no_license
ViolaYing/correlationAnalyzeR
1c0fbbe43d70654e9058a01acc2b01feb352d6e2
a405e878c48d84b8691069c05b142e3435ce3b8d
refs/heads/master
2023-04-08T07:31:44.890040
2021-04-02T19:08:54
2021-04-02T19:08:54
null
0
0
null
null
null
null
UTF-8
R
false
false
4,102
r
FigS2.R
library(tidyverse) library(ggpubr) library(correlationAnalyzeR) res <- correlationAnalyzeR::analyzeGenePairs( genesOfInterest = c("BRCA1", "BRCA2"), Sample_Type = "all", runGSEA = FALSE ) g1 <- res$compared$VST_corrPlot$corrPlot_disease + labs(title = "All samples") resNorm <- correlationAnalyzeR::analyzeGenePairs( genesOfInterest = c("BRCA1", "BRCA2"), Sample_Type = "normal", runGSEA = FALSE ) g2 <- resNorm$compared$VST_corrPlot$corrPlot_disease + labs(title = "Normal samples") resCancer <- correlationAnalyzeR::analyzeGenePairs( genesOfInterest = c("BRCA1", "BRCA2"), Sample_Type = "cancer", runGSEA = FALSE ) g3 <- resCancer$compared$VST_corrPlot$corrPlot_disease + labs(title = "Cancer samples") ggarrange(g1, g2, g3, nrow = 1, align = "hv") + ggsave(filename = "../Manuscript/FinalAssets/FigureS2_raw.png", height = 5, width = 18) cd <- correlationAnalyzeR::human_coldata write_csv(cd, file = "misc/colData.csv") ### IL1B; IL1RN resRev <- analyzeGenePairs(genesOfInterest = c("IL1B", "IL1RN"), runGSEA = F) resRev$compared$VST_corrPlot$corrPlot_tissue g1 <- res$compared$VST_corrPlot$corrPlot_disease + labs(title = "All samples") resNorm <- correlationAnalyzeR::analyzeGenePairs( genesOfInterest = c("BRCA1", "NQO1"), Sample_Type = "normal", runGSEA = FALSE ) g2 <- resNorm$compared$VST_corrPlot$corrPlot_disease + labs(title = "Normal samples") resCancer <- correlationAnalyzeR::analyzeGenePairs( genesOfInterest = c("BRCA1", "NQO1"), Sample_Type = "cancer", runGSEA = FALSE ) g3 <- resCancer$compared$VST_corrPlot$corrPlot_disease + labs(title = "Cancer samples") geneOne <- "BRCA1" geneTwo <- "NQO1" titleStr <- "Normal samples" Rval <- res$compared$VST_corrPlot$Rval Padj <- res$compared$VST_corrPlot$Padj resNorm$compared$VST_corrPlot$corrPlot_VST_data %>% mutate(Condition = ifelse(Group %in% c( # "Mammary - Normal", # "Respiratory - Normal", # "Thyroid - Normal", # "Esophagus - Normal", "Pancreas - Normal", "Prostate - Normal", "Skin - Normal", # "Mammary - Normal", # "Female Reproductive - Normal", # "Respiratory - Normal", # "Kidney - Normal", "Liver - Normal" # "Cartilage - Normal", # "Adispoe - Normal", # "Muscle - Normal", # "Brain - Normal", # "Retina - Normal", # "Endothelial - Normal" ), "Correlated", ifelse(Group %in% c( "Prenatal - Normal", "Male Reproductive - Normal", "Stem Like - Normal", "Bone - Normal" ), "Anticorrelated", "Other" ))) %>% mutate(Condition = factor(Condition, levels = c( "Correlated", "Anticorrelated", "Other" ))) %>% arrange(desc(Condition)) %>% ggplot2::ggplot(ggplot2::aes_string(x = geneOne, y = geneTwo, group="Group", text = "samples", color = "Condition")) + ggplot2::geom_point(alpha = .8) + ggplot2::labs(title = titleStr) + ggplot2::theme_bw(base_size = 16) + ggplot2::xlab(paste0(geneOne, " Expression (VST)")) + ggplot2::ylab(paste0(geneTwo, " Expression (VST)"))
3aaf4c0b32723797bdf4cd5c30f0d1c54f28cb7a
d164a5c189a89d1b61f03693d70898e6f359fff4
/src/53_discriptive_3.R
79e2e94038dc19ecb90e2e7e7b4fe8bbe827fb75
[]
no_license
nishinoh/jahead_secondary2019
fed33966620372b5cf000a4be119de58584be91a
f61e5393b443d840edcb6309d6000ed03aa18254
refs/heads/master
2020-07-04T12:19:55.135616
2020-04-07T09:59:49
2020-04-07T09:59:49
202,285,264
0
0
null
null
null
null
UTF-8
R
false
false
2,381
r
53_discriptive_3.R
library(tidyverse) load("~/Data/JAHEAD/Process_Files/data_after_41_data_frame.rda") load("~/Data/JAHEAD/Process_Files/data_after_14.rda") theme_set(theme_bw(base_size = 18, base_family = "HiraKakuProN-W3") + theme(axis.text=element_text(colour="black"))) # 1. 基本的な情報の作成 ================================== N <- nrow(data_complete_cases) # data_long(回答者のロングデータ)から分析に使われるケースのみ抜き出す # 次の抜き出しでだけ利用する tmp <- data_complete_cases %>% distinct(id_personyear) data_complete_cases_personyear <- data_long %>% filter(id_personyear %in% tmp$id_personyear) rm(tmp) ##### 回答者単位の記述統計 ============================== # ケース数 data_complete_cases_personyear %>% count(wave, ques_type) # アウトカムの分布 data_complete_cases %>% count(do_care_parents_adl, do_care_parents_iadl, do_care_parents_iadl_only) %>% mutate(r = n/N * 100) # ADL・IADLの困難度の分布 p_lim_adl <- data_complete_cases_personyear %>% count(lim_adl) %>% ggplot(aes(x=factor(lim_adl), y=n)) + geom_bar(stat="identity", fill="#009FE1") + labs(x="ADLの困難度") quartz(file="~/downloads/fig_lim_adl.pdf", type="pdf", width=4,height=4) p_lim_adl dev.off() p_lim_iadl <- data_complete_cases_personyear %>% count(lim_iadl) %>% ggplot(aes(x=factor(lim_iadl), y=n)) + geom_bar(stat="identity", fill="#009FE1") + labs(x="IADLの困難度") quartz(file="~/downloads/fig_lim_iadl.pdf", type="pdf", width=4,height=4) p_lim_iadl dev.off() # デイサービス・ホームヘルプの利用頻度 p_use_dayservice <- data_complete_cases_personyear %>% count(use_dayservice_n) %>% ggplot(aes(x=factor(use_dayservice_n), y=n)) + geom_bar(stat="identity", fill="#009FE1") + labs(x="デイサービス利用頻度") quartz(file="~/downloads/fig_use_dayservice.pdf", type="pdf", width=4,height=4) p_use_dayservice dev.off() p_use_homehelp <- data_complete_cases_personyear %>% count(use_homehelp_n) %>% ggplot(aes(x=factor(use_homehelp_n), y=n)) + geom_bar(stat="identity", fill="#009FE1") + labs(x="ホームヘルプ利用頻度") quartz(file="~/downloads/fig_use_homehelp.pdf", type="pdf", width=4,height=4) p_use_homehelp dev.off()
a0c69aa6b9af22a19e8d1e1c0d25fbd9987c031b
f91c8c94d9c374b5d368802a882e8fd9fd9b5932
/R_come_from_sxjns/R语言小作业/e1.R
f0d0aabaa0c12d8e41da38bb7e0c94da0d2e36dd
[]
no_license
chenw265/R_picking
7cd6273d5dc6a1838a4759148a7e3b73f9492af5
bcadbc0b35de5c86176a4bacc277817583a74a07
refs/heads/master
2020-05-23T13:56:07.563751
2019-05-15T09:22:17
2019-05-15T09:22:17
186,789,743
0
0
null
null
null
null
UTF-8
R
false
false
392
r
e1.R
rm(list = ls()) options(stringsAsFactors = F) a=read.table('e1.txt') head(a) library(org.Hs.eg.db) ls("package:org.Hs.eg.db") g2s=toTable(org.Hs.egSYMBOL);head(g2s) g2e=toTable(org.Hs.egENSEMBL);head(g2e) head(g2e) library(stringr) a$ensembl_id=unlist(lapply(a$V1,function(x){ strsplit(as.character(x),'[.]')[[1]][1] }) ) tmp=merge(a,g2e,by='ensembl_id') tmp=merge(tmp,g2s,by='gene_id')
cbe0b963f9604bd7af4b71ca4523701a232d6871
b0c5f1ab6c4e098219b4732f9b050b2aa7871f56
/OptumOncologyEHR/R/OptumOncologyTestFramework.r
e37bf71a4a1a3e11c86ff0b97f97b9786bdfad4f
[]
no_license
chrisknoll/CDMTests
ae89f0ec70c829b33a45205d254430b04775f42e
758fa82381e8c9a5d791890b806f16241df3f2d7
refs/heads/master
2021-04-09T10:20:32.349463
2016-06-09T13:43:50
2016-06-09T14:04:29
60,777,314
0
0
null
null
null
null
UTF-8
R
false
false
461,040
r
OptumOncologyTestFramework.r
frameworkContext <- new.env(parent = emptyenv()); initFramework <- function() { insertSql <- c() insertSql <- c(insertSql, "TRUNCATE TABLE provider;") insertSql <- c(insertSql, "TRUNCATE TABLE care_area;") insertSql <- c(insertSql, "TRUNCATE TABLE patient;") insertSql <- c(insertSql, "TRUNCATE TABLE encounter_provider;") insertSql <- c(insertSql, "TRUNCATE TABLE visit;") insertSql <- c(insertSql, "TRUNCATE TABLE encounter;") insertSql <- c(insertSql, "TRUNCATE TABLE diagnosis;") insertSql <- c(insertSql, "TRUNCATE TABLE nlp_sds;") insertSql <- c(insertSql, "TRUNCATE TABLE nlp_sds_family;") insertSql <- c(insertSql, "TRUNCATE TABLE [procedure];") insertSql <- c(insertSql, "TRUNCATE TABLE labs;") insertSql <- c(insertSql, "TRUNCATE TABLE observations;") insertSql <- c(insertSql, "TRUNCATE TABLE nlp_measurements;") insertSql <- c(insertSql, "TRUNCATE TABLE microbiology;") insertSql <- c(insertSql, "TRUNCATE TABLE nlp_biomarker;") insertSql <- c(insertSql, "TRUNCATE TABLE medication_administrations;") insertSql <- c(insertSql, "TRUNCATE TABLE patient_reported_meds;") insertSql <- c(insertSql, "TRUNCATE TABLE prescriptions_written;") insertSql <- c(insertSql, "TRUNCATE TABLE nlp_drug_rationale;") insertSql <- c(insertSql, "TRUNCATE TABLE immunization;") insertSql <- c(insertSql, "TRUNCATE TABLE insurance;") frameworkContext$insertSql <- insertSql; testSql <- c() testSql <- c(testSql, "IF OBJECT_ID('test_results', 'U') IS NOT NULL") testSql <- c(testSql, " DROP TABLE test_results;") testSql <- c(testSql, "") testSql <- c(testSql, "CREATE TABLE test_results (id INT, description VARCHAR(512), test VARCHAR(256), status VARCHAR(5));") testSql <- c(testSql, "") frameworkContext$testSql <- testSql; frameworkContext$testId = 1; frameworkContext$testDescription = ""; frameworkContext$defaultValues =new.env(parent = emptyenv()); defaults <- new.env(parent = emptyenv()) defaults$provid <- "List truncated..." defaults$specialty <- "Unspecified" defaults$prim_spec_ind <- "1" frameworkContext$defaultValues$provider = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT095853463" defaults$encid <- "List truncated..." defaults$carearea <- "UNKNOWN CARE AREA" defaults$carearea_time <- "1900-01-01.000000" frameworkContext$defaultValues$care_area = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "List truncated..." defaults$birth_yr <- "1930 and Earlier" defaults$gender <- "Male" defaults$race <- "Caucasian" defaults$ethnicity <- "Not Hispanic" defaults$region <- "South" defaults$division <- "South Atl/West South Crl" defaults$avg_hh_income <- "39005.0" defaults$pct_college_educ <- "26.0" defaults$deceased_indicator <- "0" defaults$idn_indicator <- "1" defaults$first_month_active <- "200601" defaults$last_month_active <- "201506" defaults$notes_eligible <- "1" defaults$has_notes <- "1" defaults$sourceid <- "S0034" defaults$source_data_through <- "201506" frameworkContext$defaultValues$patient = defaults; defaults <- new.env(parent = emptyenv()) defaults$encid <- "List truncated..." defaults$provid <- "70371" defaults$provider_role <- "ATTENDING" frameworkContext$defaultValues$encounter_provider = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT091048451" defaults$visitid <- "List truncated..." defaults$visit_type <- "Inpatient" defaults$visit_start_date <- "2012-08-13" defaults$visit_start_time <- "1900-01-01.000000" defaults$visit_end_date <- "2014-07-25" defaults$visit_end_time <- "1900-01-01.000000" defaults$discharge_disposition <- "01 DISCHARGED TO HOME OR SELF CARE" defaults$admission_source <- "Referred by physician or self referral; non-healthcare facility point of origin" frameworkContext$defaultValues$visit = defaults; defaults <- new.env(parent = emptyenv()) defaults$encid <- "List truncated..." defaults$ptid <- "List truncated..." defaults$interaction_type <- "Office or clinic patient" defaults$interaction_date <- "2014-06-16" defaults$interaction_time <- "1900-01-01.000000" frameworkContext$defaultValues$encounter = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "List truncated..." defaults$diagnosis_status <- "Diagnosis of" defaults$diagnosis_cd_type <- "ICD9" defaults$diag_date <- "2014-05-02" defaults$diag_time <- "1900-01-01.000000" defaults$primary_diagnosis <- "0" defaults$admitting_diagnosis <- "0" defaults$discharge_diagnosis <- "0" defaults$poa <- "0" defaults$problem_list <- "N" frameworkContext$defaultValues$diagnosis = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "List truncated..." defaults$note_date <- "2013-04-23" defaults$sds_term <- "pain" frameworkContext$defaultValues$nlp_sds = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT084524827" defaults$note_date <- "2014-07-23" defaults$sds_term <- "cancer" defaults$sds_family_member <- "who=family" defaults$note_section <- "family medical history" frameworkContext$defaultValues$nlp_sds_family = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "List truncated..." defaults$proc_code_type <- "CPT4" defaults$proc_date <- "2012-10-22" defaults$proc_time <- "1900-01-01.000000" frameworkContext$defaultValues$procedure = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT143890838" defaults$test_name <- "O2 saturation.oximetry" defaults$result_time <- "1900-01-01.000000" defaults$test_result <- "Negative" defaults$result_unit <- "%" defaults$evaluated_for_range <- "N" defaults$value_within_range <- "U" frameworkContext$defaultValues$labs = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT143890838" defaults$obs_type <- "SBP" defaults$obs_date <- "2014-06-10" defaults$obs_time <- "1900-01-01.000000" defaults$obs_result <- "18" defaults$obs_unit <- "mm Hg" defaults$evaluated_for_range <- "N" defaults$value_within_range <- "U" frameworkContext$defaultValues$observations = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT130234983" defaults$note_date <- "2013-04-23" defaults$measurement_type <- "DBP" defaults$measurement_value <- "2" frameworkContext$defaultValues$nlp_measurements = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT117858758" defaults$order_time <- "1900-01-01.000000" defaults$collect_time <- "1900-01-01.000000" defaults$result_date <- "2015-05-22" defaults$result_time <- "1900-01-01.000000" defaults$specimen_source <- "Urine" frameworkContext$defaultValues$microbiology = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT084542965" defaults$note_date <- "2013-04-23" defaults$biomarker <- "CD20" defaults$biomarker_status <- "positive" frameworkContext$defaultValues$nlp_biomarker = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT093154612" defaults$drug_name <- "SODIUM CHLORIDE 0.9 %" defaults$ndc <- "00338004904" defaults$ndc_source <- "Derived" defaults$order_date <- "2014-10-07" defaults$order_time <- "1900-01-01.000000" defaults$route <- "Intravenous" defaults$generic_desc <- "SODIUM CHLORIDE" defaults$drug_class <- "Intravenous nutritional therapy; electrolyte; trace element; metal; vitamin; alone or combinations" frameworkContext$defaultValues$medication_administrations = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT155237089" defaults$reported_date <- "2009-03-27" defaults$ndc <- "49999035930" defaults$route <- "Oral" defaults$strength_unit <- "mg" defaults$dosage_form <- "Tabs" defaults$drug_class <- "Salicylates" defaults$ndc_source <- "Direct" frameworkContext$defaultValues$patient_reported_meds = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT118881881" defaults$rxdate <- "2014-02-24" defaults$rxtime <- "1900-01-01.000000" defaults$ndc <- "00406035705" defaults$quantity_per_fill <- "30" defaults$num_refills <- "0.0" defaults$route <- "Oral" defaults$strength_unit <- "mg" defaults$ndc_source <- "Direct" defaults$drug_class <- "HMG & CoA reductase inhibitors (statins)" defaults$dosage_form <- "Tabs" frameworkContext$defaultValues$prescriptions_written = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT191017751" defaults$note_date <- "2013-04-23" defaults$note_section <- "MEDICATIONS" defaults$drug_name <- "ASPIRIN" defaults$drug_action <- "N/A" defaults$drug_action_preposition <- "OF" frameworkContext$defaultValues$nlp_drug_rationale = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT194773862" defaults$ndc <- "49281001350" defaults$ndc_source <- "Derived" defaults$immunization_desc <- "INFLUENZA VIRUS VACCINE; INACTIVATED" defaults$mapped_name <- "Influenza Inactivated Vaccine" frameworkContext$defaultValues$immunization = defaults; defaults <- new.env(parent = emptyenv()) defaults$ptid <- "PT130555350" defaults$encid <- "List truncated..." defaults$insurance_date <- "2008-09-15" defaults$insurance_time <- "1900-01-01.000000" defaults$ins_type <- "Medicare" frameworkContext$defaultValues$insurance = defaults; } declareTest <- function(id, description) { frameworkContext$testId = id; frameworkContext$testDescription = description; sql <- c("", paste0("-- ", id, ": ", description)); frameworkContext$insertSql = c(frameworkContext$insertSql, sql); frameworkContext$testSql = c(frameworkContext$testSql, sql); } set_defaults_provider <- function(provid, specialty, prim_spec_ind) { defaults <- frameworkContext$defaultValues$provider; if (!missing(provid)) { defaults$provid <- provid } if (!missing(specialty)) { defaults$specialty <- specialty } if (!missing(prim_spec_ind)) { defaults$prim_spec_ind <- prim_spec_ind } invisible(defaults) } set_defaults_care_area <- function(ptid, encid, carearea, carearea_date, carearea_time) { defaults <- frameworkContext$defaultValues$care_area; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(carearea)) { defaults$carearea <- carearea } if (!missing(carearea_date)) { defaults$carearea_date <- carearea_date } if (!missing(carearea_time)) { defaults$carearea_time <- carearea_time } invisible(defaults) } set_defaults_patient <- function(ptid, birth_yr, gender, race, ethnicity, region, division, avg_hh_income, pct_college_educ, deceased_indicator, date_of_death, provid_pcp, idn_indicator, first_month_active, last_month_active, notes_eligible, has_notes, sourceid, source_data_through) { defaults <- frameworkContext$defaultValues$patient; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(birth_yr)) { defaults$birth_yr <- birth_yr } if (!missing(gender)) { defaults$gender <- gender } if (!missing(race)) { defaults$race <- race } if (!missing(ethnicity)) { defaults$ethnicity <- ethnicity } if (!missing(region)) { defaults$region <- region } if (!missing(division)) { defaults$division <- division } if (!missing(avg_hh_income)) { defaults$avg_hh_income <- avg_hh_income } if (!missing(pct_college_educ)) { defaults$pct_college_educ <- pct_college_educ } if (!missing(deceased_indicator)) { defaults$deceased_indicator <- deceased_indicator } if (!missing(date_of_death)) { defaults$date_of_death <- date_of_death } if (!missing(provid_pcp)) { defaults$provid_pcp <- provid_pcp } if (!missing(idn_indicator)) { defaults$idn_indicator <- idn_indicator } if (!missing(first_month_active)) { defaults$first_month_active <- first_month_active } if (!missing(last_month_active)) { defaults$last_month_active <- last_month_active } if (!missing(notes_eligible)) { defaults$notes_eligible <- notes_eligible } if (!missing(has_notes)) { defaults$has_notes <- has_notes } if (!missing(sourceid)) { defaults$sourceid <- sourceid } if (!missing(source_data_through)) { defaults$source_data_through <- source_data_through } invisible(defaults) } set_defaults_encounter_provider <- function(encid, provid, provider_role) { defaults <- frameworkContext$defaultValues$encounter_provider; if (!missing(encid)) { defaults$encid <- encid } if (!missing(provid)) { defaults$provid <- provid } if (!missing(provider_role)) { defaults$provider_role <- provider_role } invisible(defaults) } set_defaults_visit <- function(ptid, visitid, visit_type, visit_start_date, visit_start_time, visit_end_date, visit_end_time, discharge_disposition, admission_source, drg) { defaults <- frameworkContext$defaultValues$visit; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(visitid)) { defaults$visitid <- visitid } if (!missing(visit_type)) { defaults$visit_type <- visit_type } if (!missing(visit_start_date)) { defaults$visit_start_date <- visit_start_date } if (!missing(visit_start_time)) { defaults$visit_start_time <- visit_start_time } if (!missing(visit_end_date)) { defaults$visit_end_date <- visit_end_date } if (!missing(visit_end_time)) { defaults$visit_end_time <- visit_end_time } if (!missing(discharge_disposition)) { defaults$discharge_disposition <- discharge_disposition } if (!missing(admission_source)) { defaults$admission_source <- admission_source } if (!missing(drg)) { defaults$drg <- drg } invisible(defaults) } set_defaults_encounter <- function(encid, ptid, visitid, interaction_type, interaction_date, interaction_time) { defaults <- frameworkContext$defaultValues$encounter; if (!missing(encid)) { defaults$encid <- encid } if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(visitid)) { defaults$visitid <- visitid } if (!missing(interaction_type)) { defaults$interaction_type <- interaction_type } if (!missing(interaction_date)) { defaults$interaction_date <- interaction_date } if (!missing(interaction_time)) { defaults$interaction_time <- interaction_time } invisible(defaults) } set_defaults_diagnosis <- function(ptid, diagnosis_status, diagnosis_cd, diagnosis_cd_type, diag_date, diag_time, encid, primary_diagnosis, admitting_diagnosis, discharge_diagnosis, poa, problem_list) { defaults <- frameworkContext$defaultValues$diagnosis; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(diagnosis_status)) { defaults$diagnosis_status <- diagnosis_status } if (!missing(diagnosis_cd)) { defaults$diagnosis_cd <- diagnosis_cd } if (!missing(diagnosis_cd_type)) { defaults$diagnosis_cd_type <- diagnosis_cd_type } if (!missing(diag_date)) { defaults$diag_date <- diag_date } if (!missing(diag_time)) { defaults$diag_time <- diag_time } if (!missing(encid)) { defaults$encid <- encid } if (!missing(primary_diagnosis)) { defaults$primary_diagnosis <- primary_diagnosis } if (!missing(admitting_diagnosis)) { defaults$admitting_diagnosis <- admitting_diagnosis } if (!missing(discharge_diagnosis)) { defaults$discharge_diagnosis <- discharge_diagnosis } if (!missing(poa)) { defaults$poa <- poa } if (!missing(problem_list)) { defaults$problem_list <- problem_list } invisible(defaults) } set_defaults_nlp_sds <- function(ptid, encid, note_date, sds_term, sds_location, sds_attribute, sds_sentiment, note_section) { defaults <- frameworkContext$defaultValues$nlp_sds; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(note_date)) { defaults$note_date <- note_date } if (!missing(sds_term)) { defaults$sds_term <- sds_term } if (!missing(sds_location)) { defaults$sds_location <- sds_location } if (!missing(sds_attribute)) { defaults$sds_attribute <- sds_attribute } if (!missing(sds_sentiment)) { defaults$sds_sentiment <- sds_sentiment } if (!missing(note_section)) { defaults$note_section <- note_section } invisible(defaults) } set_defaults_nlp_sds_family <- function(ptid, encid, note_date, sds_term, sds_location, sds_family_member, sds_sentiment, note_section) { defaults <- frameworkContext$defaultValues$nlp_sds_family; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(note_date)) { defaults$note_date <- note_date } if (!missing(sds_term)) { defaults$sds_term <- sds_term } if (!missing(sds_location)) { defaults$sds_location <- sds_location } if (!missing(sds_family_member)) { defaults$sds_family_member <- sds_family_member } if (!missing(sds_sentiment)) { defaults$sds_sentiment <- sds_sentiment } if (!missing(note_section)) { defaults$note_section <- note_section } invisible(defaults) } set_defaults_procedure <- function(ptid, proc_code, proc_code_type, proc_date, proc_time, provid_perform, encid, proc_desc, provid_order, betos_code, betos_desc) { defaults <- frameworkContext$defaultValues$procedure; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(proc_code)) { defaults$proc_code <- proc_code } if (!missing(proc_code_type)) { defaults$proc_code_type <- proc_code_type } if (!missing(proc_date)) { defaults$proc_date <- proc_date } if (!missing(proc_time)) { defaults$proc_time <- proc_time } if (!missing(provid_perform)) { defaults$provid_perform <- provid_perform } if (!missing(encid)) { defaults$encid <- encid } if (!missing(proc_desc)) { defaults$proc_desc <- proc_desc } if (!missing(provid_order)) { defaults$provid_order <- provid_order } if (!missing(betos_code)) { defaults$betos_code <- betos_code } if (!missing(betos_desc)) { defaults$betos_desc <- betos_desc } invisible(defaults) } set_defaults_labs <- function(ptid, encid, test_name, order_date, order_time, collected_date, collected_time, result_date, result_time, test_result, relative_indicator, result_unit, normal_range, evaluated_for_range, value_within_range) { defaults <- frameworkContext$defaultValues$labs; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(test_name)) { defaults$test_name <- test_name } if (!missing(order_date)) { defaults$order_date <- order_date } if (!missing(order_time)) { defaults$order_time <- order_time } if (!missing(collected_date)) { defaults$collected_date <- collected_date } if (!missing(collected_time)) { defaults$collected_time <- collected_time } if (!missing(result_date)) { defaults$result_date <- result_date } if (!missing(result_time)) { defaults$result_time <- result_time } if (!missing(test_result)) { defaults$test_result <- test_result } if (!missing(relative_indicator)) { defaults$relative_indicator <- relative_indicator } if (!missing(result_unit)) { defaults$result_unit <- result_unit } if (!missing(normal_range)) { defaults$normal_range <- normal_range } if (!missing(evaluated_for_range)) { defaults$evaluated_for_range <- evaluated_for_range } if (!missing(value_within_range)) { defaults$value_within_range <- value_within_range } invisible(defaults) } set_defaults_observations <- function(ptid, encid, obs_type, obs_date, obs_time, obs_result, obs_unit, evaluated_for_range, value_within_range) { defaults <- frameworkContext$defaultValues$observations; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(obs_type)) { defaults$obs_type <- obs_type } if (!missing(obs_date)) { defaults$obs_date <- obs_date } if (!missing(obs_time)) { defaults$obs_time <- obs_time } if (!missing(obs_result)) { defaults$obs_result <- obs_result } if (!missing(obs_unit)) { defaults$obs_unit <- obs_unit } if (!missing(evaluated_for_range)) { defaults$evaluated_for_range <- evaluated_for_range } if (!missing(value_within_range)) { defaults$value_within_range <- value_within_range } invisible(defaults) } set_defaults_nlp_measurements <- function(ptid, encid, note_date, measurement_type, measurement_value, measurement_detail, note_section, measurement_date) { defaults <- frameworkContext$defaultValues$nlp_measurements; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(note_date)) { defaults$note_date <- note_date } if (!missing(measurement_type)) { defaults$measurement_type <- measurement_type } if (!missing(measurement_value)) { defaults$measurement_value <- measurement_value } if (!missing(measurement_detail)) { defaults$measurement_detail <- measurement_detail } if (!missing(note_section)) { defaults$note_section <- note_section } if (!missing(measurement_date)) { defaults$measurement_date <- measurement_date } invisible(defaults) } set_defaults_microbiology <- function(ptid, encid, order_date, order_time, collect_date, collect_time, receive_date, receive_time, result_date, result_time, result_status, specimen_source, organism, mapped_organism_found, mapped_organism_excluded, culture_growth, culture_value, culture_unit, antibiotic, mapped_antibiotic, sensitivity) { defaults <- frameworkContext$defaultValues$microbiology; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(order_date)) { defaults$order_date <- order_date } if (!missing(order_time)) { defaults$order_time <- order_time } if (!missing(collect_date)) { defaults$collect_date <- collect_date } if (!missing(collect_time)) { defaults$collect_time <- collect_time } if (!missing(receive_date)) { defaults$receive_date <- receive_date } if (!missing(receive_time)) { defaults$receive_time <- receive_time } if (!missing(result_date)) { defaults$result_date <- result_date } if (!missing(result_time)) { defaults$result_time <- result_time } if (!missing(result_status)) { defaults$result_status <- result_status } if (!missing(specimen_source)) { defaults$specimen_source <- specimen_source } if (!missing(organism)) { defaults$organism <- organism } if (!missing(mapped_organism_found)) { defaults$mapped_organism_found <- mapped_organism_found } if (!missing(mapped_organism_excluded)) { defaults$mapped_organism_excluded <- mapped_organism_excluded } if (!missing(culture_growth)) { defaults$culture_growth <- culture_growth } if (!missing(culture_value)) { defaults$culture_value <- culture_value } if (!missing(culture_unit)) { defaults$culture_unit <- culture_unit } if (!missing(antibiotic)) { defaults$antibiotic <- antibiotic } if (!missing(mapped_antibiotic)) { defaults$mapped_antibiotic <- mapped_antibiotic } if (!missing(sensitivity)) { defaults$sensitivity <- sensitivity } invisible(defaults) } set_defaults_nlp_biomarker <- function(ptid, note_date, biomarker, variation_detail, biomarker_status) { defaults <- frameworkContext$defaultValues$nlp_biomarker; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(note_date)) { defaults$note_date <- note_date } if (!missing(biomarker)) { defaults$biomarker <- biomarker } if (!missing(variation_detail)) { defaults$variation_detail <- variation_detail } if (!missing(biomarker_status)) { defaults$biomarker_status <- biomarker_status } invisible(defaults) } set_defaults_medication_administrations <- function(ptid, encid, drug_name, ndc, ndc_source, order_date, order_time, admin_date, admin_time, provid, quantity_of_dose, route, strength, strength_unit, dosage_form, dosefreq, generic_desc, drug_class) { defaults <- frameworkContext$defaultValues$medication_administrations; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(drug_name)) { defaults$drug_name <- drug_name } if (!missing(ndc)) { defaults$ndc <- ndc } if (!missing(ndc_source)) { defaults$ndc_source <- ndc_source } if (!missing(order_date)) { defaults$order_date <- order_date } if (!missing(order_time)) { defaults$order_time <- order_time } if (!missing(admin_date)) { defaults$admin_date <- admin_date } if (!missing(admin_time)) { defaults$admin_time <- admin_time } if (!missing(provid)) { defaults$provid <- provid } if (!missing(quantity_of_dose)) { defaults$quantity_of_dose <- quantity_of_dose } if (!missing(route)) { defaults$route <- route } if (!missing(strength)) { defaults$strength <- strength } if (!missing(strength_unit)) { defaults$strength_unit <- strength_unit } if (!missing(dosage_form)) { defaults$dosage_form <- dosage_form } if (!missing(dosefreq)) { defaults$dosefreq <- dosefreq } if (!missing(generic_desc)) { defaults$generic_desc <- generic_desc } if (!missing(drug_class)) { defaults$drug_class <- drug_class } invisible(defaults) } set_defaults_patient_reported_meds <- function(ptid, reported_date, ndc, provid, route, quantity_of_dose, strength, strength_unit, dosage_form, dosefreq, generic_desc, drug_class, drug_name, ndc_source) { defaults <- frameworkContext$defaultValues$patient_reported_meds; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(reported_date)) { defaults$reported_date <- reported_date } if (!missing(ndc)) { defaults$ndc <- ndc } if (!missing(provid)) { defaults$provid <- provid } if (!missing(route)) { defaults$route <- route } if (!missing(quantity_of_dose)) { defaults$quantity_of_dose <- quantity_of_dose } if (!missing(strength)) { defaults$strength <- strength } if (!missing(strength_unit)) { defaults$strength_unit <- strength_unit } if (!missing(dosage_form)) { defaults$dosage_form <- dosage_form } if (!missing(dosefreq)) { defaults$dosefreq <- dosefreq } if (!missing(generic_desc)) { defaults$generic_desc <- generic_desc } if (!missing(drug_class)) { defaults$drug_class <- drug_class } if (!missing(drug_name)) { defaults$drug_name <- drug_name } if (!missing(ndc_source)) { defaults$ndc_source <- ndc_source } invisible(defaults) } set_defaults_prescriptions_written <- function(ptid, rxdate, rxtime, ndc, quantity_per_fill, num_refills, days_supply, provid, route, quantity_of_dose, strength, strength_unit, generic_desc, ndc_source, drug_class, drug_name, dosefreq, dosage_form) { defaults <- frameworkContext$defaultValues$prescriptions_written; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(rxdate)) { defaults$rxdate <- rxdate } if (!missing(rxtime)) { defaults$rxtime <- rxtime } if (!missing(ndc)) { defaults$ndc <- ndc } if (!missing(quantity_per_fill)) { defaults$quantity_per_fill <- quantity_per_fill } if (!missing(num_refills)) { defaults$num_refills <- num_refills } if (!missing(days_supply)) { defaults$days_supply <- days_supply } if (!missing(provid)) { defaults$provid <- provid } if (!missing(route)) { defaults$route <- route } if (!missing(quantity_of_dose)) { defaults$quantity_of_dose <- quantity_of_dose } if (!missing(strength)) { defaults$strength <- strength } if (!missing(strength_unit)) { defaults$strength_unit <- strength_unit } if (!missing(generic_desc)) { defaults$generic_desc <- generic_desc } if (!missing(ndc_source)) { defaults$ndc_source <- ndc_source } if (!missing(drug_class)) { defaults$drug_class <- drug_class } if (!missing(drug_name)) { defaults$drug_name <- drug_name } if (!missing(dosefreq)) { defaults$dosefreq <- dosefreq } if (!missing(dosage_form)) { defaults$dosage_form <- dosage_form } invisible(defaults) } set_defaults_nlp_drug_rationale <- function(ptid, encid, note_date, note_section, drug_name, drug_action, drug_action_preposition, reason_general, sentiment, sentiment_who) { defaults <- frameworkContext$defaultValues$nlp_drug_rationale; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(note_date)) { defaults$note_date <- note_date } if (!missing(note_section)) { defaults$note_section <- note_section } if (!missing(drug_name)) { defaults$drug_name <- drug_name } if (!missing(drug_action)) { defaults$drug_action <- drug_action } if (!missing(drug_action_preposition)) { defaults$drug_action_preposition <- drug_action_preposition } if (!missing(reason_general)) { defaults$reason_general <- reason_general } if (!missing(sentiment)) { defaults$sentiment <- sentiment } if (!missing(sentiment_who)) { defaults$sentiment_who <- sentiment_who } invisible(defaults) } set_defaults_immunization <- function(ptid, immunization_date, ndc, pt_reported, ndc_source, immunization_desc, mapped_name) { defaults <- frameworkContext$defaultValues$immunization; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(immunization_date)) { defaults$immunization_date <- immunization_date } if (!missing(ndc)) { defaults$ndc <- ndc } if (!missing(pt_reported)) { defaults$pt_reported <- pt_reported } if (!missing(ndc_source)) { defaults$ndc_source <- ndc_source } if (!missing(immunization_desc)) { defaults$immunization_desc <- immunization_desc } if (!missing(mapped_name)) { defaults$mapped_name <- mapped_name } invisible(defaults) } set_defaults_insurance <- function(ptid, encid, insurance_date, insurance_time, ins_type) { defaults <- frameworkContext$defaultValues$insurance; if (!missing(ptid)) { defaults$ptid <- ptid } if (!missing(encid)) { defaults$encid <- encid } if (!missing(insurance_date)) { defaults$insurance_date <- insurance_date } if (!missing(insurance_time)) { defaults$insurance_time <- insurance_time } if (!missing(ins_type)) { defaults$ins_type <- ins_type } invisible(defaults) } get_defaults_provider <- function() { return(frameworkContext$defaultValues) } get_defaults_care_area <- function() { return(frameworkContext$defaultValues) } get_defaults_patient <- function() { return(frameworkContext$defaultValues) } get_defaults_encounter_provider <- function() { return(frameworkContext$defaultValues) } get_defaults_visit <- function() { return(frameworkContext$defaultValues) } get_defaults_encounter <- function() { return(frameworkContext$defaultValues) } get_defaults_diagnosis <- function() { return(frameworkContext$defaultValues) } get_defaults_nlp_sds <- function() { return(frameworkContext$defaultValues) } get_defaults_nlp_sds_family <- function() { return(frameworkContext$defaultValues) } get_defaults_procedure <- function() { return(frameworkContext$defaultValues) } get_defaults_labs <- function() { return(frameworkContext$defaultValues) } get_defaults_observations <- function() { return(frameworkContext$defaultValues) } get_defaults_nlp_measurements <- function() { return(frameworkContext$defaultValues) } get_defaults_microbiology <- function() { return(frameworkContext$defaultValues) } get_defaults_nlp_biomarker <- function() { return(frameworkContext$defaultValues) } get_defaults_medication_administrations <- function() { return(frameworkContext$defaultValues) } get_defaults_patient_reported_meds <- function() { return(frameworkContext$defaultValues) } get_defaults_prescriptions_written <- function() { return(frameworkContext$defaultValues) } get_defaults_nlp_drug_rationale <- function() { return(frameworkContext$defaultValues) } get_defaults_immunization <- function() { return(frameworkContext$defaultValues) } get_defaults_insurance <- function() { return(frameworkContext$defaultValues) } add_provider <- function(provid, specialty, prim_spec_ind) { defaults <- frameworkContext$defaultValues$provider; insertFields <- c() insertValues <- c() if (missing(provid)) { provid <- defaults$provid } if (!is.null(provid)) { insertFields <- c(insertFields, "provid") insertValues <- c(insertValues, provid) } if (missing(specialty)) { specialty <- defaults$specialty } if (!is.null(specialty)) { insertFields <- c(insertFields, "specialty") insertValues <- c(insertValues, specialty) } if (missing(prim_spec_ind)) { prim_spec_ind <- defaults$prim_spec_ind } if (!is.null(prim_spec_ind)) { insertFields <- c(insertFields, "prim_spec_ind") insertValues <- c(insertValues, prim_spec_ind) } statement <- paste0("INSERT INTO provider (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_care_area <- function(ptid, encid, carearea, carearea_date, carearea_time) { defaults <- frameworkContext$defaultValues$care_area; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(carearea)) { carearea <- defaults$carearea } if (!is.null(carearea)) { insertFields <- c(insertFields, "carearea") insertValues <- c(insertValues, carearea) } if (missing(carearea_date)) { carearea_date <- defaults$carearea_date } if (!is.null(carearea_date)) { insertFields <- c(insertFields, "carearea_date") insertValues <- c(insertValues, carearea_date) } if (missing(carearea_time)) { carearea_time <- defaults$carearea_time } if (!is.null(carearea_time)) { insertFields <- c(insertFields, "carearea_time") insertValues <- c(insertValues, carearea_time) } statement <- paste0("INSERT INTO care_area (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_patient <- function(ptid, birth_yr, gender, race, ethnicity, region, division, avg_hh_income, pct_college_educ, deceased_indicator, date_of_death, provid_pcp, idn_indicator, first_month_active, last_month_active, notes_eligible, has_notes, sourceid, source_data_through) { defaults <- frameworkContext$defaultValues$patient; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(birth_yr)) { birth_yr <- defaults$birth_yr } if (!is.null(birth_yr)) { insertFields <- c(insertFields, "birth_yr") insertValues <- c(insertValues, birth_yr) } if (missing(gender)) { gender <- defaults$gender } if (!is.null(gender)) { insertFields <- c(insertFields, "gender") insertValues <- c(insertValues, gender) } if (missing(race)) { race <- defaults$race } if (!is.null(race)) { insertFields <- c(insertFields, "race") insertValues <- c(insertValues, race) } if (missing(ethnicity)) { ethnicity <- defaults$ethnicity } if (!is.null(ethnicity)) { insertFields <- c(insertFields, "ethnicity") insertValues <- c(insertValues, ethnicity) } if (missing(region)) { region <- defaults$region } if (!is.null(region)) { insertFields <- c(insertFields, "region") insertValues <- c(insertValues, region) } if (missing(division)) { division <- defaults$division } if (!is.null(division)) { insertFields <- c(insertFields, "division") insertValues <- c(insertValues, division) } if (missing(avg_hh_income)) { avg_hh_income <- defaults$avg_hh_income } if (!is.null(avg_hh_income)) { insertFields <- c(insertFields, "avg_hh_income") insertValues <- c(insertValues, avg_hh_income) } if (missing(pct_college_educ)) { pct_college_educ <- defaults$pct_college_educ } if (!is.null(pct_college_educ)) { insertFields <- c(insertFields, "pct_college_educ") insertValues <- c(insertValues, pct_college_educ) } if (missing(deceased_indicator)) { deceased_indicator <- defaults$deceased_indicator } if (!is.null(deceased_indicator)) { insertFields <- c(insertFields, "deceased_indicator") insertValues <- c(insertValues, deceased_indicator) } if (missing(date_of_death)) { date_of_death <- defaults$date_of_death } if (!is.null(date_of_death)) { insertFields <- c(insertFields, "date_of_death") insertValues <- c(insertValues, date_of_death) } if (missing(provid_pcp)) { provid_pcp <- defaults$provid_pcp } if (!is.null(provid_pcp)) { insertFields <- c(insertFields, "provid_pcp") insertValues <- c(insertValues, provid_pcp) } if (missing(idn_indicator)) { idn_indicator <- defaults$idn_indicator } if (!is.null(idn_indicator)) { insertFields <- c(insertFields, "idn_indicator") insertValues <- c(insertValues, idn_indicator) } if (missing(first_month_active)) { first_month_active <- defaults$first_month_active } if (!is.null(first_month_active)) { insertFields <- c(insertFields, "first_month_active") insertValues <- c(insertValues, first_month_active) } if (missing(last_month_active)) { last_month_active <- defaults$last_month_active } if (!is.null(last_month_active)) { insertFields <- c(insertFields, "last_month_active") insertValues <- c(insertValues, last_month_active) } if (missing(notes_eligible)) { notes_eligible <- defaults$notes_eligible } if (!is.null(notes_eligible)) { insertFields <- c(insertFields, "notes_eligible") insertValues <- c(insertValues, notes_eligible) } if (missing(has_notes)) { has_notes <- defaults$has_notes } if (!is.null(has_notes)) { insertFields <- c(insertFields, "has_notes") insertValues <- c(insertValues, has_notes) } if (missing(sourceid)) { sourceid <- defaults$sourceid } if (!is.null(sourceid)) { insertFields <- c(insertFields, "sourceid") insertValues <- c(insertValues, sourceid) } if (missing(source_data_through)) { source_data_through <- defaults$source_data_through } if (!is.null(source_data_through)) { insertFields <- c(insertFields, "source_data_through") insertValues <- c(insertValues, source_data_through) } statement <- paste0("INSERT INTO patient (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_encounter_provider <- function(encid, provid, provider_role) { defaults <- frameworkContext$defaultValues$encounter_provider; insertFields <- c() insertValues <- c() if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(provid)) { provid <- defaults$provid } if (!is.null(provid)) { insertFields <- c(insertFields, "provid") insertValues <- c(insertValues, provid) } if (missing(provider_role)) { provider_role <- defaults$provider_role } if (!is.null(provider_role)) { insertFields <- c(insertFields, "provider_role") insertValues <- c(insertValues, provider_role) } statement <- paste0("INSERT INTO encounter_provider (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_visit <- function(ptid, visitid, visit_type, visit_start_date, visit_start_time, visit_end_date, visit_end_time, discharge_disposition, admission_source, drg) { defaults <- frameworkContext$defaultValues$visit; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(visitid)) { visitid <- defaults$visitid } if (!is.null(visitid)) { insertFields <- c(insertFields, "visitid") insertValues <- c(insertValues, visitid) } if (missing(visit_type)) { visit_type <- defaults$visit_type } if (!is.null(visit_type)) { insertFields <- c(insertFields, "visit_type") insertValues <- c(insertValues, visit_type) } if (missing(visit_start_date)) { visit_start_date <- defaults$visit_start_date } if (!is.null(visit_start_date)) { insertFields <- c(insertFields, "visit_start_date") insertValues <- c(insertValues, visit_start_date) } if (missing(visit_start_time)) { visit_start_time <- defaults$visit_start_time } if (!is.null(visit_start_time)) { insertFields <- c(insertFields, "visit_start_time") insertValues <- c(insertValues, visit_start_time) } if (missing(visit_end_date)) { visit_end_date <- defaults$visit_end_date } if (!is.null(visit_end_date)) { insertFields <- c(insertFields, "visit_end_date") insertValues <- c(insertValues, visit_end_date) } if (missing(visit_end_time)) { visit_end_time <- defaults$visit_end_time } if (!is.null(visit_end_time)) { insertFields <- c(insertFields, "visit_end_time") insertValues <- c(insertValues, visit_end_time) } if (missing(discharge_disposition)) { discharge_disposition <- defaults$discharge_disposition } if (!is.null(discharge_disposition)) { insertFields <- c(insertFields, "discharge_disposition") insertValues <- c(insertValues, discharge_disposition) } if (missing(admission_source)) { admission_source <- defaults$admission_source } if (!is.null(admission_source)) { insertFields <- c(insertFields, "admission_source") insertValues <- c(insertValues, admission_source) } if (missing(drg)) { drg <- defaults$drg } if (!is.null(drg)) { insertFields <- c(insertFields, "drg") insertValues <- c(insertValues, drg) } statement <- paste0("INSERT INTO visit (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_encounter <- function(encid, ptid, visitid, interaction_type, interaction_date, interaction_time) { defaults <- frameworkContext$defaultValues$encounter; insertFields <- c() insertValues <- c() if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(visitid)) { visitid <- defaults$visitid } if (!is.null(visitid)) { insertFields <- c(insertFields, "visitid") insertValues <- c(insertValues, visitid) } if (missing(interaction_type)) { interaction_type <- defaults$interaction_type } if (!is.null(interaction_type)) { insertFields <- c(insertFields, "interaction_type") insertValues <- c(insertValues, interaction_type) } if (missing(interaction_date)) { interaction_date <- defaults$interaction_date } if (!is.null(interaction_date)) { insertFields <- c(insertFields, "interaction_date") insertValues <- c(insertValues, interaction_date) } if (missing(interaction_time)) { interaction_time <- defaults$interaction_time } if (!is.null(interaction_time)) { insertFields <- c(insertFields, "interaction_time") insertValues <- c(insertValues, interaction_time) } statement <- paste0("INSERT INTO encounter (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_diagnosis <- function(ptid, diagnosis_status, diagnosis_cd, diagnosis_cd_type, diag_date, diag_time, encid, primary_diagnosis, admitting_diagnosis, discharge_diagnosis, poa, problem_list) { defaults <- frameworkContext$defaultValues$diagnosis; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(diagnosis_status)) { diagnosis_status <- defaults$diagnosis_status } if (!is.null(diagnosis_status)) { insertFields <- c(insertFields, "diagnosis_status") insertValues <- c(insertValues, diagnosis_status) } if (missing(diagnosis_cd)) { diagnosis_cd <- defaults$diagnosis_cd } if (!is.null(diagnosis_cd)) { insertFields <- c(insertFields, "diagnosis_cd") insertValues <- c(insertValues, diagnosis_cd) } if (missing(diagnosis_cd_type)) { diagnosis_cd_type <- defaults$diagnosis_cd_type } if (!is.null(diagnosis_cd_type)) { insertFields <- c(insertFields, "diagnosis_cd_type") insertValues <- c(insertValues, diagnosis_cd_type) } if (missing(diag_date)) { diag_date <- defaults$diag_date } if (!is.null(diag_date)) { insertFields <- c(insertFields, "diag_date") insertValues <- c(insertValues, diag_date) } if (missing(diag_time)) { diag_time <- defaults$diag_time } if (!is.null(diag_time)) { insertFields <- c(insertFields, "diag_time") insertValues <- c(insertValues, diag_time) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(primary_diagnosis)) { primary_diagnosis <- defaults$primary_diagnosis } if (!is.null(primary_diagnosis)) { insertFields <- c(insertFields, "primary_diagnosis") insertValues <- c(insertValues, primary_diagnosis) } if (missing(admitting_diagnosis)) { admitting_diagnosis <- defaults$admitting_diagnosis } if (!is.null(admitting_diagnosis)) { insertFields <- c(insertFields, "admitting_diagnosis") insertValues <- c(insertValues, admitting_diagnosis) } if (missing(discharge_diagnosis)) { discharge_diagnosis <- defaults$discharge_diagnosis } if (!is.null(discharge_diagnosis)) { insertFields <- c(insertFields, "discharge_diagnosis") insertValues <- c(insertValues, discharge_diagnosis) } if (missing(poa)) { poa <- defaults$poa } if (!is.null(poa)) { insertFields <- c(insertFields, "poa") insertValues <- c(insertValues, poa) } if (missing(problem_list)) { problem_list <- defaults$problem_list } if (!is.null(problem_list)) { insertFields <- c(insertFields, "problem_list") insertValues <- c(insertValues, problem_list) } statement <- paste0("INSERT INTO diagnosis (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_nlp_sds <- function(ptid, encid, note_date, sds_term, sds_location, sds_attribute, sds_sentiment, note_section) { defaults <- frameworkContext$defaultValues$nlp_sds; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(note_date)) { note_date <- defaults$note_date } if (!is.null(note_date)) { insertFields <- c(insertFields, "note_date") insertValues <- c(insertValues, note_date) } if (missing(sds_term)) { sds_term <- defaults$sds_term } if (!is.null(sds_term)) { insertFields <- c(insertFields, "sds_term") insertValues <- c(insertValues, sds_term) } if (missing(sds_location)) { sds_location <- defaults$sds_location } if (!is.null(sds_location)) { insertFields <- c(insertFields, "sds_location") insertValues <- c(insertValues, sds_location) } if (missing(sds_attribute)) { sds_attribute <- defaults$sds_attribute } if (!is.null(sds_attribute)) { insertFields <- c(insertFields, "sds_attribute") insertValues <- c(insertValues, sds_attribute) } if (missing(sds_sentiment)) { sds_sentiment <- defaults$sds_sentiment } if (!is.null(sds_sentiment)) { insertFields <- c(insertFields, "sds_sentiment") insertValues <- c(insertValues, sds_sentiment) } if (missing(note_section)) { note_section <- defaults$note_section } if (!is.null(note_section)) { insertFields <- c(insertFields, "note_section") insertValues <- c(insertValues, note_section) } statement <- paste0("INSERT INTO nlp_sds (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_nlp_sds_family <- function(ptid, encid, note_date, sds_term, sds_location, sds_family_member, sds_sentiment, note_section) { defaults <- frameworkContext$defaultValues$nlp_sds_family; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(note_date)) { note_date <- defaults$note_date } if (!is.null(note_date)) { insertFields <- c(insertFields, "note_date") insertValues <- c(insertValues, note_date) } if (missing(sds_term)) { sds_term <- defaults$sds_term } if (!is.null(sds_term)) { insertFields <- c(insertFields, "sds_term") insertValues <- c(insertValues, sds_term) } if (missing(sds_location)) { sds_location <- defaults$sds_location } if (!is.null(sds_location)) { insertFields <- c(insertFields, "sds_location") insertValues <- c(insertValues, sds_location) } if (missing(sds_family_member)) { sds_family_member <- defaults$sds_family_member } if (!is.null(sds_family_member)) { insertFields <- c(insertFields, "sds_family_member") insertValues <- c(insertValues, sds_family_member) } if (missing(sds_sentiment)) { sds_sentiment <- defaults$sds_sentiment } if (!is.null(sds_sentiment)) { insertFields <- c(insertFields, "sds_sentiment") insertValues <- c(insertValues, sds_sentiment) } if (missing(note_section)) { note_section <- defaults$note_section } if (!is.null(note_section)) { insertFields <- c(insertFields, "note_section") insertValues <- c(insertValues, note_section) } statement <- paste0("INSERT INTO nlp_sds_family (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_procedure <- function(ptid, proc_code, proc_code_type, proc_date, proc_time, provid_perform, encid, proc_desc, provid_order, betos_code, betos_desc) { defaults <- frameworkContext$defaultValues$procedure; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(proc_code)) { proc_code <- defaults$proc_code } if (!is.null(proc_code)) { insertFields <- c(insertFields, "proc_code") insertValues <- c(insertValues, proc_code) } if (missing(proc_code_type)) { proc_code_type <- defaults$proc_code_type } if (!is.null(proc_code_type)) { insertFields <- c(insertFields, "proc_code_type") insertValues <- c(insertValues, proc_code_type) } if (missing(proc_date)) { proc_date <- defaults$proc_date } if (!is.null(proc_date)) { insertFields <- c(insertFields, "proc_date") insertValues <- c(insertValues, proc_date) } if (missing(proc_time)) { proc_time <- defaults$proc_time } if (!is.null(proc_time)) { insertFields <- c(insertFields, "proc_time") insertValues <- c(insertValues, proc_time) } if (missing(provid_perform)) { provid_perform <- defaults$provid_perform } if (!is.null(provid_perform)) { insertFields <- c(insertFields, "provid_perform") insertValues <- c(insertValues, provid_perform) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(proc_desc)) { proc_desc <- defaults$proc_desc } if (!is.null(proc_desc)) { insertFields <- c(insertFields, "proc_desc") insertValues <- c(insertValues, proc_desc) } if (missing(provid_order)) { provid_order <- defaults$provid_order } if (!is.null(provid_order)) { insertFields <- c(insertFields, "provid_order") insertValues <- c(insertValues, provid_order) } if (missing(betos_code)) { betos_code <- defaults$betos_code } if (!is.null(betos_code)) { insertFields <- c(insertFields, "betos_code") insertValues <- c(insertValues, betos_code) } if (missing(betos_desc)) { betos_desc <- defaults$betos_desc } if (!is.null(betos_desc)) { insertFields <- c(insertFields, "betos_desc") insertValues <- c(insertValues, betos_desc) } statement <- paste0("INSERT INTO [procedure] (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_labs <- function(ptid, encid, test_name, order_date, order_time, collected_date, collected_time, result_date, result_time, test_result, relative_indicator, result_unit, normal_range, evaluated_for_range, value_within_range) { defaults <- frameworkContext$defaultValues$labs; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(test_name)) { test_name <- defaults$test_name } if (!is.null(test_name)) { insertFields <- c(insertFields, "test_name") insertValues <- c(insertValues, test_name) } if (missing(order_date)) { order_date <- defaults$order_date } if (!is.null(order_date)) { insertFields <- c(insertFields, "order_date") insertValues <- c(insertValues, order_date) } if (missing(order_time)) { order_time <- defaults$order_time } if (!is.null(order_time)) { insertFields <- c(insertFields, "order_time") insertValues <- c(insertValues, order_time) } if (missing(collected_date)) { collected_date <- defaults$collected_date } if (!is.null(collected_date)) { insertFields <- c(insertFields, "collected_date") insertValues <- c(insertValues, collected_date) } if (missing(collected_time)) { collected_time <- defaults$collected_time } if (!is.null(collected_time)) { insertFields <- c(insertFields, "collected_time") insertValues <- c(insertValues, collected_time) } if (missing(result_date)) { result_date <- defaults$result_date } if (!is.null(result_date)) { insertFields <- c(insertFields, "result_date") insertValues <- c(insertValues, result_date) } if (missing(result_time)) { result_time <- defaults$result_time } if (!is.null(result_time)) { insertFields <- c(insertFields, "result_time") insertValues <- c(insertValues, result_time) } if (missing(test_result)) { test_result <- defaults$test_result } if (!is.null(test_result)) { insertFields <- c(insertFields, "test_result") insertValues <- c(insertValues, test_result) } if (missing(relative_indicator)) { relative_indicator <- defaults$relative_indicator } if (!is.null(relative_indicator)) { insertFields <- c(insertFields, "relative_indicator") insertValues <- c(insertValues, relative_indicator) } if (missing(result_unit)) { result_unit <- defaults$result_unit } if (!is.null(result_unit)) { insertFields <- c(insertFields, "result_unit") insertValues <- c(insertValues, result_unit) } if (missing(normal_range)) { normal_range <- defaults$normal_range } if (!is.null(normal_range)) { insertFields <- c(insertFields, "normal_range") insertValues <- c(insertValues, normal_range) } if (missing(evaluated_for_range)) { evaluated_for_range <- defaults$evaluated_for_range } if (!is.null(evaluated_for_range)) { insertFields <- c(insertFields, "evaluated_for_range") insertValues <- c(insertValues, evaluated_for_range) } if (missing(value_within_range)) { value_within_range <- defaults$value_within_range } if (!is.null(value_within_range)) { insertFields <- c(insertFields, "value_within_range") insertValues <- c(insertValues, value_within_range) } statement <- paste0("INSERT INTO labs (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_observations <- function(ptid, encid, obs_type, obs_date, obs_time, obs_result, obs_unit, evaluated_for_range, value_within_range) { defaults <- frameworkContext$defaultValues$observations; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(obs_type)) { obs_type <- defaults$obs_type } if (!is.null(obs_type)) { insertFields <- c(insertFields, "obs_type") insertValues <- c(insertValues, obs_type) } if (missing(obs_date)) { obs_date <- defaults$obs_date } if (!is.null(obs_date)) { insertFields <- c(insertFields, "obs_date") insertValues <- c(insertValues, obs_date) } if (missing(obs_time)) { obs_time <- defaults$obs_time } if (!is.null(obs_time)) { insertFields <- c(insertFields, "obs_time") insertValues <- c(insertValues, obs_time) } if (missing(obs_result)) { obs_result <- defaults$obs_result } if (!is.null(obs_result)) { insertFields <- c(insertFields, "obs_result") insertValues <- c(insertValues, obs_result) } if (missing(obs_unit)) { obs_unit <- defaults$obs_unit } if (!is.null(obs_unit)) { insertFields <- c(insertFields, "obs_unit") insertValues <- c(insertValues, obs_unit) } if (missing(evaluated_for_range)) { evaluated_for_range <- defaults$evaluated_for_range } if (!is.null(evaluated_for_range)) { insertFields <- c(insertFields, "evaluated_for_range") insertValues <- c(insertValues, evaluated_for_range) } if (missing(value_within_range)) { value_within_range <- defaults$value_within_range } if (!is.null(value_within_range)) { insertFields <- c(insertFields, "value_within_range") insertValues <- c(insertValues, value_within_range) } statement <- paste0("INSERT INTO observations (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_nlp_measurements <- function(ptid, encid, note_date, measurement_type, measurement_value, measurement_detail, note_section, measurement_date) { defaults <- frameworkContext$defaultValues$nlp_measurements; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(note_date)) { note_date <- defaults$note_date } if (!is.null(note_date)) { insertFields <- c(insertFields, "note_date") insertValues <- c(insertValues, note_date) } if (missing(measurement_type)) { measurement_type <- defaults$measurement_type } if (!is.null(measurement_type)) { insertFields <- c(insertFields, "measurement_type") insertValues <- c(insertValues, measurement_type) } if (missing(measurement_value)) { measurement_value <- defaults$measurement_value } if (!is.null(measurement_value)) { insertFields <- c(insertFields, "measurement_value") insertValues <- c(insertValues, measurement_value) } if (missing(measurement_detail)) { measurement_detail <- defaults$measurement_detail } if (!is.null(measurement_detail)) { insertFields <- c(insertFields, "measurement_detail") insertValues <- c(insertValues, measurement_detail) } if (missing(note_section)) { note_section <- defaults$note_section } if (!is.null(note_section)) { insertFields <- c(insertFields, "note_section") insertValues <- c(insertValues, note_section) } if (missing(measurement_date)) { measurement_date <- defaults$measurement_date } if (!is.null(measurement_date)) { insertFields <- c(insertFields, "measurement_date") insertValues <- c(insertValues, measurement_date) } statement <- paste0("INSERT INTO nlp_measurements (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_microbiology <- function(ptid, encid, order_date, order_time, collect_date, collect_time, receive_date, receive_time, result_date, result_time, result_status, specimen_source, organism, mapped_organism_found, mapped_organism_excluded, culture_growth, culture_value, culture_unit, antibiotic, mapped_antibiotic, sensitivity) { defaults <- frameworkContext$defaultValues$microbiology; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(order_date)) { order_date <- defaults$order_date } if (!is.null(order_date)) { insertFields <- c(insertFields, "order_date") insertValues <- c(insertValues, order_date) } if (missing(order_time)) { order_time <- defaults$order_time } if (!is.null(order_time)) { insertFields <- c(insertFields, "order_time") insertValues <- c(insertValues, order_time) } if (missing(collect_date)) { collect_date <- defaults$collect_date } if (!is.null(collect_date)) { insertFields <- c(insertFields, "collect_date") insertValues <- c(insertValues, collect_date) } if (missing(collect_time)) { collect_time <- defaults$collect_time } if (!is.null(collect_time)) { insertFields <- c(insertFields, "collect_time") insertValues <- c(insertValues, collect_time) } if (missing(receive_date)) { receive_date <- defaults$receive_date } if (!is.null(receive_date)) { insertFields <- c(insertFields, "receive_date") insertValues <- c(insertValues, receive_date) } if (missing(receive_time)) { receive_time <- defaults$receive_time } if (!is.null(receive_time)) { insertFields <- c(insertFields, "receive_time") insertValues <- c(insertValues, receive_time) } if (missing(result_date)) { result_date <- defaults$result_date } if (!is.null(result_date)) { insertFields <- c(insertFields, "result_date") insertValues <- c(insertValues, result_date) } if (missing(result_time)) { result_time <- defaults$result_time } if (!is.null(result_time)) { insertFields <- c(insertFields, "result_time") insertValues <- c(insertValues, result_time) } if (missing(result_status)) { result_status <- defaults$result_status } if (!is.null(result_status)) { insertFields <- c(insertFields, "result_status") insertValues <- c(insertValues, result_status) } if (missing(specimen_source)) { specimen_source <- defaults$specimen_source } if (!is.null(specimen_source)) { insertFields <- c(insertFields, "specimen_source") insertValues <- c(insertValues, specimen_source) } if (missing(organism)) { organism <- defaults$organism } if (!is.null(organism)) { insertFields <- c(insertFields, "organism") insertValues <- c(insertValues, organism) } if (missing(mapped_organism_found)) { mapped_organism_found <- defaults$mapped_organism_found } if (!is.null(mapped_organism_found)) { insertFields <- c(insertFields, "mapped_organism_found") insertValues <- c(insertValues, mapped_organism_found) } if (missing(mapped_organism_excluded)) { mapped_organism_excluded <- defaults$mapped_organism_excluded } if (!is.null(mapped_organism_excluded)) { insertFields <- c(insertFields, "mapped_organism_excluded") insertValues <- c(insertValues, mapped_organism_excluded) } if (missing(culture_growth)) { culture_growth <- defaults$culture_growth } if (!is.null(culture_growth)) { insertFields <- c(insertFields, "culture_growth") insertValues <- c(insertValues, culture_growth) } if (missing(culture_value)) { culture_value <- defaults$culture_value } if (!is.null(culture_value)) { insertFields <- c(insertFields, "culture_value") insertValues <- c(insertValues, culture_value) } if (missing(culture_unit)) { culture_unit <- defaults$culture_unit } if (!is.null(culture_unit)) { insertFields <- c(insertFields, "culture_unit") insertValues <- c(insertValues, culture_unit) } if (missing(antibiotic)) { antibiotic <- defaults$antibiotic } if (!is.null(antibiotic)) { insertFields <- c(insertFields, "antibiotic") insertValues <- c(insertValues, antibiotic) } if (missing(mapped_antibiotic)) { mapped_antibiotic <- defaults$mapped_antibiotic } if (!is.null(mapped_antibiotic)) { insertFields <- c(insertFields, "mapped_antibiotic") insertValues <- c(insertValues, mapped_antibiotic) } if (missing(sensitivity)) { sensitivity <- defaults$sensitivity } if (!is.null(sensitivity)) { insertFields <- c(insertFields, "sensitivity") insertValues <- c(insertValues, sensitivity) } statement <- paste0("INSERT INTO microbiology (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_nlp_biomarker <- function(ptid, note_date, biomarker, variation_detail, biomarker_status) { defaults <- frameworkContext$defaultValues$nlp_biomarker; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(note_date)) { note_date <- defaults$note_date } if (!is.null(note_date)) { insertFields <- c(insertFields, "note_date") insertValues <- c(insertValues, note_date) } if (missing(biomarker)) { biomarker <- defaults$biomarker } if (!is.null(biomarker)) { insertFields <- c(insertFields, "biomarker") insertValues <- c(insertValues, biomarker) } if (missing(variation_detail)) { variation_detail <- defaults$variation_detail } if (!is.null(variation_detail)) { insertFields <- c(insertFields, "variation_detail") insertValues <- c(insertValues, variation_detail) } if (missing(biomarker_status)) { biomarker_status <- defaults$biomarker_status } if (!is.null(biomarker_status)) { insertFields <- c(insertFields, "biomarker_status") insertValues <- c(insertValues, biomarker_status) } statement <- paste0("INSERT INTO nlp_biomarker (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_medication_administrations <- function(ptid, encid, drug_name, ndc, ndc_source, order_date, order_time, admin_date, admin_time, provid, quantity_of_dose, route, strength, strength_unit, dosage_form, dosefreq, generic_desc, drug_class) { defaults <- frameworkContext$defaultValues$medication_administrations; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(drug_name)) { drug_name <- defaults$drug_name } if (!is.null(drug_name)) { insertFields <- c(insertFields, "drug_name") insertValues <- c(insertValues, drug_name) } if (missing(ndc)) { ndc <- defaults$ndc } if (!is.null(ndc)) { insertFields <- c(insertFields, "ndc") insertValues <- c(insertValues, ndc) } if (missing(ndc_source)) { ndc_source <- defaults$ndc_source } if (!is.null(ndc_source)) { insertFields <- c(insertFields, "ndc_source") insertValues <- c(insertValues, ndc_source) } if (missing(order_date)) { order_date <- defaults$order_date } if (!is.null(order_date)) { insertFields <- c(insertFields, "order_date") insertValues <- c(insertValues, order_date) } if (missing(order_time)) { order_time <- defaults$order_time } if (!is.null(order_time)) { insertFields <- c(insertFields, "order_time") insertValues <- c(insertValues, order_time) } if (missing(admin_date)) { admin_date <- defaults$admin_date } if (!is.null(admin_date)) { insertFields <- c(insertFields, "admin_date") insertValues <- c(insertValues, admin_date) } if (missing(admin_time)) { admin_time <- defaults$admin_time } if (!is.null(admin_time)) { insertFields <- c(insertFields, "admin_time") insertValues <- c(insertValues, admin_time) } if (missing(provid)) { provid <- defaults$provid } if (!is.null(provid)) { insertFields <- c(insertFields, "provid") insertValues <- c(insertValues, provid) } if (missing(quantity_of_dose)) { quantity_of_dose <- defaults$quantity_of_dose } if (!is.null(quantity_of_dose)) { insertFields <- c(insertFields, "quantity_of_dose") insertValues <- c(insertValues, quantity_of_dose) } if (missing(route)) { route <- defaults$route } if (!is.null(route)) { insertFields <- c(insertFields, "route") insertValues <- c(insertValues, route) } if (missing(strength)) { strength <- defaults$strength } if (!is.null(strength)) { insertFields <- c(insertFields, "strength") insertValues <- c(insertValues, strength) } if (missing(strength_unit)) { strength_unit <- defaults$strength_unit } if (!is.null(strength_unit)) { insertFields <- c(insertFields, "strength_unit") insertValues <- c(insertValues, strength_unit) } if (missing(dosage_form)) { dosage_form <- defaults$dosage_form } if (!is.null(dosage_form)) { insertFields <- c(insertFields, "dosage_form") insertValues <- c(insertValues, dosage_form) } if (missing(dosefreq)) { dosefreq <- defaults$dosefreq } if (!is.null(dosefreq)) { insertFields <- c(insertFields, "dosefreq") insertValues <- c(insertValues, dosefreq) } if (missing(generic_desc)) { generic_desc <- defaults$generic_desc } if (!is.null(generic_desc)) { insertFields <- c(insertFields, "generic_desc") insertValues <- c(insertValues, generic_desc) } if (missing(drug_class)) { drug_class <- defaults$drug_class } if (!is.null(drug_class)) { insertFields <- c(insertFields, "drug_class") insertValues <- c(insertValues, drug_class) } statement <- paste0("INSERT INTO medication_administrations (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_patient_reported_meds <- function(ptid, reported_date, ndc, provid, route, quantity_of_dose, strength, strength_unit, dosage_form, dosefreq, generic_desc, drug_class, drug_name, ndc_source) { defaults <- frameworkContext$defaultValues$patient_reported_meds; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(reported_date)) { reported_date <- defaults$reported_date } if (!is.null(reported_date)) { insertFields <- c(insertFields, "reported_date") insertValues <- c(insertValues, reported_date) } if (missing(ndc)) { ndc <- defaults$ndc } if (!is.null(ndc)) { insertFields <- c(insertFields, "ndc") insertValues <- c(insertValues, ndc) } if (missing(provid)) { provid <- defaults$provid } if (!is.null(provid)) { insertFields <- c(insertFields, "provid") insertValues <- c(insertValues, provid) } if (missing(route)) { route <- defaults$route } if (!is.null(route)) { insertFields <- c(insertFields, "route") insertValues <- c(insertValues, route) } if (missing(quantity_of_dose)) { quantity_of_dose <- defaults$quantity_of_dose } if (!is.null(quantity_of_dose)) { insertFields <- c(insertFields, "quantity_of_dose") insertValues <- c(insertValues, quantity_of_dose) } if (missing(strength)) { strength <- defaults$strength } if (!is.null(strength)) { insertFields <- c(insertFields, "strength") insertValues <- c(insertValues, strength) } if (missing(strength_unit)) { strength_unit <- defaults$strength_unit } if (!is.null(strength_unit)) { insertFields <- c(insertFields, "strength_unit") insertValues <- c(insertValues, strength_unit) } if (missing(dosage_form)) { dosage_form <- defaults$dosage_form } if (!is.null(dosage_form)) { insertFields <- c(insertFields, "dosage_form") insertValues <- c(insertValues, dosage_form) } if (missing(dosefreq)) { dosefreq <- defaults$dosefreq } if (!is.null(dosefreq)) { insertFields <- c(insertFields, "dosefreq") insertValues <- c(insertValues, dosefreq) } if (missing(generic_desc)) { generic_desc <- defaults$generic_desc } if (!is.null(generic_desc)) { insertFields <- c(insertFields, "generic_desc") insertValues <- c(insertValues, generic_desc) } if (missing(drug_class)) { drug_class <- defaults$drug_class } if (!is.null(drug_class)) { insertFields <- c(insertFields, "drug_class") insertValues <- c(insertValues, drug_class) } if (missing(drug_name)) { drug_name <- defaults$drug_name } if (!is.null(drug_name)) { insertFields <- c(insertFields, "drug_name") insertValues <- c(insertValues, drug_name) } if (missing(ndc_source)) { ndc_source <- defaults$ndc_source } if (!is.null(ndc_source)) { insertFields <- c(insertFields, "ndc_source") insertValues <- c(insertValues, ndc_source) } statement <- paste0("INSERT INTO patient_reported_meds (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_prescriptions_written <- function(ptid, rxdate, rxtime, ndc, quantity_per_fill, num_refills, days_supply, provid, route, quantity_of_dose, strength, strength_unit, generic_desc, ndc_source, drug_class, drug_name, dosefreq, dosage_form) { defaults <- frameworkContext$defaultValues$prescriptions_written; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(rxdate)) { rxdate <- defaults$rxdate } if (!is.null(rxdate)) { insertFields <- c(insertFields, "rxdate") insertValues <- c(insertValues, rxdate) } if (missing(rxtime)) { rxtime <- defaults$rxtime } if (!is.null(rxtime)) { insertFields <- c(insertFields, "rxtime") insertValues <- c(insertValues, rxtime) } if (missing(ndc)) { ndc <- defaults$ndc } if (!is.null(ndc)) { insertFields <- c(insertFields, "ndc") insertValues <- c(insertValues, ndc) } if (missing(quantity_per_fill)) { quantity_per_fill <- defaults$quantity_per_fill } if (!is.null(quantity_per_fill)) { insertFields <- c(insertFields, "quantity_per_fill") insertValues <- c(insertValues, quantity_per_fill) } if (missing(num_refills)) { num_refills <- defaults$num_refills } if (!is.null(num_refills)) { insertFields <- c(insertFields, "num_refills") insertValues <- c(insertValues, num_refills) } if (missing(days_supply)) { days_supply <- defaults$days_supply } if (!is.null(days_supply)) { insertFields <- c(insertFields, "days_supply") insertValues <- c(insertValues, days_supply) } if (missing(provid)) { provid <- defaults$provid } if (!is.null(provid)) { insertFields <- c(insertFields, "provid") insertValues <- c(insertValues, provid) } if (missing(route)) { route <- defaults$route } if (!is.null(route)) { insertFields <- c(insertFields, "route") insertValues <- c(insertValues, route) } if (missing(quantity_of_dose)) { quantity_of_dose <- defaults$quantity_of_dose } if (!is.null(quantity_of_dose)) { insertFields <- c(insertFields, "quantity_of_dose") insertValues <- c(insertValues, quantity_of_dose) } if (missing(strength)) { strength <- defaults$strength } if (!is.null(strength)) { insertFields <- c(insertFields, "strength") insertValues <- c(insertValues, strength) } if (missing(strength_unit)) { strength_unit <- defaults$strength_unit } if (!is.null(strength_unit)) { insertFields <- c(insertFields, "strength_unit") insertValues <- c(insertValues, strength_unit) } if (missing(generic_desc)) { generic_desc <- defaults$generic_desc } if (!is.null(generic_desc)) { insertFields <- c(insertFields, "generic_desc") insertValues <- c(insertValues, generic_desc) } if (missing(ndc_source)) { ndc_source <- defaults$ndc_source } if (!is.null(ndc_source)) { insertFields <- c(insertFields, "ndc_source") insertValues <- c(insertValues, ndc_source) } if (missing(drug_class)) { drug_class <- defaults$drug_class } if (!is.null(drug_class)) { insertFields <- c(insertFields, "drug_class") insertValues <- c(insertValues, drug_class) } if (missing(drug_name)) { drug_name <- defaults$drug_name } if (!is.null(drug_name)) { insertFields <- c(insertFields, "drug_name") insertValues <- c(insertValues, drug_name) } if (missing(dosefreq)) { dosefreq <- defaults$dosefreq } if (!is.null(dosefreq)) { insertFields <- c(insertFields, "dosefreq") insertValues <- c(insertValues, dosefreq) } if (missing(dosage_form)) { dosage_form <- defaults$dosage_form } if (!is.null(dosage_form)) { insertFields <- c(insertFields, "dosage_form") insertValues <- c(insertValues, dosage_form) } statement <- paste0("INSERT INTO prescriptions_written (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_nlp_drug_rationale <- function(ptid, encid, note_date, note_section, drug_name, drug_action, drug_action_preposition, reason_general, sentiment, sentiment_who) { defaults <- frameworkContext$defaultValues$nlp_drug_rationale; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(note_date)) { note_date <- defaults$note_date } if (!is.null(note_date)) { insertFields <- c(insertFields, "note_date") insertValues <- c(insertValues, note_date) } if (missing(note_section)) { note_section <- defaults$note_section } if (!is.null(note_section)) { insertFields <- c(insertFields, "note_section") insertValues <- c(insertValues, note_section) } if (missing(drug_name)) { drug_name <- defaults$drug_name } if (!is.null(drug_name)) { insertFields <- c(insertFields, "drug_name") insertValues <- c(insertValues, drug_name) } if (missing(drug_action)) { drug_action <- defaults$drug_action } if (!is.null(drug_action)) { insertFields <- c(insertFields, "drug_action") insertValues <- c(insertValues, drug_action) } if (missing(drug_action_preposition)) { drug_action_preposition <- defaults$drug_action_preposition } if (!is.null(drug_action_preposition)) { insertFields <- c(insertFields, "drug_action_preposition") insertValues <- c(insertValues, drug_action_preposition) } if (missing(reason_general)) { reason_general <- defaults$reason_general } if (!is.null(reason_general)) { insertFields <- c(insertFields, "reason_general") insertValues <- c(insertValues, reason_general) } if (missing(sentiment)) { sentiment <- defaults$sentiment } if (!is.null(sentiment)) { insertFields <- c(insertFields, "sentiment") insertValues <- c(insertValues, sentiment) } if (missing(sentiment_who)) { sentiment_who <- defaults$sentiment_who } if (!is.null(sentiment_who)) { insertFields <- c(insertFields, "sentiment_who") insertValues <- c(insertValues, sentiment_who) } statement <- paste0("INSERT INTO nlp_drug_rationale (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_immunization <- function(ptid, immunization_date, ndc, pt_reported, ndc_source, immunization_desc, mapped_name) { defaults <- frameworkContext$defaultValues$immunization; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(immunization_date)) { immunization_date <- defaults$immunization_date } if (!is.null(immunization_date)) { insertFields <- c(insertFields, "immunization_date") insertValues <- c(insertValues, immunization_date) } if (missing(ndc)) { ndc <- defaults$ndc } if (!is.null(ndc)) { insertFields <- c(insertFields, "ndc") insertValues <- c(insertValues, ndc) } if (missing(pt_reported)) { pt_reported <- defaults$pt_reported } if (!is.null(pt_reported)) { insertFields <- c(insertFields, "pt_reported") insertValues <- c(insertValues, pt_reported) } if (missing(ndc_source)) { ndc_source <- defaults$ndc_source } if (!is.null(ndc_source)) { insertFields <- c(insertFields, "ndc_source") insertValues <- c(insertValues, ndc_source) } if (missing(immunization_desc)) { immunization_desc <- defaults$immunization_desc } if (!is.null(immunization_desc)) { insertFields <- c(insertFields, "immunization_desc") insertValues <- c(insertValues, immunization_desc) } if (missing(mapped_name)) { mapped_name <- defaults$mapped_name } if (!is.null(mapped_name)) { insertFields <- c(insertFields, "mapped_name") insertValues <- c(insertValues, mapped_name) } statement <- paste0("INSERT INTO immunization (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } add_insurance <- function(ptid, encid, insurance_date, insurance_time, ins_type) { defaults <- frameworkContext$defaultValues$insurance; insertFields <- c() insertValues <- c() if (missing(ptid)) { ptid <- defaults$ptid } if (!is.null(ptid)) { insertFields <- c(insertFields, "ptid") insertValues <- c(insertValues, ptid) } if (missing(encid)) { encid <- defaults$encid } if (!is.null(encid)) { insertFields <- c(insertFields, "encid") insertValues <- c(insertValues, encid) } if (missing(insurance_date)) { insurance_date <- defaults$insurance_date } if (!is.null(insurance_date)) { insertFields <- c(insertFields, "insurance_date") insertValues <- c(insertValues, insurance_date) } if (missing(insurance_time)) { insurance_time <- defaults$insurance_time } if (!is.null(insurance_time)) { insertFields <- c(insertFields, "insurance_time") insertValues <- c(insertValues, insurance_time) } if (missing(ins_type)) { ins_type <- defaults$ins_type } if (!is.null(ins_type)) { insertFields <- c(insertFields, "ins_type") insertValues <- c(insertValues, ins_type) } statement <- paste0("INSERT INTO insurance (", paste(insertFields, collapse = ", "), ") VALUES ('", paste(insertValues, collapse = "', '"), "');") frameworkContext$insertSql = c(frameworkContext$insertSql, statement); invisible(statement); } expect_provider <- function(provider_id, provider_name, npi, dea, specialty_concept_id, care_site_id, year_of_birth, gender_concept_id, provider_source_value, specialty_source_value, specialty_source_concept_id, gender_source_value, gender_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect provider' AS test, CASE WHEN(SELECT COUNT(*) FROM provider WHERE") first <- TRUE if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(provider_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_name)) { statement <- paste0(statement, " provider_name IS NULL") } else { statement <- paste0(statement, " provider_name = '", provider_name,"'") } } if (!missing(npi)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(npi)) { statement <- paste0(statement, " npi IS NULL") } else { statement <- paste0(statement, " npi = '", npi,"'") } } if (!missing(dea)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dea)) { statement <- paste0(statement, " dea IS NULL") } else { statement <- paste0(statement, " dea = '", dea,"'") } } if (!missing(specialty_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_concept_id)) { statement <- paste0(statement, " specialty_concept_id IS NULL") } else { statement <- paste0(statement, " specialty_concept_id = '", specialty_concept_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(year_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(year_of_birth)) { statement <- paste0(statement, " year_of_birth IS NULL") } else { statement <- paste0(statement, " year_of_birth = '", year_of_birth,"'") } } if (!missing(gender_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_concept_id)) { statement <- paste0(statement, " gender_concept_id IS NULL") } else { statement <- paste0(statement, " gender_concept_id = '", gender_concept_id,"'") } } if (!missing(provider_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_source_value)) { statement <- paste0(statement, " provider_source_value IS NULL") } else { statement <- paste0(statement, " provider_source_value = '", provider_source_value,"'") } } if (!missing(specialty_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_source_value)) { statement <- paste0(statement, " specialty_source_value IS NULL") } else { statement <- paste0(statement, " specialty_source_value = '", specialty_source_value,"'") } } if (!missing(specialty_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_source_concept_id)) { statement <- paste0(statement, " specialty_source_concept_id IS NULL") } else { statement <- paste0(statement, " specialty_source_concept_id = '", specialty_source_concept_id,"'") } } if (!missing(gender_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_value)) { statement <- paste0(statement, " gender_source_value IS NULL") } else { statement <- paste0(statement, " gender_source_value = '", gender_source_value,"'") } } if (!missing(gender_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_concept_id)) { statement <- paste0(statement, " gender_source_concept_id IS NULL") } else { statement <- paste0(statement, " gender_source_concept_id = '", gender_source_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_care_site <- function(care_site_id, care_site_name, place_of_service_concept_id, location_id, care_site_source_value, place_of_service_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect care_site' AS test, CASE WHEN(SELECT COUNT(*) FROM care_site WHERE") first <- TRUE if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(care_site_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_name)) { statement <- paste0(statement, " care_site_name IS NULL") } else { statement <- paste0(statement, " care_site_name = '", care_site_name,"'") } } if (!missing(place_of_service_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(place_of_service_concept_id)) { statement <- paste0(statement, " place_of_service_concept_id IS NULL") } else { statement <- paste0(statement, " place_of_service_concept_id = '", place_of_service_concept_id,"'") } } if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(care_site_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_source_value)) { statement <- paste0(statement, " care_site_source_value IS NULL") } else { statement <- paste0(statement, " care_site_source_value = '", care_site_source_value,"'") } } if (!missing(place_of_service_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(place_of_service_source_value)) { statement <- paste0(statement, " place_of_service_source_value IS NULL") } else { statement <- paste0(statement, " place_of_service_source_value = '", place_of_service_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_location <- function(location_id, address_1, address_2, city, state, zip, county, location_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect location' AS test, CASE WHEN(SELECT COUNT(*) FROM location WHERE") first <- TRUE if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(address_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(address_1)) { statement <- paste0(statement, " address_1 IS NULL") } else { statement <- paste0(statement, " address_1 = '", address_1,"'") } } if (!missing(address_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(address_2)) { statement <- paste0(statement, " address_2 IS NULL") } else { statement <- paste0(statement, " address_2 = '", address_2,"'") } } if (!missing(city)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(city)) { statement <- paste0(statement, " city IS NULL") } else { statement <- paste0(statement, " city = '", city,"'") } } if (!missing(state)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(state)) { statement <- paste0(statement, " state IS NULL") } else { statement <- paste0(statement, " state = '", state,"'") } } if (!missing(zip)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(zip)) { statement <- paste0(statement, " zip IS NULL") } else { statement <- paste0(statement, " zip = '", zip,"'") } } if (!missing(county)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(county)) { statement <- paste0(statement, " county IS NULL") } else { statement <- paste0(statement, " county = '", county,"'") } } if (!missing(location_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_source_value)) { statement <- paste0(statement, " location_source_value IS NULL") } else { statement <- paste0(statement, " location_source_value = '", location_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_person <- function(person_id, gender_concept_id, year_of_birth, month_of_birth, day_of_birth, time_of_birth, race_concept_id, ethnicity_concept_id, location_id, provider_id, care_site_id, person_source_value, gender_source_value, gender_source_concept_id, race_source_value, race_source_concept_id, ethnicity_source_value, ethnicity_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect person' AS test, CASE WHEN(SELECT COUNT(*) FROM person WHERE") first <- TRUE if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(gender_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_concept_id)) { statement <- paste0(statement, " gender_concept_id IS NULL") } else { statement <- paste0(statement, " gender_concept_id = '", gender_concept_id,"'") } } if (!missing(year_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(year_of_birth)) { statement <- paste0(statement, " year_of_birth IS NULL") } else { statement <- paste0(statement, " year_of_birth = '", year_of_birth,"'") } } if (!missing(month_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(month_of_birth)) { statement <- paste0(statement, " month_of_birth IS NULL") } else { statement <- paste0(statement, " month_of_birth = '", month_of_birth,"'") } } if (!missing(day_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(day_of_birth)) { statement <- paste0(statement, " day_of_birth IS NULL") } else { statement <- paste0(statement, " day_of_birth = '", day_of_birth,"'") } } if (!missing(time_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(time_of_birth)) { statement <- paste0(statement, " time_of_birth IS NULL") } else { statement <- paste0(statement, " time_of_birth = '", time_of_birth,"'") } } if (!missing(race_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_concept_id)) { statement <- paste0(statement, " race_concept_id IS NULL") } else { statement <- paste0(statement, " race_concept_id = '", race_concept_id,"'") } } if (!missing(ethnicity_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_concept_id)) { statement <- paste0(statement, " ethnicity_concept_id IS NULL") } else { statement <- paste0(statement, " ethnicity_concept_id = '", ethnicity_concept_id,"'") } } if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(person_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_source_value)) { statement <- paste0(statement, " person_source_value IS NULL") } else { statement <- paste0(statement, " person_source_value = '", person_source_value,"'") } } if (!missing(gender_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_value)) { statement <- paste0(statement, " gender_source_value IS NULL") } else { statement <- paste0(statement, " gender_source_value = '", gender_source_value,"'") } } if (!missing(gender_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_concept_id)) { statement <- paste0(statement, " gender_source_concept_id IS NULL") } else { statement <- paste0(statement, " gender_source_concept_id = '", gender_source_concept_id,"'") } } if (!missing(race_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_source_value)) { statement <- paste0(statement, " race_source_value IS NULL") } else { statement <- paste0(statement, " race_source_value = '", race_source_value,"'") } } if (!missing(race_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_source_concept_id)) { statement <- paste0(statement, " race_source_concept_id IS NULL") } else { statement <- paste0(statement, " race_source_concept_id = '", race_source_concept_id,"'") } } if (!missing(ethnicity_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_source_value)) { statement <- paste0(statement, " ethnicity_source_value IS NULL") } else { statement <- paste0(statement, " ethnicity_source_value = '", ethnicity_source_value,"'") } } if (!missing(ethnicity_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_source_concept_id)) { statement <- paste0(statement, " ethnicity_source_concept_id IS NULL") } else { statement <- paste0(statement, " ethnicity_source_concept_id = '", ethnicity_source_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_observation_period <- function(observation_period_id, person_id, observation_period_start_date, observation_period_end_date, period_type_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect observation_period' AS test, CASE WHEN(SELECT COUNT(*) FROM observation_period WHERE") first <- TRUE if (!missing(observation_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_id)) { statement <- paste0(statement, " observation_period_id IS NULL") } else { statement <- paste0(statement, " observation_period_id = '", observation_period_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(observation_period_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_start_date)) { statement <- paste0(statement, " observation_period_start_date IS NULL") } else { statement <- paste0(statement, " observation_period_start_date = '", observation_period_start_date,"'") } } if (!missing(observation_period_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_end_date)) { statement <- paste0(statement, " observation_period_end_date IS NULL") } else { statement <- paste0(statement, " observation_period_end_date = '", observation_period_end_date,"'") } } if (!missing(period_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(period_type_concept_id)) { statement <- paste0(statement, " period_type_concept_id IS NULL") } else { statement <- paste0(statement, " period_type_concept_id = '", period_type_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_death <- function(person_id, death_date, death_type_concept_id, cause_concept_id, cause_source_value, cause_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect death' AS test, CASE WHEN(SELECT COUNT(*) FROM death WHERE") first <- TRUE if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(death_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(death_date)) { statement <- paste0(statement, " death_date IS NULL") } else { statement <- paste0(statement, " death_date = '", death_date,"'") } } if (!missing(death_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(death_type_concept_id)) { statement <- paste0(statement, " death_type_concept_id IS NULL") } else { statement <- paste0(statement, " death_type_concept_id = '", death_type_concept_id,"'") } } if (!missing(cause_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_concept_id)) { statement <- paste0(statement, " cause_concept_id IS NULL") } else { statement <- paste0(statement, " cause_concept_id = '", cause_concept_id,"'") } } if (!missing(cause_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_source_value)) { statement <- paste0(statement, " cause_source_value IS NULL") } else { statement <- paste0(statement, " cause_source_value = '", cause_source_value,"'") } } if (!missing(cause_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_source_concept_id)) { statement <- paste0(statement, " cause_source_concept_id IS NULL") } else { statement <- paste0(statement, " cause_source_concept_id = '", cause_source_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_visit_occurrence <- function(visit_occurrence_id, person_id, visit_concept_id, visit_start_date, visit_start_time, visit_end_date, visit_end_time, visit_type_concept_id, provider_id, care_site_id, visit_source_value, visit_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect visit_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM visit_occurrence WHERE") first <- TRUE if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(visit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_concept_id)) { statement <- paste0(statement, " visit_concept_id IS NULL") } else { statement <- paste0(statement, " visit_concept_id = '", visit_concept_id,"'") } } if (!missing(visit_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_start_date)) { statement <- paste0(statement, " visit_start_date IS NULL") } else { statement <- paste0(statement, " visit_start_date = '", visit_start_date,"'") } } if (!missing(visit_start_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_start_time)) { statement <- paste0(statement, " visit_start_time IS NULL") } else { statement <- paste0(statement, " visit_start_time = '", visit_start_time,"'") } } if (!missing(visit_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_end_date)) { statement <- paste0(statement, " visit_end_date IS NULL") } else { statement <- paste0(statement, " visit_end_date = '", visit_end_date,"'") } } if (!missing(visit_end_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_end_time)) { statement <- paste0(statement, " visit_end_time IS NULL") } else { statement <- paste0(statement, " visit_end_time = '", visit_end_time,"'") } } if (!missing(visit_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_type_concept_id)) { statement <- paste0(statement, " visit_type_concept_id IS NULL") } else { statement <- paste0(statement, " visit_type_concept_id = '", visit_type_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(visit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_source_value)) { statement <- paste0(statement, " visit_source_value IS NULL") } else { statement <- paste0(statement, " visit_source_value = '", visit_source_value,"'") } } if (!missing(visit_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_source_concept_id)) { statement <- paste0(statement, " visit_source_concept_id IS NULL") } else { statement <- paste0(statement, " visit_source_concept_id = '", visit_source_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_condition_occurrence <- function(condition_occurrence_id, person_id, condition_concept_id, condition_source_concept_id, condition_source_value, condition_start_date, provider_id, visit_occurrence_id, condition_type_concept_id, condition_end_date, stop_reason) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect condition_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM condition_occurrence WHERE") first <- TRUE if (!missing(condition_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_occurrence_id)) { statement <- paste0(statement, " condition_occurrence_id IS NULL") } else { statement <- paste0(statement, " condition_occurrence_id = '", condition_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(condition_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_concept_id)) { statement <- paste0(statement, " condition_concept_id IS NULL") } else { statement <- paste0(statement, " condition_concept_id = '", condition_concept_id,"'") } } if (!missing(condition_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_source_concept_id)) { statement <- paste0(statement, " condition_source_concept_id IS NULL") } else { statement <- paste0(statement, " condition_source_concept_id = '", condition_source_concept_id,"'") } } if (!missing(condition_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_source_value)) { statement <- paste0(statement, " condition_source_value IS NULL") } else { statement <- paste0(statement, " condition_source_value = '", condition_source_value,"'") } } if (!missing(condition_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_start_date)) { statement <- paste0(statement, " condition_start_date IS NULL") } else { statement <- paste0(statement, " condition_start_date = '", condition_start_date,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(condition_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_type_concept_id)) { statement <- paste0(statement, " condition_type_concept_id IS NULL") } else { statement <- paste0(statement, " condition_type_concept_id = '", condition_type_concept_id,"'") } } if (!missing(condition_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_end_date)) { statement <- paste0(statement, " condition_end_date IS NULL") } else { statement <- paste0(statement, " condition_end_date = '", condition_end_date,"'") } } if (!missing(stop_reason)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(stop_reason)) { statement <- paste0(statement, " stop_reason IS NULL") } else { statement <- paste0(statement, " stop_reason = '", stop_reason,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_device_exposure <- function(device_exposure_id, person_id, device_concept_id, device_exposure_start_date, device_exposure_end_date, device_type_concept_id, unique_device_id, quantity, provider_id, visit_occurrence_id, device_source_value, device_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect device_exposure' AS test, CASE WHEN(SELECT COUNT(*) FROM device_exposure WHERE") first <- TRUE if (!missing(device_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_id)) { statement <- paste0(statement, " device_exposure_id IS NULL") } else { statement <- paste0(statement, " device_exposure_id = '", device_exposure_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(device_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_concept_id)) { statement <- paste0(statement, " device_concept_id IS NULL") } else { statement <- paste0(statement, " device_concept_id = '", device_concept_id,"'") } } if (!missing(device_exposure_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_start_date)) { statement <- paste0(statement, " device_exposure_start_date IS NULL") } else { statement <- paste0(statement, " device_exposure_start_date = '", device_exposure_start_date,"'") } } if (!missing(device_exposure_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_end_date)) { statement <- paste0(statement, " device_exposure_end_date IS NULL") } else { statement <- paste0(statement, " device_exposure_end_date = '", device_exposure_end_date,"'") } } if (!missing(device_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_type_concept_id)) { statement <- paste0(statement, " device_type_concept_id IS NULL") } else { statement <- paste0(statement, " device_type_concept_id = '", device_type_concept_id,"'") } } if (!missing(unique_device_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unique_device_id)) { statement <- paste0(statement, " unique_device_id IS NULL") } else { statement <- paste0(statement, " unique_device_id = '", unique_device_id,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(device_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_source_value)) { statement <- paste0(statement, " device_source_value IS NULL") } else { statement <- paste0(statement, " device_source_value = '", device_source_value,"'") } } if (!missing(device_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_source_concept_id)) { statement <- paste0(statement, " device_source_concept_id IS NULL") } else { statement <- paste0(statement, " device_source_concept_id = '", device_source_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_observation <- function(observation_id, person_id, observation_concept_id, observation_date, observation_time, observation_type_concept_id, value_as_number, value_as_string, value_as_concept_id, qualifier_concept_id, unit_concept_id, provider_id, visit_occurrence_id, observation_source_value, observation_source_concept_id, unit_source_value, qualifier_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect observation' AS test, CASE WHEN(SELECT COUNT(*) FROM observation WHERE") first <- TRUE if (!missing(observation_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_id)) { statement <- paste0(statement, " observation_id IS NULL") } else { statement <- paste0(statement, " observation_id = '", observation_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(observation_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_concept_id)) { statement <- paste0(statement, " observation_concept_id IS NULL") } else { statement <- paste0(statement, " observation_concept_id = '", observation_concept_id,"'") } } if (!missing(observation_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_date)) { statement <- paste0(statement, " observation_date IS NULL") } else { statement <- paste0(statement, " observation_date = '", observation_date,"'") } } if (!missing(observation_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_time)) { statement <- paste0(statement, " observation_time IS NULL") } else { statement <- paste0(statement, " observation_time = '", observation_time,"'") } } if (!missing(observation_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_type_concept_id)) { statement <- paste0(statement, " observation_type_concept_id IS NULL") } else { statement <- paste0(statement, " observation_type_concept_id = '", observation_type_concept_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_string)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_string)) { statement <- paste0(statement, " value_as_string IS NULL") } else { statement <- paste0(statement, " value_as_string = '", value_as_string,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } if (!missing(qualifier_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_concept_id)) { statement <- paste0(statement, " qualifier_concept_id IS NULL") } else { statement <- paste0(statement, " qualifier_concept_id = '", qualifier_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(observation_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_source_value)) { statement <- paste0(statement, " observation_source_value IS NULL") } else { statement <- paste0(statement, " observation_source_value = '", observation_source_value,"'") } } if (!missing(observation_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_source_concept_id)) { statement <- paste0(statement, " observation_source_concept_id IS NULL") } else { statement <- paste0(statement, " observation_source_concept_id = '", observation_source_concept_id,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(qualifier_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_source_value)) { statement <- paste0(statement, " qualifier_source_value IS NULL") } else { statement <- paste0(statement, " qualifier_source_value = '", qualifier_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_measurement <- function(measurement_id, person_id, measurement_concept_id, measurement_date, measurement_time, measurement_type_concept_id, operator_concept_id, value_as_number, value_as_concept_id, unit_concept_id, range_low, range_high, provider_id, visit_occurrence_id, measurement_source_value, measurement_source_concept_id, unit_source_value, value_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect measurement' AS test, CASE WHEN(SELECT COUNT(*) FROM measurement WHERE") first <- TRUE if (!missing(measurement_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_id)) { statement <- paste0(statement, " measurement_id IS NULL") } else { statement <- paste0(statement, " measurement_id = '", measurement_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(measurement_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_concept_id)) { statement <- paste0(statement, " measurement_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_concept_id = '", measurement_concept_id,"'") } } if (!missing(measurement_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_date)) { statement <- paste0(statement, " measurement_date IS NULL") } else { statement <- paste0(statement, " measurement_date = '", measurement_date,"'") } } if (!missing(measurement_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_time)) { statement <- paste0(statement, " measurement_time IS NULL") } else { statement <- paste0(statement, " measurement_time = '", measurement_time,"'") } } if (!missing(measurement_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_type_concept_id)) { statement <- paste0(statement, " measurement_type_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_type_concept_id = '", measurement_type_concept_id,"'") } } if (!missing(operator_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(operator_concept_id)) { statement <- paste0(statement, " operator_concept_id IS NULL") } else { statement <- paste0(statement, " operator_concept_id = '", operator_concept_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(range_low)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(range_low)) { statement <- paste0(statement, " range_low IS NULL") } else { statement <- paste0(statement, " range_low = '", range_low,"'") } } if (!missing(range_high)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(range_high)) { statement <- paste0(statement, " range_high IS NULL") } else { statement <- paste0(statement, " range_high = '", range_high,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(measurement_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_source_value)) { statement <- paste0(statement, " measurement_source_value IS NULL") } else { statement <- paste0(statement, " measurement_source_value = '", measurement_source_value,"'") } } if (!missing(measurement_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_source_concept_id)) { statement <- paste0(statement, " measurement_source_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_source_concept_id = '", measurement_source_concept_id,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(value_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_source_value)) { statement <- paste0(statement, " value_source_value IS NULL") } else { statement <- paste0(statement, " value_source_value = '", value_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_procedure_occurrence <- function(procedure_occurrence_id, person_id, procedure_concept_id, procedure_date, procedure_type_concept_id, modifier_concept_id, quantity, provider_id, visit_occurrence_id, procedure_source_value, procedure_source_concept_id, qualifier_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect procedure_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM procedure_occurrence WHERE") first <- TRUE if (!missing(procedure_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_occurrence_id)) { statement <- paste0(statement, " procedure_occurrence_id IS NULL") } else { statement <- paste0(statement, " procedure_occurrence_id = '", procedure_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(procedure_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_concept_id)) { statement <- paste0(statement, " procedure_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_concept_id = '", procedure_concept_id,"'") } } if (!missing(procedure_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_date)) { statement <- paste0(statement, " procedure_date IS NULL") } else { statement <- paste0(statement, " procedure_date = '", procedure_date,"'") } } if (!missing(procedure_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_type_concept_id)) { statement <- paste0(statement, " procedure_type_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_type_concept_id = '", procedure_type_concept_id,"'") } } if (!missing(modifier_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(modifier_concept_id)) { statement <- paste0(statement, " modifier_concept_id IS NULL") } else { statement <- paste0(statement, " modifier_concept_id = '", modifier_concept_id,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(procedure_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_source_value)) { statement <- paste0(statement, " procedure_source_value IS NULL") } else { statement <- paste0(statement, " procedure_source_value = '", procedure_source_value,"'") } } if (!missing(procedure_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_source_concept_id)) { statement <- paste0(statement, " procedure_source_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_source_concept_id = '", procedure_source_concept_id,"'") } } if (!missing(qualifier_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_source_value)) { statement <- paste0(statement, " qualifier_source_value IS NULL") } else { statement <- paste0(statement, " qualifier_source_value = '", qualifier_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_drug_exposure <- function(drug_exposure_id, person_id, drug_exposure_start_date, drug_concept_id, drug_source_value, drug_source_concept_id, drug_type_concept_id, provider_id, visit_occurrence_id, route_concept_id, route_source_value, quantity, refills, days_supply, dose_unit_concept_id, dose_unit_source_value, effective_drug_dose, stop_reason, sig, lot_number, drug_exposure_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_exposure' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_exposure WHERE") first <- TRUE if (!missing(drug_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_id)) { statement <- paste0(statement, " drug_exposure_id IS NULL") } else { statement <- paste0(statement, " drug_exposure_id = '", drug_exposure_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_exposure_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_start_date)) { statement <- paste0(statement, " drug_exposure_start_date IS NULL") } else { statement <- paste0(statement, " drug_exposure_start_date = '", drug_exposure_start_date,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(drug_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_source_value)) { statement <- paste0(statement, " drug_source_value IS NULL") } else { statement <- paste0(statement, " drug_source_value = '", drug_source_value,"'") } } if (!missing(drug_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_source_concept_id)) { statement <- paste0(statement, " drug_source_concept_id IS NULL") } else { statement <- paste0(statement, " drug_source_concept_id = '", drug_source_concept_id,"'") } } if (!missing(drug_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_type_concept_id)) { statement <- paste0(statement, " drug_type_concept_id IS NULL") } else { statement <- paste0(statement, " drug_type_concept_id = '", drug_type_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(route_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(route_concept_id)) { statement <- paste0(statement, " route_concept_id IS NULL") } else { statement <- paste0(statement, " route_concept_id = '", route_concept_id,"'") } } if (!missing(route_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(route_source_value)) { statement <- paste0(statement, " route_source_value IS NULL") } else { statement <- paste0(statement, " route_source_value = '", route_source_value,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(refills)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(refills)) { statement <- paste0(statement, " refills IS NULL") } else { statement <- paste0(statement, " refills = '", refills,"'") } } if (!missing(days_supply)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(days_supply)) { statement <- paste0(statement, " days_supply IS NULL") } else { statement <- paste0(statement, " days_supply = '", days_supply,"'") } } if (!missing(dose_unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_unit_concept_id)) { statement <- paste0(statement, " dose_unit_concept_id IS NULL") } else { statement <- paste0(statement, " dose_unit_concept_id = '", dose_unit_concept_id,"'") } } if (!missing(dose_unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_unit_source_value)) { statement <- paste0(statement, " dose_unit_source_value IS NULL") } else { statement <- paste0(statement, " dose_unit_source_value = '", dose_unit_source_value,"'") } } if (!missing(effective_drug_dose)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(effective_drug_dose)) { statement <- paste0(statement, " effective_drug_dose IS NULL") } else { statement <- paste0(statement, " effective_drug_dose = '", effective_drug_dose,"'") } } if (!missing(stop_reason)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(stop_reason)) { statement <- paste0(statement, " stop_reason IS NULL") } else { statement <- paste0(statement, " stop_reason = '", stop_reason,"'") } } if (!missing(sig)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(sig)) { statement <- paste0(statement, " sig IS NULL") } else { statement <- paste0(statement, " sig = '", sig,"'") } } if (!missing(lot_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(lot_number)) { statement <- paste0(statement, " lot_number IS NULL") } else { statement <- paste0(statement, " lot_number = '", lot_number,"'") } } if (!missing(drug_exposure_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_end_date)) { statement <- paste0(statement, " drug_exposure_end_date IS NULL") } else { statement <- paste0(statement, " drug_exposure_end_date = '", drug_exposure_end_date,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_fact_relationship <- function(domain_concept_id_1, fact_id_1, domain_concept_id_2, fact_id_2, relationship_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect fact_relationship' AS test, CASE WHEN(SELECT COUNT(*) FROM fact_relationship WHERE") first <- TRUE if (!missing(domain_concept_id_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(domain_concept_id_1)) { statement <- paste0(statement, " domain_concept_id_1 IS NULL") } else { statement <- paste0(statement, " domain_concept_id_1 = '", domain_concept_id_1,"'") } } if (!missing(fact_id_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(fact_id_1)) { statement <- paste0(statement, " fact_id_1 IS NULL") } else { statement <- paste0(statement, " fact_id_1 = '", fact_id_1,"'") } } if (!missing(domain_concept_id_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(domain_concept_id_2)) { statement <- paste0(statement, " domain_concept_id_2 IS NULL") } else { statement <- paste0(statement, " domain_concept_id_2 = '", domain_concept_id_2,"'") } } if (!missing(fact_id_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(fact_id_2)) { statement <- paste0(statement, " fact_id_2 IS NULL") } else { statement <- paste0(statement, " fact_id_2 = '", fact_id_2,"'") } } if (!missing(relationship_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(relationship_concept_id)) { statement <- paste0(statement, " relationship_concept_id IS NULL") } else { statement <- paste0(statement, " relationship_concept_id = '", relationship_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_payer_plan_period <- function(payer_plan_period_id, person_id, payer_plan_period_start_date, payer_plan_period_end_date, payer_source_value, plan_source_value, family_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect payer_plan_period' AS test, CASE WHEN(SELECT COUNT(*) FROM payer_plan_period WHERE") first <- TRUE if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(payer_plan_period_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_start_date)) { statement <- paste0(statement, " payer_plan_period_start_date IS NULL") } else { statement <- paste0(statement, " payer_plan_period_start_date = '", payer_plan_period_start_date,"'") } } if (!missing(payer_plan_period_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_end_date)) { statement <- paste0(statement, " payer_plan_period_end_date IS NULL") } else { statement <- paste0(statement, " payer_plan_period_end_date = '", payer_plan_period_end_date,"'") } } if (!missing(payer_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_source_value)) { statement <- paste0(statement, " payer_source_value IS NULL") } else { statement <- paste0(statement, " payer_source_value = '", payer_source_value,"'") } } if (!missing(plan_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(plan_source_value)) { statement <- paste0(statement, " plan_source_value IS NULL") } else { statement <- paste0(statement, " plan_source_value = '", plan_source_value,"'") } } if (!missing(family_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(family_source_value)) { statement <- paste0(statement, " family_source_value IS NULL") } else { statement <- paste0(statement, " family_source_value = '", family_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_note <- function(note_id, person_id, note_date, note_time, note_type_concept_id, note_text, provider_id, visit_occurrence_id, note_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect note' AS test, CASE WHEN(SELECT COUNT(*) FROM note WHERE") first <- TRUE if (!missing(note_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_id)) { statement <- paste0(statement, " note_id IS NULL") } else { statement <- paste0(statement, " note_id = '", note_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(note_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_date)) { statement <- paste0(statement, " note_date IS NULL") } else { statement <- paste0(statement, " note_date = '", note_date,"'") } } if (!missing(note_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_time)) { statement <- paste0(statement, " note_time IS NULL") } else { statement <- paste0(statement, " note_time = '", note_time,"'") } } if (!missing(note_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_type_concept_id)) { statement <- paste0(statement, " note_type_concept_id IS NULL") } else { statement <- paste0(statement, " note_type_concept_id = '", note_type_concept_id,"'") } } if (!missing(note_text)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_text)) { statement <- paste0(statement, " note_text IS NULL") } else { statement <- paste0(statement, " note_text = '", note_text,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(note_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_source_value)) { statement <- paste0(statement, " note_source_value IS NULL") } else { statement <- paste0(statement, " note_source_value = '", note_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_specimen <- function(specimen_id, person_id, specimen_concept_id, specimen_type_concept_id, specimen_date, specimen_time, quantity, unit_concept_id, anatomic_site_concept_id, disease_status_concept_id, specimen_source_id, specimen_source_value, unit_source_value, anatomic_site_source_value, disease_status_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect specimen' AS test, CASE WHEN(SELECT COUNT(*) FROM specimen WHERE") first <- TRUE if (!missing(specimen_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_id)) { statement <- paste0(statement, " specimen_id IS NULL") } else { statement <- paste0(statement, " specimen_id = '", specimen_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(specimen_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_concept_id)) { statement <- paste0(statement, " specimen_concept_id IS NULL") } else { statement <- paste0(statement, " specimen_concept_id = '", specimen_concept_id,"'") } } if (!missing(specimen_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_type_concept_id)) { statement <- paste0(statement, " specimen_type_concept_id IS NULL") } else { statement <- paste0(statement, " specimen_type_concept_id = '", specimen_type_concept_id,"'") } } if (!missing(specimen_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_date)) { statement <- paste0(statement, " specimen_date IS NULL") } else { statement <- paste0(statement, " specimen_date = '", specimen_date,"'") } } if (!missing(specimen_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_time)) { statement <- paste0(statement, " specimen_time IS NULL") } else { statement <- paste0(statement, " specimen_time = '", specimen_time,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(anatomic_site_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(anatomic_site_concept_id)) { statement <- paste0(statement, " anatomic_site_concept_id IS NULL") } else { statement <- paste0(statement, " anatomic_site_concept_id = '", anatomic_site_concept_id,"'") } } if (!missing(disease_status_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(disease_status_concept_id)) { statement <- paste0(statement, " disease_status_concept_id IS NULL") } else { statement <- paste0(statement, " disease_status_concept_id = '", disease_status_concept_id,"'") } } if (!missing(specimen_source_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_source_id)) { statement <- paste0(statement, " specimen_source_id IS NULL") } else { statement <- paste0(statement, " specimen_source_id = '", specimen_source_id,"'") } } if (!missing(specimen_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_source_value)) { statement <- paste0(statement, " specimen_source_value IS NULL") } else { statement <- paste0(statement, " specimen_source_value = '", specimen_source_value,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(anatomic_site_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(anatomic_site_source_value)) { statement <- paste0(statement, " anatomic_site_source_value IS NULL") } else { statement <- paste0(statement, " anatomic_site_source_value = '", anatomic_site_source_value,"'") } } if (!missing(disease_status_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(disease_status_source_value)) { statement <- paste0(statement, " disease_status_source_value IS NULL") } else { statement <- paste0(statement, " disease_status_source_value = '", disease_status_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_procedure_cost <- function(procedure_cost_id, procedure_occurrence_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, revenue_code_concept_id, payer_plan_period_id, revenue_code_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect procedure_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM procedure_cost WHERE") first <- TRUE if (!missing(procedure_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_cost_id)) { statement <- paste0(statement, " procedure_cost_id IS NULL") } else { statement <- paste0(statement, " procedure_cost_id = '", procedure_cost_id,"'") } } if (!missing(procedure_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_occurrence_id)) { statement <- paste0(statement, " procedure_occurrence_id IS NULL") } else { statement <- paste0(statement, " procedure_occurrence_id = '", procedure_occurrence_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(revenue_code_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(revenue_code_concept_id)) { statement <- paste0(statement, " revenue_code_concept_id IS NULL") } else { statement <- paste0(statement, " revenue_code_concept_id = '", revenue_code_concept_id,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } if (!missing(revenue_code_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(revenue_code_source_value)) { statement <- paste0(statement, " revenue_code_source_value IS NULL") } else { statement <- paste0(statement, " revenue_code_source_value = '", revenue_code_source_value,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_visit_cost <- function(visit_cost_id, visit_occurrence_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect visit_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM visit_cost WHERE") first <- TRUE if (!missing(visit_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_cost_id)) { statement <- paste0(statement, " visit_cost_id IS NULL") } else { statement <- paste0(statement, " visit_cost_id = '", visit_cost_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_drug_cost <- function(drug_cost_id, drug_exposure_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, ingredient_cost, dispensing_fee, average_wholesale_price, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_cost WHERE") first <- TRUE if (!missing(drug_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_cost_id)) { statement <- paste0(statement, " drug_cost_id IS NULL") } else { statement <- paste0(statement, " drug_cost_id = '", drug_cost_id,"'") } } if (!missing(drug_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_id)) { statement <- paste0(statement, " drug_exposure_id IS NULL") } else { statement <- paste0(statement, " drug_exposure_id = '", drug_exposure_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(ingredient_cost)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ingredient_cost)) { statement <- paste0(statement, " ingredient_cost IS NULL") } else { statement <- paste0(statement, " ingredient_cost = '", ingredient_cost,"'") } } if (!missing(dispensing_fee)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dispensing_fee)) { statement <- paste0(statement, " dispensing_fee IS NULL") } else { statement <- paste0(statement, " dispensing_fee = '", dispensing_fee,"'") } } if (!missing(average_wholesale_price)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(average_wholesale_price)) { statement <- paste0(statement, " average_wholesale_price IS NULL") } else { statement <- paste0(statement, " average_wholesale_price = '", average_wholesale_price,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_device_cost <- function(device_cost_id, device_exposure_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect device_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM device_cost WHERE") first <- TRUE if (!missing(device_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_cost_id)) { statement <- paste0(statement, " device_cost_id IS NULL") } else { statement <- paste0(statement, " device_cost_id = '", device_cost_id,"'") } } if (!missing(device_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_id)) { statement <- paste0(statement, " device_exposure_id IS NULL") } else { statement <- paste0(statement, " device_exposure_id = '", device_exposure_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_drug_era <- function(drug_era_id, person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, drug_exposure_count, gap_days) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_era' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_era WHERE") first <- TRUE if (!missing(drug_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_id)) { statement <- paste0(statement, " drug_era_id IS NULL") } else { statement <- paste0(statement, " drug_era_id = '", drug_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(drug_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_start_date)) { statement <- paste0(statement, " drug_era_start_date IS NULL") } else { statement <- paste0(statement, " drug_era_start_date = '", drug_era_start_date,"'") } } if (!missing(drug_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_end_date)) { statement <- paste0(statement, " drug_era_end_date IS NULL") } else { statement <- paste0(statement, " drug_era_end_date = '", drug_era_end_date,"'") } } if (!missing(drug_exposure_count)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_count)) { statement <- paste0(statement, " drug_exposure_count IS NULL") } else { statement <- paste0(statement, " drug_exposure_count = '", drug_exposure_count,"'") } } if (!missing(gap_days)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gap_days)) { statement <- paste0(statement, " gap_days IS NULL") } else { statement <- paste0(statement, " gap_days = '", gap_days,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_dose_era <- function(dose_era_id, person_id, drug_concept_id, unit_concept_id, dose_value, dose_era_start_date, dose_era_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect dose_era' AS test, CASE WHEN(SELECT COUNT(*) FROM dose_era WHERE") first <- TRUE if (!missing(dose_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_id)) { statement <- paste0(statement, " dose_era_id IS NULL") } else { statement <- paste0(statement, " dose_era_id = '", dose_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(dose_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_value)) { statement <- paste0(statement, " dose_value IS NULL") } else { statement <- paste0(statement, " dose_value = '", dose_value,"'") } } if (!missing(dose_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_start_date)) { statement <- paste0(statement, " dose_era_start_date IS NULL") } else { statement <- paste0(statement, " dose_era_start_date = '", dose_era_start_date,"'") } } if (!missing(dose_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_end_date)) { statement <- paste0(statement, " dose_era_end_date IS NULL") } else { statement <- paste0(statement, " dose_era_end_date = '", dose_era_end_date,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_condition_era <- function(condition_era_id, person_id, condition_concept_id, condition_era_start_date, condition_era_end_date, condition_occurrence_count) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect condition_era' AS test, CASE WHEN(SELECT COUNT(*) FROM condition_era WHERE") first <- TRUE if (!missing(condition_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_id)) { statement <- paste0(statement, " condition_era_id IS NULL") } else { statement <- paste0(statement, " condition_era_id = '", condition_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(condition_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_concept_id)) { statement <- paste0(statement, " condition_concept_id IS NULL") } else { statement <- paste0(statement, " condition_concept_id = '", condition_concept_id,"'") } } if (!missing(condition_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_start_date)) { statement <- paste0(statement, " condition_era_start_date IS NULL") } else { statement <- paste0(statement, " condition_era_start_date = '", condition_era_start_date,"'") } } if (!missing(condition_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_end_date)) { statement <- paste0(statement, " condition_era_end_date IS NULL") } else { statement <- paste0(statement, " condition_era_end_date = '", condition_era_end_date,"'") } } if (!missing(condition_occurrence_count)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_occurrence_count)) { statement <- paste0(statement, " condition_occurrence_count IS NULL") } else { statement <- paste0(statement, " condition_occurrence_count = '", condition_occurrence_count,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_cdm_source <- function(cdm_source_name, cdm_source_abbreviation, cdm_holder, source_description, source_documentation_reference, cdm_etl_reference, source_release_date, cdm_release_date, cdm_version, vocabulary_version) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cdm_source' AS test, CASE WHEN(SELECT COUNT(*) FROM cdm_source WHERE") first <- TRUE if (!missing(cdm_source_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_source_name)) { statement <- paste0(statement, " cdm_source_name IS NULL") } else { statement <- paste0(statement, " cdm_source_name = '", cdm_source_name,"'") } } if (!missing(cdm_source_abbreviation)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_source_abbreviation)) { statement <- paste0(statement, " cdm_source_abbreviation IS NULL") } else { statement <- paste0(statement, " cdm_source_abbreviation = '", cdm_source_abbreviation,"'") } } if (!missing(cdm_holder)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_holder)) { statement <- paste0(statement, " cdm_holder IS NULL") } else { statement <- paste0(statement, " cdm_holder = '", cdm_holder,"'") } } if (!missing(source_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_description)) { statement <- paste0(statement, " source_description IS NULL") } else { statement <- paste0(statement, " source_description = '", source_description,"'") } } if (!missing(source_documentation_reference)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_documentation_reference)) { statement <- paste0(statement, " source_documentation_reference IS NULL") } else { statement <- paste0(statement, " source_documentation_reference = '", source_documentation_reference,"'") } } if (!missing(cdm_etl_reference)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_etl_reference)) { statement <- paste0(statement, " cdm_etl_reference IS NULL") } else { statement <- paste0(statement, " cdm_etl_reference = '", cdm_etl_reference,"'") } } if (!missing(source_release_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_release_date)) { statement <- paste0(statement, " source_release_date IS NULL") } else { statement <- paste0(statement, " source_release_date = '", source_release_date,"'") } } if (!missing(cdm_release_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_release_date)) { statement <- paste0(statement, " cdm_release_date IS NULL") } else { statement <- paste0(statement, " cdm_release_date = '", cdm_release_date,"'") } } if (!missing(cdm_version)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_version)) { statement <- paste0(statement, " cdm_version IS NULL") } else { statement <- paste0(statement, " cdm_version = '", cdm_version,"'") } } if (!missing(vocabulary_version)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(vocabulary_version)) { statement <- paste0(statement, " vocabulary_version IS NULL") } else { statement <- paste0(statement, " vocabulary_version = '", vocabulary_version,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_cohort <- function(cohort_definition_id, subject_id, cohort_start_date, cohort_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(subject_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_id)) { statement <- paste0(statement, " subject_id IS NULL") } else { statement <- paste0(statement, " subject_id = '", subject_id,"'") } } if (!missing(cohort_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_start_date)) { statement <- paste0(statement, " cohort_start_date IS NULL") } else { statement <- paste0(statement, " cohort_start_date = '", cohort_start_date,"'") } } if (!missing(cohort_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_end_date)) { statement <- paste0(statement, " cohort_end_date IS NULL") } else { statement <- paste0(statement, " cohort_end_date = '", cohort_end_date,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_cohort_definition <- function(cohort_definition_id, cohort_definition_name, cohort_definition_description, definition_type_concept_id, cohort_definition_syntax, subject_concept_id, cohort_instantiation_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort_definition' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort_definition WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(cohort_definition_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_name)) { statement <- paste0(statement, " cohort_definition_name IS NULL") } else { statement <- paste0(statement, " cohort_definition_name = '", cohort_definition_name,"'") } } if (!missing(cohort_definition_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_description)) { statement <- paste0(statement, " cohort_definition_description IS NULL") } else { statement <- paste0(statement, " cohort_definition_description = '", cohort_definition_description,"'") } } if (!missing(definition_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(definition_type_concept_id)) { statement <- paste0(statement, " definition_type_concept_id IS NULL") } else { statement <- paste0(statement, " definition_type_concept_id = '", definition_type_concept_id,"'") } } if (!missing(cohort_definition_syntax)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_syntax)) { statement <- paste0(statement, " cohort_definition_syntax IS NULL") } else { statement <- paste0(statement, " cohort_definition_syntax = '", cohort_definition_syntax,"'") } } if (!missing(subject_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_concept_id)) { statement <- paste0(statement, " subject_concept_id IS NULL") } else { statement <- paste0(statement, " subject_concept_id = '", subject_concept_id,"'") } } if (!missing(cohort_instantiation_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_instantiation_date)) { statement <- paste0(statement, " cohort_instantiation_date IS NULL") } else { statement <- paste0(statement, " cohort_instantiation_date = '", cohort_instantiation_date,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_cohort_attribute <- function(cohort_definition_id, cohort_start_date, cohort_end_date, subject_id, attribute_definition_id, value_as_number, value_as_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort_attribute' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort_attribute WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(cohort_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_start_date)) { statement <- paste0(statement, " cohort_start_date IS NULL") } else { statement <- paste0(statement, " cohort_start_date = '", cohort_start_date,"'") } } if (!missing(cohort_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_end_date)) { statement <- paste0(statement, " cohort_end_date IS NULL") } else { statement <- paste0(statement, " cohort_end_date = '", cohort_end_date,"'") } } if (!missing(subject_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_id)) { statement <- paste0(statement, " subject_id IS NULL") } else { statement <- paste0(statement, " subject_id = '", subject_id,"'") } } if (!missing(attribute_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_definition_id)) { statement <- paste0(statement, " attribute_definition_id IS NULL") } else { statement <- paste0(statement, " attribute_definition_id = '", attribute_definition_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_attribute_definition <- function(attribute_definition_id, attribute_name, attribute_description, attribute_type_concept_id, attribute_syntax) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect attribute_definition' AS test, CASE WHEN(SELECT COUNT(*) FROM attribute_definition WHERE") first <- TRUE if (!missing(attribute_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_definition_id)) { statement <- paste0(statement, " attribute_definition_id IS NULL") } else { statement <- paste0(statement, " attribute_definition_id = '", attribute_definition_id,"'") } } if (!missing(attribute_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_name)) { statement <- paste0(statement, " attribute_name IS NULL") } else { statement <- paste0(statement, " attribute_name = '", attribute_name,"'") } } if (!missing(attribute_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_description)) { statement <- paste0(statement, " attribute_description IS NULL") } else { statement <- paste0(statement, " attribute_description = '", attribute_description,"'") } } if (!missing(attribute_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_type_concept_id)) { statement <- paste0(statement, " attribute_type_concept_id IS NULL") } else { statement <- paste0(statement, " attribute_type_concept_id = '", attribute_type_concept_id,"'") } } if (!missing(attribute_syntax)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_syntax)) { statement <- paste0(statement, " attribute_syntax IS NULL") } else { statement <- paste0(statement, " attribute_syntax = '", attribute_syntax,"'") } } statement <- paste0(statement, ") = 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_provider <- function(provider_id, provider_name, npi, dea, specialty_concept_id, care_site_id, year_of_birth, gender_concept_id, provider_source_value, specialty_source_value, specialty_source_concept_id, gender_source_value, gender_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect provider' AS test, CASE WHEN(SELECT COUNT(*) FROM provider WHERE") first <- TRUE if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(provider_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_name)) { statement <- paste0(statement, " provider_name IS NULL") } else { statement <- paste0(statement, " provider_name = '", provider_name,"'") } } if (!missing(npi)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(npi)) { statement <- paste0(statement, " npi IS NULL") } else { statement <- paste0(statement, " npi = '", npi,"'") } } if (!missing(dea)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dea)) { statement <- paste0(statement, " dea IS NULL") } else { statement <- paste0(statement, " dea = '", dea,"'") } } if (!missing(specialty_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_concept_id)) { statement <- paste0(statement, " specialty_concept_id IS NULL") } else { statement <- paste0(statement, " specialty_concept_id = '", specialty_concept_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(year_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(year_of_birth)) { statement <- paste0(statement, " year_of_birth IS NULL") } else { statement <- paste0(statement, " year_of_birth = '", year_of_birth,"'") } } if (!missing(gender_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_concept_id)) { statement <- paste0(statement, " gender_concept_id IS NULL") } else { statement <- paste0(statement, " gender_concept_id = '", gender_concept_id,"'") } } if (!missing(provider_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_source_value)) { statement <- paste0(statement, " provider_source_value IS NULL") } else { statement <- paste0(statement, " provider_source_value = '", provider_source_value,"'") } } if (!missing(specialty_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_source_value)) { statement <- paste0(statement, " specialty_source_value IS NULL") } else { statement <- paste0(statement, " specialty_source_value = '", specialty_source_value,"'") } } if (!missing(specialty_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_source_concept_id)) { statement <- paste0(statement, " specialty_source_concept_id IS NULL") } else { statement <- paste0(statement, " specialty_source_concept_id = '", specialty_source_concept_id,"'") } } if (!missing(gender_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_value)) { statement <- paste0(statement, " gender_source_value IS NULL") } else { statement <- paste0(statement, " gender_source_value = '", gender_source_value,"'") } } if (!missing(gender_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_concept_id)) { statement <- paste0(statement, " gender_source_concept_id IS NULL") } else { statement <- paste0(statement, " gender_source_concept_id = '", gender_source_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_care_site <- function(care_site_id, care_site_name, place_of_service_concept_id, location_id, care_site_source_value, place_of_service_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect care_site' AS test, CASE WHEN(SELECT COUNT(*) FROM care_site WHERE") first <- TRUE if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(care_site_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_name)) { statement <- paste0(statement, " care_site_name IS NULL") } else { statement <- paste0(statement, " care_site_name = '", care_site_name,"'") } } if (!missing(place_of_service_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(place_of_service_concept_id)) { statement <- paste0(statement, " place_of_service_concept_id IS NULL") } else { statement <- paste0(statement, " place_of_service_concept_id = '", place_of_service_concept_id,"'") } } if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(care_site_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_source_value)) { statement <- paste0(statement, " care_site_source_value IS NULL") } else { statement <- paste0(statement, " care_site_source_value = '", care_site_source_value,"'") } } if (!missing(place_of_service_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(place_of_service_source_value)) { statement <- paste0(statement, " place_of_service_source_value IS NULL") } else { statement <- paste0(statement, " place_of_service_source_value = '", place_of_service_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_location <- function(location_id, address_1, address_2, city, state, zip, county, location_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect location' AS test, CASE WHEN(SELECT COUNT(*) FROM location WHERE") first <- TRUE if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(address_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(address_1)) { statement <- paste0(statement, " address_1 IS NULL") } else { statement <- paste0(statement, " address_1 = '", address_1,"'") } } if (!missing(address_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(address_2)) { statement <- paste0(statement, " address_2 IS NULL") } else { statement <- paste0(statement, " address_2 = '", address_2,"'") } } if (!missing(city)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(city)) { statement <- paste0(statement, " city IS NULL") } else { statement <- paste0(statement, " city = '", city,"'") } } if (!missing(state)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(state)) { statement <- paste0(statement, " state IS NULL") } else { statement <- paste0(statement, " state = '", state,"'") } } if (!missing(zip)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(zip)) { statement <- paste0(statement, " zip IS NULL") } else { statement <- paste0(statement, " zip = '", zip,"'") } } if (!missing(county)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(county)) { statement <- paste0(statement, " county IS NULL") } else { statement <- paste0(statement, " county = '", county,"'") } } if (!missing(location_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_source_value)) { statement <- paste0(statement, " location_source_value IS NULL") } else { statement <- paste0(statement, " location_source_value = '", location_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_person <- function(person_id, gender_concept_id, year_of_birth, month_of_birth, day_of_birth, time_of_birth, race_concept_id, ethnicity_concept_id, location_id, provider_id, care_site_id, person_source_value, gender_source_value, gender_source_concept_id, race_source_value, race_source_concept_id, ethnicity_source_value, ethnicity_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect person' AS test, CASE WHEN(SELECT COUNT(*) FROM person WHERE") first <- TRUE if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(gender_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_concept_id)) { statement <- paste0(statement, " gender_concept_id IS NULL") } else { statement <- paste0(statement, " gender_concept_id = '", gender_concept_id,"'") } } if (!missing(year_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(year_of_birth)) { statement <- paste0(statement, " year_of_birth IS NULL") } else { statement <- paste0(statement, " year_of_birth = '", year_of_birth,"'") } } if (!missing(month_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(month_of_birth)) { statement <- paste0(statement, " month_of_birth IS NULL") } else { statement <- paste0(statement, " month_of_birth = '", month_of_birth,"'") } } if (!missing(day_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(day_of_birth)) { statement <- paste0(statement, " day_of_birth IS NULL") } else { statement <- paste0(statement, " day_of_birth = '", day_of_birth,"'") } } if (!missing(time_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(time_of_birth)) { statement <- paste0(statement, " time_of_birth IS NULL") } else { statement <- paste0(statement, " time_of_birth = '", time_of_birth,"'") } } if (!missing(race_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_concept_id)) { statement <- paste0(statement, " race_concept_id IS NULL") } else { statement <- paste0(statement, " race_concept_id = '", race_concept_id,"'") } } if (!missing(ethnicity_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_concept_id)) { statement <- paste0(statement, " ethnicity_concept_id IS NULL") } else { statement <- paste0(statement, " ethnicity_concept_id = '", ethnicity_concept_id,"'") } } if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(person_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_source_value)) { statement <- paste0(statement, " person_source_value IS NULL") } else { statement <- paste0(statement, " person_source_value = '", person_source_value,"'") } } if (!missing(gender_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_value)) { statement <- paste0(statement, " gender_source_value IS NULL") } else { statement <- paste0(statement, " gender_source_value = '", gender_source_value,"'") } } if (!missing(gender_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_concept_id)) { statement <- paste0(statement, " gender_source_concept_id IS NULL") } else { statement <- paste0(statement, " gender_source_concept_id = '", gender_source_concept_id,"'") } } if (!missing(race_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_source_value)) { statement <- paste0(statement, " race_source_value IS NULL") } else { statement <- paste0(statement, " race_source_value = '", race_source_value,"'") } } if (!missing(race_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_source_concept_id)) { statement <- paste0(statement, " race_source_concept_id IS NULL") } else { statement <- paste0(statement, " race_source_concept_id = '", race_source_concept_id,"'") } } if (!missing(ethnicity_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_source_value)) { statement <- paste0(statement, " ethnicity_source_value IS NULL") } else { statement <- paste0(statement, " ethnicity_source_value = '", ethnicity_source_value,"'") } } if (!missing(ethnicity_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_source_concept_id)) { statement <- paste0(statement, " ethnicity_source_concept_id IS NULL") } else { statement <- paste0(statement, " ethnicity_source_concept_id = '", ethnicity_source_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_observation_period <- function(observation_period_id, person_id, observation_period_start_date, observation_period_end_date, period_type_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect observation_period' AS test, CASE WHEN(SELECT COUNT(*) FROM observation_period WHERE") first <- TRUE if (!missing(observation_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_id)) { statement <- paste0(statement, " observation_period_id IS NULL") } else { statement <- paste0(statement, " observation_period_id = '", observation_period_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(observation_period_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_start_date)) { statement <- paste0(statement, " observation_period_start_date IS NULL") } else { statement <- paste0(statement, " observation_period_start_date = '", observation_period_start_date,"'") } } if (!missing(observation_period_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_end_date)) { statement <- paste0(statement, " observation_period_end_date IS NULL") } else { statement <- paste0(statement, " observation_period_end_date = '", observation_period_end_date,"'") } } if (!missing(period_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(period_type_concept_id)) { statement <- paste0(statement, " period_type_concept_id IS NULL") } else { statement <- paste0(statement, " period_type_concept_id = '", period_type_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_death <- function(person_id, death_date, death_type_concept_id, cause_concept_id, cause_source_value, cause_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect death' AS test, CASE WHEN(SELECT COUNT(*) FROM death WHERE") first <- TRUE if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(death_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(death_date)) { statement <- paste0(statement, " death_date IS NULL") } else { statement <- paste0(statement, " death_date = '", death_date,"'") } } if (!missing(death_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(death_type_concept_id)) { statement <- paste0(statement, " death_type_concept_id IS NULL") } else { statement <- paste0(statement, " death_type_concept_id = '", death_type_concept_id,"'") } } if (!missing(cause_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_concept_id)) { statement <- paste0(statement, " cause_concept_id IS NULL") } else { statement <- paste0(statement, " cause_concept_id = '", cause_concept_id,"'") } } if (!missing(cause_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_source_value)) { statement <- paste0(statement, " cause_source_value IS NULL") } else { statement <- paste0(statement, " cause_source_value = '", cause_source_value,"'") } } if (!missing(cause_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_source_concept_id)) { statement <- paste0(statement, " cause_source_concept_id IS NULL") } else { statement <- paste0(statement, " cause_source_concept_id = '", cause_source_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_visit_occurrence <- function(visit_occurrence_id, person_id, visit_concept_id, visit_start_date, visit_start_time, visit_end_date, visit_end_time, visit_type_concept_id, provider_id, care_site_id, visit_source_value, visit_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect visit_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM visit_occurrence WHERE") first <- TRUE if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(visit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_concept_id)) { statement <- paste0(statement, " visit_concept_id IS NULL") } else { statement <- paste0(statement, " visit_concept_id = '", visit_concept_id,"'") } } if (!missing(visit_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_start_date)) { statement <- paste0(statement, " visit_start_date IS NULL") } else { statement <- paste0(statement, " visit_start_date = '", visit_start_date,"'") } } if (!missing(visit_start_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_start_time)) { statement <- paste0(statement, " visit_start_time IS NULL") } else { statement <- paste0(statement, " visit_start_time = '", visit_start_time,"'") } } if (!missing(visit_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_end_date)) { statement <- paste0(statement, " visit_end_date IS NULL") } else { statement <- paste0(statement, " visit_end_date = '", visit_end_date,"'") } } if (!missing(visit_end_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_end_time)) { statement <- paste0(statement, " visit_end_time IS NULL") } else { statement <- paste0(statement, " visit_end_time = '", visit_end_time,"'") } } if (!missing(visit_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_type_concept_id)) { statement <- paste0(statement, " visit_type_concept_id IS NULL") } else { statement <- paste0(statement, " visit_type_concept_id = '", visit_type_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(visit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_source_value)) { statement <- paste0(statement, " visit_source_value IS NULL") } else { statement <- paste0(statement, " visit_source_value = '", visit_source_value,"'") } } if (!missing(visit_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_source_concept_id)) { statement <- paste0(statement, " visit_source_concept_id IS NULL") } else { statement <- paste0(statement, " visit_source_concept_id = '", visit_source_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_condition_occurrence <- function(condition_occurrence_id, person_id, condition_concept_id, condition_source_concept_id, condition_source_value, condition_start_date, provider_id, visit_occurrence_id, condition_type_concept_id, condition_end_date, stop_reason) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect condition_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM condition_occurrence WHERE") first <- TRUE if (!missing(condition_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_occurrence_id)) { statement <- paste0(statement, " condition_occurrence_id IS NULL") } else { statement <- paste0(statement, " condition_occurrence_id = '", condition_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(condition_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_concept_id)) { statement <- paste0(statement, " condition_concept_id IS NULL") } else { statement <- paste0(statement, " condition_concept_id = '", condition_concept_id,"'") } } if (!missing(condition_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_source_concept_id)) { statement <- paste0(statement, " condition_source_concept_id IS NULL") } else { statement <- paste0(statement, " condition_source_concept_id = '", condition_source_concept_id,"'") } } if (!missing(condition_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_source_value)) { statement <- paste0(statement, " condition_source_value IS NULL") } else { statement <- paste0(statement, " condition_source_value = '", condition_source_value,"'") } } if (!missing(condition_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_start_date)) { statement <- paste0(statement, " condition_start_date IS NULL") } else { statement <- paste0(statement, " condition_start_date = '", condition_start_date,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(condition_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_type_concept_id)) { statement <- paste0(statement, " condition_type_concept_id IS NULL") } else { statement <- paste0(statement, " condition_type_concept_id = '", condition_type_concept_id,"'") } } if (!missing(condition_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_end_date)) { statement <- paste0(statement, " condition_end_date IS NULL") } else { statement <- paste0(statement, " condition_end_date = '", condition_end_date,"'") } } if (!missing(stop_reason)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(stop_reason)) { statement <- paste0(statement, " stop_reason IS NULL") } else { statement <- paste0(statement, " stop_reason = '", stop_reason,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_device_exposure <- function(device_exposure_id, person_id, device_concept_id, device_exposure_start_date, device_exposure_end_date, device_type_concept_id, unique_device_id, quantity, provider_id, visit_occurrence_id, device_source_value, device_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect device_exposure' AS test, CASE WHEN(SELECT COUNT(*) FROM device_exposure WHERE") first <- TRUE if (!missing(device_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_id)) { statement <- paste0(statement, " device_exposure_id IS NULL") } else { statement <- paste0(statement, " device_exposure_id = '", device_exposure_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(device_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_concept_id)) { statement <- paste0(statement, " device_concept_id IS NULL") } else { statement <- paste0(statement, " device_concept_id = '", device_concept_id,"'") } } if (!missing(device_exposure_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_start_date)) { statement <- paste0(statement, " device_exposure_start_date IS NULL") } else { statement <- paste0(statement, " device_exposure_start_date = '", device_exposure_start_date,"'") } } if (!missing(device_exposure_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_end_date)) { statement <- paste0(statement, " device_exposure_end_date IS NULL") } else { statement <- paste0(statement, " device_exposure_end_date = '", device_exposure_end_date,"'") } } if (!missing(device_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_type_concept_id)) { statement <- paste0(statement, " device_type_concept_id IS NULL") } else { statement <- paste0(statement, " device_type_concept_id = '", device_type_concept_id,"'") } } if (!missing(unique_device_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unique_device_id)) { statement <- paste0(statement, " unique_device_id IS NULL") } else { statement <- paste0(statement, " unique_device_id = '", unique_device_id,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(device_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_source_value)) { statement <- paste0(statement, " device_source_value IS NULL") } else { statement <- paste0(statement, " device_source_value = '", device_source_value,"'") } } if (!missing(device_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_source_concept_id)) { statement <- paste0(statement, " device_source_concept_id IS NULL") } else { statement <- paste0(statement, " device_source_concept_id = '", device_source_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_observation <- function(observation_id, person_id, observation_concept_id, observation_date, observation_time, observation_type_concept_id, value_as_number, value_as_string, value_as_concept_id, qualifier_concept_id, unit_concept_id, provider_id, visit_occurrence_id, observation_source_value, observation_source_concept_id, unit_source_value, qualifier_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect observation' AS test, CASE WHEN(SELECT COUNT(*) FROM observation WHERE") first <- TRUE if (!missing(observation_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_id)) { statement <- paste0(statement, " observation_id IS NULL") } else { statement <- paste0(statement, " observation_id = '", observation_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(observation_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_concept_id)) { statement <- paste0(statement, " observation_concept_id IS NULL") } else { statement <- paste0(statement, " observation_concept_id = '", observation_concept_id,"'") } } if (!missing(observation_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_date)) { statement <- paste0(statement, " observation_date IS NULL") } else { statement <- paste0(statement, " observation_date = '", observation_date,"'") } } if (!missing(observation_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_time)) { statement <- paste0(statement, " observation_time IS NULL") } else { statement <- paste0(statement, " observation_time = '", observation_time,"'") } } if (!missing(observation_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_type_concept_id)) { statement <- paste0(statement, " observation_type_concept_id IS NULL") } else { statement <- paste0(statement, " observation_type_concept_id = '", observation_type_concept_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_string)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_string)) { statement <- paste0(statement, " value_as_string IS NULL") } else { statement <- paste0(statement, " value_as_string = '", value_as_string,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } if (!missing(qualifier_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_concept_id)) { statement <- paste0(statement, " qualifier_concept_id IS NULL") } else { statement <- paste0(statement, " qualifier_concept_id = '", qualifier_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(observation_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_source_value)) { statement <- paste0(statement, " observation_source_value IS NULL") } else { statement <- paste0(statement, " observation_source_value = '", observation_source_value,"'") } } if (!missing(observation_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_source_concept_id)) { statement <- paste0(statement, " observation_source_concept_id IS NULL") } else { statement <- paste0(statement, " observation_source_concept_id = '", observation_source_concept_id,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(qualifier_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_source_value)) { statement <- paste0(statement, " qualifier_source_value IS NULL") } else { statement <- paste0(statement, " qualifier_source_value = '", qualifier_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_measurement <- function(measurement_id, person_id, measurement_concept_id, measurement_date, measurement_time, measurement_type_concept_id, operator_concept_id, value_as_number, value_as_concept_id, unit_concept_id, range_low, range_high, provider_id, visit_occurrence_id, measurement_source_value, measurement_source_concept_id, unit_source_value, value_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect measurement' AS test, CASE WHEN(SELECT COUNT(*) FROM measurement WHERE") first <- TRUE if (!missing(measurement_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_id)) { statement <- paste0(statement, " measurement_id IS NULL") } else { statement <- paste0(statement, " measurement_id = '", measurement_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(measurement_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_concept_id)) { statement <- paste0(statement, " measurement_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_concept_id = '", measurement_concept_id,"'") } } if (!missing(measurement_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_date)) { statement <- paste0(statement, " measurement_date IS NULL") } else { statement <- paste0(statement, " measurement_date = '", measurement_date,"'") } } if (!missing(measurement_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_time)) { statement <- paste0(statement, " measurement_time IS NULL") } else { statement <- paste0(statement, " measurement_time = '", measurement_time,"'") } } if (!missing(measurement_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_type_concept_id)) { statement <- paste0(statement, " measurement_type_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_type_concept_id = '", measurement_type_concept_id,"'") } } if (!missing(operator_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(operator_concept_id)) { statement <- paste0(statement, " operator_concept_id IS NULL") } else { statement <- paste0(statement, " operator_concept_id = '", operator_concept_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(range_low)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(range_low)) { statement <- paste0(statement, " range_low IS NULL") } else { statement <- paste0(statement, " range_low = '", range_low,"'") } } if (!missing(range_high)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(range_high)) { statement <- paste0(statement, " range_high IS NULL") } else { statement <- paste0(statement, " range_high = '", range_high,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(measurement_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_source_value)) { statement <- paste0(statement, " measurement_source_value IS NULL") } else { statement <- paste0(statement, " measurement_source_value = '", measurement_source_value,"'") } } if (!missing(measurement_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_source_concept_id)) { statement <- paste0(statement, " measurement_source_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_source_concept_id = '", measurement_source_concept_id,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(value_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_source_value)) { statement <- paste0(statement, " value_source_value IS NULL") } else { statement <- paste0(statement, " value_source_value = '", value_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_procedure_occurrence <- function(procedure_occurrence_id, person_id, procedure_concept_id, procedure_date, procedure_type_concept_id, modifier_concept_id, quantity, provider_id, visit_occurrence_id, procedure_source_value, procedure_source_concept_id, qualifier_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect procedure_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM procedure_occurrence WHERE") first <- TRUE if (!missing(procedure_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_occurrence_id)) { statement <- paste0(statement, " procedure_occurrence_id IS NULL") } else { statement <- paste0(statement, " procedure_occurrence_id = '", procedure_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(procedure_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_concept_id)) { statement <- paste0(statement, " procedure_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_concept_id = '", procedure_concept_id,"'") } } if (!missing(procedure_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_date)) { statement <- paste0(statement, " procedure_date IS NULL") } else { statement <- paste0(statement, " procedure_date = '", procedure_date,"'") } } if (!missing(procedure_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_type_concept_id)) { statement <- paste0(statement, " procedure_type_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_type_concept_id = '", procedure_type_concept_id,"'") } } if (!missing(modifier_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(modifier_concept_id)) { statement <- paste0(statement, " modifier_concept_id IS NULL") } else { statement <- paste0(statement, " modifier_concept_id = '", modifier_concept_id,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(procedure_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_source_value)) { statement <- paste0(statement, " procedure_source_value IS NULL") } else { statement <- paste0(statement, " procedure_source_value = '", procedure_source_value,"'") } } if (!missing(procedure_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_source_concept_id)) { statement <- paste0(statement, " procedure_source_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_source_concept_id = '", procedure_source_concept_id,"'") } } if (!missing(qualifier_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_source_value)) { statement <- paste0(statement, " qualifier_source_value IS NULL") } else { statement <- paste0(statement, " qualifier_source_value = '", qualifier_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_drug_exposure <- function(drug_exposure_id, person_id, drug_exposure_start_date, drug_concept_id, drug_source_value, drug_source_concept_id, drug_type_concept_id, provider_id, visit_occurrence_id, route_concept_id, route_source_value, quantity, refills, days_supply, dose_unit_concept_id, dose_unit_source_value, effective_drug_dose, stop_reason, sig, lot_number, drug_exposure_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_exposure' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_exposure WHERE") first <- TRUE if (!missing(drug_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_id)) { statement <- paste0(statement, " drug_exposure_id IS NULL") } else { statement <- paste0(statement, " drug_exposure_id = '", drug_exposure_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_exposure_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_start_date)) { statement <- paste0(statement, " drug_exposure_start_date IS NULL") } else { statement <- paste0(statement, " drug_exposure_start_date = '", drug_exposure_start_date,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(drug_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_source_value)) { statement <- paste0(statement, " drug_source_value IS NULL") } else { statement <- paste0(statement, " drug_source_value = '", drug_source_value,"'") } } if (!missing(drug_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_source_concept_id)) { statement <- paste0(statement, " drug_source_concept_id IS NULL") } else { statement <- paste0(statement, " drug_source_concept_id = '", drug_source_concept_id,"'") } } if (!missing(drug_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_type_concept_id)) { statement <- paste0(statement, " drug_type_concept_id IS NULL") } else { statement <- paste0(statement, " drug_type_concept_id = '", drug_type_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(route_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(route_concept_id)) { statement <- paste0(statement, " route_concept_id IS NULL") } else { statement <- paste0(statement, " route_concept_id = '", route_concept_id,"'") } } if (!missing(route_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(route_source_value)) { statement <- paste0(statement, " route_source_value IS NULL") } else { statement <- paste0(statement, " route_source_value = '", route_source_value,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(refills)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(refills)) { statement <- paste0(statement, " refills IS NULL") } else { statement <- paste0(statement, " refills = '", refills,"'") } } if (!missing(days_supply)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(days_supply)) { statement <- paste0(statement, " days_supply IS NULL") } else { statement <- paste0(statement, " days_supply = '", days_supply,"'") } } if (!missing(dose_unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_unit_concept_id)) { statement <- paste0(statement, " dose_unit_concept_id IS NULL") } else { statement <- paste0(statement, " dose_unit_concept_id = '", dose_unit_concept_id,"'") } } if (!missing(dose_unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_unit_source_value)) { statement <- paste0(statement, " dose_unit_source_value IS NULL") } else { statement <- paste0(statement, " dose_unit_source_value = '", dose_unit_source_value,"'") } } if (!missing(effective_drug_dose)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(effective_drug_dose)) { statement <- paste0(statement, " effective_drug_dose IS NULL") } else { statement <- paste0(statement, " effective_drug_dose = '", effective_drug_dose,"'") } } if (!missing(stop_reason)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(stop_reason)) { statement <- paste0(statement, " stop_reason IS NULL") } else { statement <- paste0(statement, " stop_reason = '", stop_reason,"'") } } if (!missing(sig)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(sig)) { statement <- paste0(statement, " sig IS NULL") } else { statement <- paste0(statement, " sig = '", sig,"'") } } if (!missing(lot_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(lot_number)) { statement <- paste0(statement, " lot_number IS NULL") } else { statement <- paste0(statement, " lot_number = '", lot_number,"'") } } if (!missing(drug_exposure_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_end_date)) { statement <- paste0(statement, " drug_exposure_end_date IS NULL") } else { statement <- paste0(statement, " drug_exposure_end_date = '", drug_exposure_end_date,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_fact_relationship <- function(domain_concept_id_1, fact_id_1, domain_concept_id_2, fact_id_2, relationship_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect fact_relationship' AS test, CASE WHEN(SELECT COUNT(*) FROM fact_relationship WHERE") first <- TRUE if (!missing(domain_concept_id_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(domain_concept_id_1)) { statement <- paste0(statement, " domain_concept_id_1 IS NULL") } else { statement <- paste0(statement, " domain_concept_id_1 = '", domain_concept_id_1,"'") } } if (!missing(fact_id_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(fact_id_1)) { statement <- paste0(statement, " fact_id_1 IS NULL") } else { statement <- paste0(statement, " fact_id_1 = '", fact_id_1,"'") } } if (!missing(domain_concept_id_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(domain_concept_id_2)) { statement <- paste0(statement, " domain_concept_id_2 IS NULL") } else { statement <- paste0(statement, " domain_concept_id_2 = '", domain_concept_id_2,"'") } } if (!missing(fact_id_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(fact_id_2)) { statement <- paste0(statement, " fact_id_2 IS NULL") } else { statement <- paste0(statement, " fact_id_2 = '", fact_id_2,"'") } } if (!missing(relationship_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(relationship_concept_id)) { statement <- paste0(statement, " relationship_concept_id IS NULL") } else { statement <- paste0(statement, " relationship_concept_id = '", relationship_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_payer_plan_period <- function(payer_plan_period_id, person_id, payer_plan_period_start_date, payer_plan_period_end_date, payer_source_value, plan_source_value, family_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect payer_plan_period' AS test, CASE WHEN(SELECT COUNT(*) FROM payer_plan_period WHERE") first <- TRUE if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(payer_plan_period_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_start_date)) { statement <- paste0(statement, " payer_plan_period_start_date IS NULL") } else { statement <- paste0(statement, " payer_plan_period_start_date = '", payer_plan_period_start_date,"'") } } if (!missing(payer_plan_period_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_end_date)) { statement <- paste0(statement, " payer_plan_period_end_date IS NULL") } else { statement <- paste0(statement, " payer_plan_period_end_date = '", payer_plan_period_end_date,"'") } } if (!missing(payer_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_source_value)) { statement <- paste0(statement, " payer_source_value IS NULL") } else { statement <- paste0(statement, " payer_source_value = '", payer_source_value,"'") } } if (!missing(plan_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(plan_source_value)) { statement <- paste0(statement, " plan_source_value IS NULL") } else { statement <- paste0(statement, " plan_source_value = '", plan_source_value,"'") } } if (!missing(family_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(family_source_value)) { statement <- paste0(statement, " family_source_value IS NULL") } else { statement <- paste0(statement, " family_source_value = '", family_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_note <- function(note_id, person_id, note_date, note_time, note_type_concept_id, note_text, provider_id, visit_occurrence_id, note_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect note' AS test, CASE WHEN(SELECT COUNT(*) FROM note WHERE") first <- TRUE if (!missing(note_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_id)) { statement <- paste0(statement, " note_id IS NULL") } else { statement <- paste0(statement, " note_id = '", note_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(note_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_date)) { statement <- paste0(statement, " note_date IS NULL") } else { statement <- paste0(statement, " note_date = '", note_date,"'") } } if (!missing(note_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_time)) { statement <- paste0(statement, " note_time IS NULL") } else { statement <- paste0(statement, " note_time = '", note_time,"'") } } if (!missing(note_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_type_concept_id)) { statement <- paste0(statement, " note_type_concept_id IS NULL") } else { statement <- paste0(statement, " note_type_concept_id = '", note_type_concept_id,"'") } } if (!missing(note_text)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_text)) { statement <- paste0(statement, " note_text IS NULL") } else { statement <- paste0(statement, " note_text = '", note_text,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(note_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_source_value)) { statement <- paste0(statement, " note_source_value IS NULL") } else { statement <- paste0(statement, " note_source_value = '", note_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_specimen <- function(specimen_id, person_id, specimen_concept_id, specimen_type_concept_id, specimen_date, specimen_time, quantity, unit_concept_id, anatomic_site_concept_id, disease_status_concept_id, specimen_source_id, specimen_source_value, unit_source_value, anatomic_site_source_value, disease_status_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect specimen' AS test, CASE WHEN(SELECT COUNT(*) FROM specimen WHERE") first <- TRUE if (!missing(specimen_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_id)) { statement <- paste0(statement, " specimen_id IS NULL") } else { statement <- paste0(statement, " specimen_id = '", specimen_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(specimen_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_concept_id)) { statement <- paste0(statement, " specimen_concept_id IS NULL") } else { statement <- paste0(statement, " specimen_concept_id = '", specimen_concept_id,"'") } } if (!missing(specimen_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_type_concept_id)) { statement <- paste0(statement, " specimen_type_concept_id IS NULL") } else { statement <- paste0(statement, " specimen_type_concept_id = '", specimen_type_concept_id,"'") } } if (!missing(specimen_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_date)) { statement <- paste0(statement, " specimen_date IS NULL") } else { statement <- paste0(statement, " specimen_date = '", specimen_date,"'") } } if (!missing(specimen_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_time)) { statement <- paste0(statement, " specimen_time IS NULL") } else { statement <- paste0(statement, " specimen_time = '", specimen_time,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(anatomic_site_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(anatomic_site_concept_id)) { statement <- paste0(statement, " anatomic_site_concept_id IS NULL") } else { statement <- paste0(statement, " anatomic_site_concept_id = '", anatomic_site_concept_id,"'") } } if (!missing(disease_status_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(disease_status_concept_id)) { statement <- paste0(statement, " disease_status_concept_id IS NULL") } else { statement <- paste0(statement, " disease_status_concept_id = '", disease_status_concept_id,"'") } } if (!missing(specimen_source_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_source_id)) { statement <- paste0(statement, " specimen_source_id IS NULL") } else { statement <- paste0(statement, " specimen_source_id = '", specimen_source_id,"'") } } if (!missing(specimen_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_source_value)) { statement <- paste0(statement, " specimen_source_value IS NULL") } else { statement <- paste0(statement, " specimen_source_value = '", specimen_source_value,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(anatomic_site_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(anatomic_site_source_value)) { statement <- paste0(statement, " anatomic_site_source_value IS NULL") } else { statement <- paste0(statement, " anatomic_site_source_value = '", anatomic_site_source_value,"'") } } if (!missing(disease_status_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(disease_status_source_value)) { statement <- paste0(statement, " disease_status_source_value IS NULL") } else { statement <- paste0(statement, " disease_status_source_value = '", disease_status_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_procedure_cost <- function(procedure_cost_id, procedure_occurrence_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, revenue_code_concept_id, payer_plan_period_id, revenue_code_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect procedure_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM procedure_cost WHERE") first <- TRUE if (!missing(procedure_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_cost_id)) { statement <- paste0(statement, " procedure_cost_id IS NULL") } else { statement <- paste0(statement, " procedure_cost_id = '", procedure_cost_id,"'") } } if (!missing(procedure_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_occurrence_id)) { statement <- paste0(statement, " procedure_occurrence_id IS NULL") } else { statement <- paste0(statement, " procedure_occurrence_id = '", procedure_occurrence_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(revenue_code_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(revenue_code_concept_id)) { statement <- paste0(statement, " revenue_code_concept_id IS NULL") } else { statement <- paste0(statement, " revenue_code_concept_id = '", revenue_code_concept_id,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } if (!missing(revenue_code_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(revenue_code_source_value)) { statement <- paste0(statement, " revenue_code_source_value IS NULL") } else { statement <- paste0(statement, " revenue_code_source_value = '", revenue_code_source_value,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_visit_cost <- function(visit_cost_id, visit_occurrence_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect visit_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM visit_cost WHERE") first <- TRUE if (!missing(visit_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_cost_id)) { statement <- paste0(statement, " visit_cost_id IS NULL") } else { statement <- paste0(statement, " visit_cost_id = '", visit_cost_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_drug_cost <- function(drug_cost_id, drug_exposure_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, ingredient_cost, dispensing_fee, average_wholesale_price, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_cost WHERE") first <- TRUE if (!missing(drug_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_cost_id)) { statement <- paste0(statement, " drug_cost_id IS NULL") } else { statement <- paste0(statement, " drug_cost_id = '", drug_cost_id,"'") } } if (!missing(drug_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_id)) { statement <- paste0(statement, " drug_exposure_id IS NULL") } else { statement <- paste0(statement, " drug_exposure_id = '", drug_exposure_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(ingredient_cost)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ingredient_cost)) { statement <- paste0(statement, " ingredient_cost IS NULL") } else { statement <- paste0(statement, " ingredient_cost = '", ingredient_cost,"'") } } if (!missing(dispensing_fee)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dispensing_fee)) { statement <- paste0(statement, " dispensing_fee IS NULL") } else { statement <- paste0(statement, " dispensing_fee = '", dispensing_fee,"'") } } if (!missing(average_wholesale_price)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(average_wholesale_price)) { statement <- paste0(statement, " average_wholesale_price IS NULL") } else { statement <- paste0(statement, " average_wholesale_price = '", average_wholesale_price,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_device_cost <- function(device_cost_id, device_exposure_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect device_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM device_cost WHERE") first <- TRUE if (!missing(device_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_cost_id)) { statement <- paste0(statement, " device_cost_id IS NULL") } else { statement <- paste0(statement, " device_cost_id = '", device_cost_id,"'") } } if (!missing(device_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_id)) { statement <- paste0(statement, " device_exposure_id IS NULL") } else { statement <- paste0(statement, " device_exposure_id = '", device_exposure_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_drug_era <- function(drug_era_id, person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, drug_exposure_count, gap_days) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_era' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_era WHERE") first <- TRUE if (!missing(drug_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_id)) { statement <- paste0(statement, " drug_era_id IS NULL") } else { statement <- paste0(statement, " drug_era_id = '", drug_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(drug_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_start_date)) { statement <- paste0(statement, " drug_era_start_date IS NULL") } else { statement <- paste0(statement, " drug_era_start_date = '", drug_era_start_date,"'") } } if (!missing(drug_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_end_date)) { statement <- paste0(statement, " drug_era_end_date IS NULL") } else { statement <- paste0(statement, " drug_era_end_date = '", drug_era_end_date,"'") } } if (!missing(drug_exposure_count)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_count)) { statement <- paste0(statement, " drug_exposure_count IS NULL") } else { statement <- paste0(statement, " drug_exposure_count = '", drug_exposure_count,"'") } } if (!missing(gap_days)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gap_days)) { statement <- paste0(statement, " gap_days IS NULL") } else { statement <- paste0(statement, " gap_days = '", gap_days,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_dose_era <- function(dose_era_id, person_id, drug_concept_id, unit_concept_id, dose_value, dose_era_start_date, dose_era_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect dose_era' AS test, CASE WHEN(SELECT COUNT(*) FROM dose_era WHERE") first <- TRUE if (!missing(dose_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_id)) { statement <- paste0(statement, " dose_era_id IS NULL") } else { statement <- paste0(statement, " dose_era_id = '", dose_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(dose_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_value)) { statement <- paste0(statement, " dose_value IS NULL") } else { statement <- paste0(statement, " dose_value = '", dose_value,"'") } } if (!missing(dose_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_start_date)) { statement <- paste0(statement, " dose_era_start_date IS NULL") } else { statement <- paste0(statement, " dose_era_start_date = '", dose_era_start_date,"'") } } if (!missing(dose_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_end_date)) { statement <- paste0(statement, " dose_era_end_date IS NULL") } else { statement <- paste0(statement, " dose_era_end_date = '", dose_era_end_date,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_condition_era <- function(condition_era_id, person_id, condition_concept_id, condition_era_start_date, condition_era_end_date, condition_occurrence_count) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect condition_era' AS test, CASE WHEN(SELECT COUNT(*) FROM condition_era WHERE") first <- TRUE if (!missing(condition_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_id)) { statement <- paste0(statement, " condition_era_id IS NULL") } else { statement <- paste0(statement, " condition_era_id = '", condition_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(condition_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_concept_id)) { statement <- paste0(statement, " condition_concept_id IS NULL") } else { statement <- paste0(statement, " condition_concept_id = '", condition_concept_id,"'") } } if (!missing(condition_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_start_date)) { statement <- paste0(statement, " condition_era_start_date IS NULL") } else { statement <- paste0(statement, " condition_era_start_date = '", condition_era_start_date,"'") } } if (!missing(condition_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_end_date)) { statement <- paste0(statement, " condition_era_end_date IS NULL") } else { statement <- paste0(statement, " condition_era_end_date = '", condition_era_end_date,"'") } } if (!missing(condition_occurrence_count)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_occurrence_count)) { statement <- paste0(statement, " condition_occurrence_count IS NULL") } else { statement <- paste0(statement, " condition_occurrence_count = '", condition_occurrence_count,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_cdm_source <- function(cdm_source_name, cdm_source_abbreviation, cdm_holder, source_description, source_documentation_reference, cdm_etl_reference, source_release_date, cdm_release_date, cdm_version, vocabulary_version) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cdm_source' AS test, CASE WHEN(SELECT COUNT(*) FROM cdm_source WHERE") first <- TRUE if (!missing(cdm_source_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_source_name)) { statement <- paste0(statement, " cdm_source_name IS NULL") } else { statement <- paste0(statement, " cdm_source_name = '", cdm_source_name,"'") } } if (!missing(cdm_source_abbreviation)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_source_abbreviation)) { statement <- paste0(statement, " cdm_source_abbreviation IS NULL") } else { statement <- paste0(statement, " cdm_source_abbreviation = '", cdm_source_abbreviation,"'") } } if (!missing(cdm_holder)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_holder)) { statement <- paste0(statement, " cdm_holder IS NULL") } else { statement <- paste0(statement, " cdm_holder = '", cdm_holder,"'") } } if (!missing(source_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_description)) { statement <- paste0(statement, " source_description IS NULL") } else { statement <- paste0(statement, " source_description = '", source_description,"'") } } if (!missing(source_documentation_reference)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_documentation_reference)) { statement <- paste0(statement, " source_documentation_reference IS NULL") } else { statement <- paste0(statement, " source_documentation_reference = '", source_documentation_reference,"'") } } if (!missing(cdm_etl_reference)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_etl_reference)) { statement <- paste0(statement, " cdm_etl_reference IS NULL") } else { statement <- paste0(statement, " cdm_etl_reference = '", cdm_etl_reference,"'") } } if (!missing(source_release_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_release_date)) { statement <- paste0(statement, " source_release_date IS NULL") } else { statement <- paste0(statement, " source_release_date = '", source_release_date,"'") } } if (!missing(cdm_release_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_release_date)) { statement <- paste0(statement, " cdm_release_date IS NULL") } else { statement <- paste0(statement, " cdm_release_date = '", cdm_release_date,"'") } } if (!missing(cdm_version)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_version)) { statement <- paste0(statement, " cdm_version IS NULL") } else { statement <- paste0(statement, " cdm_version = '", cdm_version,"'") } } if (!missing(vocabulary_version)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(vocabulary_version)) { statement <- paste0(statement, " vocabulary_version IS NULL") } else { statement <- paste0(statement, " vocabulary_version = '", vocabulary_version,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_cohort <- function(cohort_definition_id, subject_id, cohort_start_date, cohort_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(subject_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_id)) { statement <- paste0(statement, " subject_id IS NULL") } else { statement <- paste0(statement, " subject_id = '", subject_id,"'") } } if (!missing(cohort_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_start_date)) { statement <- paste0(statement, " cohort_start_date IS NULL") } else { statement <- paste0(statement, " cohort_start_date = '", cohort_start_date,"'") } } if (!missing(cohort_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_end_date)) { statement <- paste0(statement, " cohort_end_date IS NULL") } else { statement <- paste0(statement, " cohort_end_date = '", cohort_end_date,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_cohort_definition <- function(cohort_definition_id, cohort_definition_name, cohort_definition_description, definition_type_concept_id, cohort_definition_syntax, subject_concept_id, cohort_instantiation_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort_definition' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort_definition WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(cohort_definition_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_name)) { statement <- paste0(statement, " cohort_definition_name IS NULL") } else { statement <- paste0(statement, " cohort_definition_name = '", cohort_definition_name,"'") } } if (!missing(cohort_definition_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_description)) { statement <- paste0(statement, " cohort_definition_description IS NULL") } else { statement <- paste0(statement, " cohort_definition_description = '", cohort_definition_description,"'") } } if (!missing(definition_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(definition_type_concept_id)) { statement <- paste0(statement, " definition_type_concept_id IS NULL") } else { statement <- paste0(statement, " definition_type_concept_id = '", definition_type_concept_id,"'") } } if (!missing(cohort_definition_syntax)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_syntax)) { statement <- paste0(statement, " cohort_definition_syntax IS NULL") } else { statement <- paste0(statement, " cohort_definition_syntax = '", cohort_definition_syntax,"'") } } if (!missing(subject_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_concept_id)) { statement <- paste0(statement, " subject_concept_id IS NULL") } else { statement <- paste0(statement, " subject_concept_id = '", subject_concept_id,"'") } } if (!missing(cohort_instantiation_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_instantiation_date)) { statement <- paste0(statement, " cohort_instantiation_date IS NULL") } else { statement <- paste0(statement, " cohort_instantiation_date = '", cohort_instantiation_date,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_cohort_attribute <- function(cohort_definition_id, cohort_start_date, cohort_end_date, subject_id, attribute_definition_id, value_as_number, value_as_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort_attribute' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort_attribute WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(cohort_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_start_date)) { statement <- paste0(statement, " cohort_start_date IS NULL") } else { statement <- paste0(statement, " cohort_start_date = '", cohort_start_date,"'") } } if (!missing(cohort_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_end_date)) { statement <- paste0(statement, " cohort_end_date IS NULL") } else { statement <- paste0(statement, " cohort_end_date = '", cohort_end_date,"'") } } if (!missing(subject_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_id)) { statement <- paste0(statement, " subject_id IS NULL") } else { statement <- paste0(statement, " subject_id = '", subject_id,"'") } } if (!missing(attribute_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_definition_id)) { statement <- paste0(statement, " attribute_definition_id IS NULL") } else { statement <- paste0(statement, " attribute_definition_id = '", attribute_definition_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_no_attribute_definition <- function(attribute_definition_id, attribute_name, attribute_description, attribute_type_concept_id, attribute_syntax) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect attribute_definition' AS test, CASE WHEN(SELECT COUNT(*) FROM attribute_definition WHERE") first <- TRUE if (!missing(attribute_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_definition_id)) { statement <- paste0(statement, " attribute_definition_id IS NULL") } else { statement <- paste0(statement, " attribute_definition_id = '", attribute_definition_id,"'") } } if (!missing(attribute_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_name)) { statement <- paste0(statement, " attribute_name IS NULL") } else { statement <- paste0(statement, " attribute_name = '", attribute_name,"'") } } if (!missing(attribute_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_description)) { statement <- paste0(statement, " attribute_description IS NULL") } else { statement <- paste0(statement, " attribute_description = '", attribute_description,"'") } } if (!missing(attribute_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_type_concept_id)) { statement <- paste0(statement, " attribute_type_concept_id IS NULL") } else { statement <- paste0(statement, " attribute_type_concept_id = '", attribute_type_concept_id,"'") } } if (!missing(attribute_syntax)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_syntax)) { statement <- paste0(statement, " attribute_syntax IS NULL") } else { statement <- paste0(statement, " attribute_syntax = '", attribute_syntax,"'") } } statement <- paste0(statement, ") != 0 THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_provider <- function(rowCount, provider_id, provider_name, npi, dea, specialty_concept_id, care_site_id, year_of_birth, gender_concept_id, provider_source_value, specialty_source_value, specialty_source_concept_id, gender_source_value, gender_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect provider' AS test, CASE WHEN(SELECT COUNT(*) FROM provider WHERE") first <- TRUE if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(provider_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_name)) { statement <- paste0(statement, " provider_name IS NULL") } else { statement <- paste0(statement, " provider_name = '", provider_name,"'") } } if (!missing(npi)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(npi)) { statement <- paste0(statement, " npi IS NULL") } else { statement <- paste0(statement, " npi = '", npi,"'") } } if (!missing(dea)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dea)) { statement <- paste0(statement, " dea IS NULL") } else { statement <- paste0(statement, " dea = '", dea,"'") } } if (!missing(specialty_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_concept_id)) { statement <- paste0(statement, " specialty_concept_id IS NULL") } else { statement <- paste0(statement, " specialty_concept_id = '", specialty_concept_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(year_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(year_of_birth)) { statement <- paste0(statement, " year_of_birth IS NULL") } else { statement <- paste0(statement, " year_of_birth = '", year_of_birth,"'") } } if (!missing(gender_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_concept_id)) { statement <- paste0(statement, " gender_concept_id IS NULL") } else { statement <- paste0(statement, " gender_concept_id = '", gender_concept_id,"'") } } if (!missing(provider_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_source_value)) { statement <- paste0(statement, " provider_source_value IS NULL") } else { statement <- paste0(statement, " provider_source_value = '", provider_source_value,"'") } } if (!missing(specialty_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_source_value)) { statement <- paste0(statement, " specialty_source_value IS NULL") } else { statement <- paste0(statement, " specialty_source_value = '", specialty_source_value,"'") } } if (!missing(specialty_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specialty_source_concept_id)) { statement <- paste0(statement, " specialty_source_concept_id IS NULL") } else { statement <- paste0(statement, " specialty_source_concept_id = '", specialty_source_concept_id,"'") } } if (!missing(gender_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_value)) { statement <- paste0(statement, " gender_source_value IS NULL") } else { statement <- paste0(statement, " gender_source_value = '", gender_source_value,"'") } } if (!missing(gender_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_concept_id)) { statement <- paste0(statement, " gender_source_concept_id IS NULL") } else { statement <- paste0(statement, " gender_source_concept_id = '", gender_source_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_care_site <- function(rowCount, care_site_id, care_site_name, place_of_service_concept_id, location_id, care_site_source_value, place_of_service_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect care_site' AS test, CASE WHEN(SELECT COUNT(*) FROM care_site WHERE") first <- TRUE if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(care_site_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_name)) { statement <- paste0(statement, " care_site_name IS NULL") } else { statement <- paste0(statement, " care_site_name = '", care_site_name,"'") } } if (!missing(place_of_service_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(place_of_service_concept_id)) { statement <- paste0(statement, " place_of_service_concept_id IS NULL") } else { statement <- paste0(statement, " place_of_service_concept_id = '", place_of_service_concept_id,"'") } } if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(care_site_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_source_value)) { statement <- paste0(statement, " care_site_source_value IS NULL") } else { statement <- paste0(statement, " care_site_source_value = '", care_site_source_value,"'") } } if (!missing(place_of_service_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(place_of_service_source_value)) { statement <- paste0(statement, " place_of_service_source_value IS NULL") } else { statement <- paste0(statement, " place_of_service_source_value = '", place_of_service_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_location <- function(rowCount, location_id, address_1, address_2, city, state, zip, county, location_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect location' AS test, CASE WHEN(SELECT COUNT(*) FROM location WHERE") first <- TRUE if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(address_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(address_1)) { statement <- paste0(statement, " address_1 IS NULL") } else { statement <- paste0(statement, " address_1 = '", address_1,"'") } } if (!missing(address_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(address_2)) { statement <- paste0(statement, " address_2 IS NULL") } else { statement <- paste0(statement, " address_2 = '", address_2,"'") } } if (!missing(city)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(city)) { statement <- paste0(statement, " city IS NULL") } else { statement <- paste0(statement, " city = '", city,"'") } } if (!missing(state)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(state)) { statement <- paste0(statement, " state IS NULL") } else { statement <- paste0(statement, " state = '", state,"'") } } if (!missing(zip)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(zip)) { statement <- paste0(statement, " zip IS NULL") } else { statement <- paste0(statement, " zip = '", zip,"'") } } if (!missing(county)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(county)) { statement <- paste0(statement, " county IS NULL") } else { statement <- paste0(statement, " county = '", county,"'") } } if (!missing(location_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_source_value)) { statement <- paste0(statement, " location_source_value IS NULL") } else { statement <- paste0(statement, " location_source_value = '", location_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_person <- function(rowCount, person_id, gender_concept_id, year_of_birth, month_of_birth, day_of_birth, time_of_birth, race_concept_id, ethnicity_concept_id, location_id, provider_id, care_site_id, person_source_value, gender_source_value, gender_source_concept_id, race_source_value, race_source_concept_id, ethnicity_source_value, ethnicity_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect person' AS test, CASE WHEN(SELECT COUNT(*) FROM person WHERE") first <- TRUE if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(gender_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_concept_id)) { statement <- paste0(statement, " gender_concept_id IS NULL") } else { statement <- paste0(statement, " gender_concept_id = '", gender_concept_id,"'") } } if (!missing(year_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(year_of_birth)) { statement <- paste0(statement, " year_of_birth IS NULL") } else { statement <- paste0(statement, " year_of_birth = '", year_of_birth,"'") } } if (!missing(month_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(month_of_birth)) { statement <- paste0(statement, " month_of_birth IS NULL") } else { statement <- paste0(statement, " month_of_birth = '", month_of_birth,"'") } } if (!missing(day_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(day_of_birth)) { statement <- paste0(statement, " day_of_birth IS NULL") } else { statement <- paste0(statement, " day_of_birth = '", day_of_birth,"'") } } if (!missing(time_of_birth)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(time_of_birth)) { statement <- paste0(statement, " time_of_birth IS NULL") } else { statement <- paste0(statement, " time_of_birth = '", time_of_birth,"'") } } if (!missing(race_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_concept_id)) { statement <- paste0(statement, " race_concept_id IS NULL") } else { statement <- paste0(statement, " race_concept_id = '", race_concept_id,"'") } } if (!missing(ethnicity_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_concept_id)) { statement <- paste0(statement, " ethnicity_concept_id IS NULL") } else { statement <- paste0(statement, " ethnicity_concept_id = '", ethnicity_concept_id,"'") } } if (!missing(location_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(location_id)) { statement <- paste0(statement, " location_id IS NULL") } else { statement <- paste0(statement, " location_id = '", location_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(person_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_source_value)) { statement <- paste0(statement, " person_source_value IS NULL") } else { statement <- paste0(statement, " person_source_value = '", person_source_value,"'") } } if (!missing(gender_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_value)) { statement <- paste0(statement, " gender_source_value IS NULL") } else { statement <- paste0(statement, " gender_source_value = '", gender_source_value,"'") } } if (!missing(gender_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gender_source_concept_id)) { statement <- paste0(statement, " gender_source_concept_id IS NULL") } else { statement <- paste0(statement, " gender_source_concept_id = '", gender_source_concept_id,"'") } } if (!missing(race_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_source_value)) { statement <- paste0(statement, " race_source_value IS NULL") } else { statement <- paste0(statement, " race_source_value = '", race_source_value,"'") } } if (!missing(race_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(race_source_concept_id)) { statement <- paste0(statement, " race_source_concept_id IS NULL") } else { statement <- paste0(statement, " race_source_concept_id = '", race_source_concept_id,"'") } } if (!missing(ethnicity_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_source_value)) { statement <- paste0(statement, " ethnicity_source_value IS NULL") } else { statement <- paste0(statement, " ethnicity_source_value = '", ethnicity_source_value,"'") } } if (!missing(ethnicity_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ethnicity_source_concept_id)) { statement <- paste0(statement, " ethnicity_source_concept_id IS NULL") } else { statement <- paste0(statement, " ethnicity_source_concept_id = '", ethnicity_source_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_observation_period <- function(rowCount, observation_period_id, person_id, observation_period_start_date, observation_period_end_date, period_type_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect observation_period' AS test, CASE WHEN(SELECT COUNT(*) FROM observation_period WHERE") first <- TRUE if (!missing(observation_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_id)) { statement <- paste0(statement, " observation_period_id IS NULL") } else { statement <- paste0(statement, " observation_period_id = '", observation_period_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(observation_period_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_start_date)) { statement <- paste0(statement, " observation_period_start_date IS NULL") } else { statement <- paste0(statement, " observation_period_start_date = '", observation_period_start_date,"'") } } if (!missing(observation_period_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_period_end_date)) { statement <- paste0(statement, " observation_period_end_date IS NULL") } else { statement <- paste0(statement, " observation_period_end_date = '", observation_period_end_date,"'") } } if (!missing(period_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(period_type_concept_id)) { statement <- paste0(statement, " period_type_concept_id IS NULL") } else { statement <- paste0(statement, " period_type_concept_id = '", period_type_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_death <- function(rowCount, person_id, death_date, death_type_concept_id, cause_concept_id, cause_source_value, cause_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect death' AS test, CASE WHEN(SELECT COUNT(*) FROM death WHERE") first <- TRUE if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(death_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(death_date)) { statement <- paste0(statement, " death_date IS NULL") } else { statement <- paste0(statement, " death_date = '", death_date,"'") } } if (!missing(death_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(death_type_concept_id)) { statement <- paste0(statement, " death_type_concept_id IS NULL") } else { statement <- paste0(statement, " death_type_concept_id = '", death_type_concept_id,"'") } } if (!missing(cause_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_concept_id)) { statement <- paste0(statement, " cause_concept_id IS NULL") } else { statement <- paste0(statement, " cause_concept_id = '", cause_concept_id,"'") } } if (!missing(cause_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_source_value)) { statement <- paste0(statement, " cause_source_value IS NULL") } else { statement <- paste0(statement, " cause_source_value = '", cause_source_value,"'") } } if (!missing(cause_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cause_source_concept_id)) { statement <- paste0(statement, " cause_source_concept_id IS NULL") } else { statement <- paste0(statement, " cause_source_concept_id = '", cause_source_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_visit_occurrence <- function(rowCount, visit_occurrence_id, person_id, visit_concept_id, visit_start_date, visit_start_time, visit_end_date, visit_end_time, visit_type_concept_id, provider_id, care_site_id, visit_source_value, visit_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect visit_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM visit_occurrence WHERE") first <- TRUE if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(visit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_concept_id)) { statement <- paste0(statement, " visit_concept_id IS NULL") } else { statement <- paste0(statement, " visit_concept_id = '", visit_concept_id,"'") } } if (!missing(visit_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_start_date)) { statement <- paste0(statement, " visit_start_date IS NULL") } else { statement <- paste0(statement, " visit_start_date = '", visit_start_date,"'") } } if (!missing(visit_start_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_start_time)) { statement <- paste0(statement, " visit_start_time IS NULL") } else { statement <- paste0(statement, " visit_start_time = '", visit_start_time,"'") } } if (!missing(visit_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_end_date)) { statement <- paste0(statement, " visit_end_date IS NULL") } else { statement <- paste0(statement, " visit_end_date = '", visit_end_date,"'") } } if (!missing(visit_end_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_end_time)) { statement <- paste0(statement, " visit_end_time IS NULL") } else { statement <- paste0(statement, " visit_end_time = '", visit_end_time,"'") } } if (!missing(visit_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_type_concept_id)) { statement <- paste0(statement, " visit_type_concept_id IS NULL") } else { statement <- paste0(statement, " visit_type_concept_id = '", visit_type_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(care_site_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(care_site_id)) { statement <- paste0(statement, " care_site_id IS NULL") } else { statement <- paste0(statement, " care_site_id = '", care_site_id,"'") } } if (!missing(visit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_source_value)) { statement <- paste0(statement, " visit_source_value IS NULL") } else { statement <- paste0(statement, " visit_source_value = '", visit_source_value,"'") } } if (!missing(visit_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_source_concept_id)) { statement <- paste0(statement, " visit_source_concept_id IS NULL") } else { statement <- paste0(statement, " visit_source_concept_id = '", visit_source_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_condition_occurrence <- function(rowCount, condition_occurrence_id, person_id, condition_concept_id, condition_source_concept_id, condition_source_value, condition_start_date, provider_id, visit_occurrence_id, condition_type_concept_id, condition_end_date, stop_reason) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect condition_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM condition_occurrence WHERE") first <- TRUE if (!missing(condition_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_occurrence_id)) { statement <- paste0(statement, " condition_occurrence_id IS NULL") } else { statement <- paste0(statement, " condition_occurrence_id = '", condition_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(condition_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_concept_id)) { statement <- paste0(statement, " condition_concept_id IS NULL") } else { statement <- paste0(statement, " condition_concept_id = '", condition_concept_id,"'") } } if (!missing(condition_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_source_concept_id)) { statement <- paste0(statement, " condition_source_concept_id IS NULL") } else { statement <- paste0(statement, " condition_source_concept_id = '", condition_source_concept_id,"'") } } if (!missing(condition_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_source_value)) { statement <- paste0(statement, " condition_source_value IS NULL") } else { statement <- paste0(statement, " condition_source_value = '", condition_source_value,"'") } } if (!missing(condition_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_start_date)) { statement <- paste0(statement, " condition_start_date IS NULL") } else { statement <- paste0(statement, " condition_start_date = '", condition_start_date,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(condition_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_type_concept_id)) { statement <- paste0(statement, " condition_type_concept_id IS NULL") } else { statement <- paste0(statement, " condition_type_concept_id = '", condition_type_concept_id,"'") } } if (!missing(condition_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_end_date)) { statement <- paste0(statement, " condition_end_date IS NULL") } else { statement <- paste0(statement, " condition_end_date = '", condition_end_date,"'") } } if (!missing(stop_reason)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(stop_reason)) { statement <- paste0(statement, " stop_reason IS NULL") } else { statement <- paste0(statement, " stop_reason = '", stop_reason,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_device_exposure <- function(rowCount, device_exposure_id, person_id, device_concept_id, device_exposure_start_date, device_exposure_end_date, device_type_concept_id, unique_device_id, quantity, provider_id, visit_occurrence_id, device_source_value, device_source_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect device_exposure' AS test, CASE WHEN(SELECT COUNT(*) FROM device_exposure WHERE") first <- TRUE if (!missing(device_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_id)) { statement <- paste0(statement, " device_exposure_id IS NULL") } else { statement <- paste0(statement, " device_exposure_id = '", device_exposure_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(device_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_concept_id)) { statement <- paste0(statement, " device_concept_id IS NULL") } else { statement <- paste0(statement, " device_concept_id = '", device_concept_id,"'") } } if (!missing(device_exposure_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_start_date)) { statement <- paste0(statement, " device_exposure_start_date IS NULL") } else { statement <- paste0(statement, " device_exposure_start_date = '", device_exposure_start_date,"'") } } if (!missing(device_exposure_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_end_date)) { statement <- paste0(statement, " device_exposure_end_date IS NULL") } else { statement <- paste0(statement, " device_exposure_end_date = '", device_exposure_end_date,"'") } } if (!missing(device_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_type_concept_id)) { statement <- paste0(statement, " device_type_concept_id IS NULL") } else { statement <- paste0(statement, " device_type_concept_id = '", device_type_concept_id,"'") } } if (!missing(unique_device_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unique_device_id)) { statement <- paste0(statement, " unique_device_id IS NULL") } else { statement <- paste0(statement, " unique_device_id = '", unique_device_id,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(device_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_source_value)) { statement <- paste0(statement, " device_source_value IS NULL") } else { statement <- paste0(statement, " device_source_value = '", device_source_value,"'") } } if (!missing(device_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_source_concept_id)) { statement <- paste0(statement, " device_source_concept_id IS NULL") } else { statement <- paste0(statement, " device_source_concept_id = '", device_source_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_observation <- function(rowCount, observation_id, person_id, observation_concept_id, observation_date, observation_time, observation_type_concept_id, value_as_number, value_as_string, value_as_concept_id, qualifier_concept_id, unit_concept_id, provider_id, visit_occurrence_id, observation_source_value, observation_source_concept_id, unit_source_value, qualifier_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect observation' AS test, CASE WHEN(SELECT COUNT(*) FROM observation WHERE") first <- TRUE if (!missing(observation_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_id)) { statement <- paste0(statement, " observation_id IS NULL") } else { statement <- paste0(statement, " observation_id = '", observation_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(observation_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_concept_id)) { statement <- paste0(statement, " observation_concept_id IS NULL") } else { statement <- paste0(statement, " observation_concept_id = '", observation_concept_id,"'") } } if (!missing(observation_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_date)) { statement <- paste0(statement, " observation_date IS NULL") } else { statement <- paste0(statement, " observation_date = '", observation_date,"'") } } if (!missing(observation_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_time)) { statement <- paste0(statement, " observation_time IS NULL") } else { statement <- paste0(statement, " observation_time = '", observation_time,"'") } } if (!missing(observation_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_type_concept_id)) { statement <- paste0(statement, " observation_type_concept_id IS NULL") } else { statement <- paste0(statement, " observation_type_concept_id = '", observation_type_concept_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_string)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_string)) { statement <- paste0(statement, " value_as_string IS NULL") } else { statement <- paste0(statement, " value_as_string = '", value_as_string,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } if (!missing(qualifier_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_concept_id)) { statement <- paste0(statement, " qualifier_concept_id IS NULL") } else { statement <- paste0(statement, " qualifier_concept_id = '", qualifier_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(observation_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_source_value)) { statement <- paste0(statement, " observation_source_value IS NULL") } else { statement <- paste0(statement, " observation_source_value = '", observation_source_value,"'") } } if (!missing(observation_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(observation_source_concept_id)) { statement <- paste0(statement, " observation_source_concept_id IS NULL") } else { statement <- paste0(statement, " observation_source_concept_id = '", observation_source_concept_id,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(qualifier_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_source_value)) { statement <- paste0(statement, " qualifier_source_value IS NULL") } else { statement <- paste0(statement, " qualifier_source_value = '", qualifier_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_measurement <- function(rowCount, measurement_id, person_id, measurement_concept_id, measurement_date, measurement_time, measurement_type_concept_id, operator_concept_id, value_as_number, value_as_concept_id, unit_concept_id, range_low, range_high, provider_id, visit_occurrence_id, measurement_source_value, measurement_source_concept_id, unit_source_value, value_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect measurement' AS test, CASE WHEN(SELECT COUNT(*) FROM measurement WHERE") first <- TRUE if (!missing(measurement_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_id)) { statement <- paste0(statement, " measurement_id IS NULL") } else { statement <- paste0(statement, " measurement_id = '", measurement_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(measurement_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_concept_id)) { statement <- paste0(statement, " measurement_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_concept_id = '", measurement_concept_id,"'") } } if (!missing(measurement_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_date)) { statement <- paste0(statement, " measurement_date IS NULL") } else { statement <- paste0(statement, " measurement_date = '", measurement_date,"'") } } if (!missing(measurement_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_time)) { statement <- paste0(statement, " measurement_time IS NULL") } else { statement <- paste0(statement, " measurement_time = '", measurement_time,"'") } } if (!missing(measurement_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_type_concept_id)) { statement <- paste0(statement, " measurement_type_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_type_concept_id = '", measurement_type_concept_id,"'") } } if (!missing(operator_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(operator_concept_id)) { statement <- paste0(statement, " operator_concept_id IS NULL") } else { statement <- paste0(statement, " operator_concept_id = '", operator_concept_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(range_low)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(range_low)) { statement <- paste0(statement, " range_low IS NULL") } else { statement <- paste0(statement, " range_low = '", range_low,"'") } } if (!missing(range_high)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(range_high)) { statement <- paste0(statement, " range_high IS NULL") } else { statement <- paste0(statement, " range_high = '", range_high,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(measurement_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_source_value)) { statement <- paste0(statement, " measurement_source_value IS NULL") } else { statement <- paste0(statement, " measurement_source_value = '", measurement_source_value,"'") } } if (!missing(measurement_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(measurement_source_concept_id)) { statement <- paste0(statement, " measurement_source_concept_id IS NULL") } else { statement <- paste0(statement, " measurement_source_concept_id = '", measurement_source_concept_id,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(value_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_source_value)) { statement <- paste0(statement, " value_source_value IS NULL") } else { statement <- paste0(statement, " value_source_value = '", value_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_procedure_occurrence <- function(rowCount, procedure_occurrence_id, person_id, procedure_concept_id, procedure_date, procedure_type_concept_id, modifier_concept_id, quantity, provider_id, visit_occurrence_id, procedure_source_value, procedure_source_concept_id, qualifier_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect procedure_occurrence' AS test, CASE WHEN(SELECT COUNT(*) FROM procedure_occurrence WHERE") first <- TRUE if (!missing(procedure_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_occurrence_id)) { statement <- paste0(statement, " procedure_occurrence_id IS NULL") } else { statement <- paste0(statement, " procedure_occurrence_id = '", procedure_occurrence_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(procedure_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_concept_id)) { statement <- paste0(statement, " procedure_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_concept_id = '", procedure_concept_id,"'") } } if (!missing(procedure_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_date)) { statement <- paste0(statement, " procedure_date IS NULL") } else { statement <- paste0(statement, " procedure_date = '", procedure_date,"'") } } if (!missing(procedure_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_type_concept_id)) { statement <- paste0(statement, " procedure_type_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_type_concept_id = '", procedure_type_concept_id,"'") } } if (!missing(modifier_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(modifier_concept_id)) { statement <- paste0(statement, " modifier_concept_id IS NULL") } else { statement <- paste0(statement, " modifier_concept_id = '", modifier_concept_id,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(procedure_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_source_value)) { statement <- paste0(statement, " procedure_source_value IS NULL") } else { statement <- paste0(statement, " procedure_source_value = '", procedure_source_value,"'") } } if (!missing(procedure_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_source_concept_id)) { statement <- paste0(statement, " procedure_source_concept_id IS NULL") } else { statement <- paste0(statement, " procedure_source_concept_id = '", procedure_source_concept_id,"'") } } if (!missing(qualifier_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(qualifier_source_value)) { statement <- paste0(statement, " qualifier_source_value IS NULL") } else { statement <- paste0(statement, " qualifier_source_value = '", qualifier_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_drug_exposure <- function(rowCount, drug_exposure_id, person_id, drug_exposure_start_date, drug_concept_id, drug_source_value, drug_source_concept_id, drug_type_concept_id, provider_id, visit_occurrence_id, route_concept_id, route_source_value, quantity, refills, days_supply, dose_unit_concept_id, dose_unit_source_value, effective_drug_dose, stop_reason, sig, lot_number, drug_exposure_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_exposure' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_exposure WHERE") first <- TRUE if (!missing(drug_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_id)) { statement <- paste0(statement, " drug_exposure_id IS NULL") } else { statement <- paste0(statement, " drug_exposure_id = '", drug_exposure_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_exposure_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_start_date)) { statement <- paste0(statement, " drug_exposure_start_date IS NULL") } else { statement <- paste0(statement, " drug_exposure_start_date = '", drug_exposure_start_date,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(drug_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_source_value)) { statement <- paste0(statement, " drug_source_value IS NULL") } else { statement <- paste0(statement, " drug_source_value = '", drug_source_value,"'") } } if (!missing(drug_source_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_source_concept_id)) { statement <- paste0(statement, " drug_source_concept_id IS NULL") } else { statement <- paste0(statement, " drug_source_concept_id = '", drug_source_concept_id,"'") } } if (!missing(drug_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_type_concept_id)) { statement <- paste0(statement, " drug_type_concept_id IS NULL") } else { statement <- paste0(statement, " drug_type_concept_id = '", drug_type_concept_id,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(route_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(route_concept_id)) { statement <- paste0(statement, " route_concept_id IS NULL") } else { statement <- paste0(statement, " route_concept_id = '", route_concept_id,"'") } } if (!missing(route_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(route_source_value)) { statement <- paste0(statement, " route_source_value IS NULL") } else { statement <- paste0(statement, " route_source_value = '", route_source_value,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(refills)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(refills)) { statement <- paste0(statement, " refills IS NULL") } else { statement <- paste0(statement, " refills = '", refills,"'") } } if (!missing(days_supply)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(days_supply)) { statement <- paste0(statement, " days_supply IS NULL") } else { statement <- paste0(statement, " days_supply = '", days_supply,"'") } } if (!missing(dose_unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_unit_concept_id)) { statement <- paste0(statement, " dose_unit_concept_id IS NULL") } else { statement <- paste0(statement, " dose_unit_concept_id = '", dose_unit_concept_id,"'") } } if (!missing(dose_unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_unit_source_value)) { statement <- paste0(statement, " dose_unit_source_value IS NULL") } else { statement <- paste0(statement, " dose_unit_source_value = '", dose_unit_source_value,"'") } } if (!missing(effective_drug_dose)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(effective_drug_dose)) { statement <- paste0(statement, " effective_drug_dose IS NULL") } else { statement <- paste0(statement, " effective_drug_dose = '", effective_drug_dose,"'") } } if (!missing(stop_reason)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(stop_reason)) { statement <- paste0(statement, " stop_reason IS NULL") } else { statement <- paste0(statement, " stop_reason = '", stop_reason,"'") } } if (!missing(sig)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(sig)) { statement <- paste0(statement, " sig IS NULL") } else { statement <- paste0(statement, " sig = '", sig,"'") } } if (!missing(lot_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(lot_number)) { statement <- paste0(statement, " lot_number IS NULL") } else { statement <- paste0(statement, " lot_number = '", lot_number,"'") } } if (!missing(drug_exposure_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_end_date)) { statement <- paste0(statement, " drug_exposure_end_date IS NULL") } else { statement <- paste0(statement, " drug_exposure_end_date = '", drug_exposure_end_date,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_fact_relationship <- function(rowCount, domain_concept_id_1, fact_id_1, domain_concept_id_2, fact_id_2, relationship_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect fact_relationship' AS test, CASE WHEN(SELECT COUNT(*) FROM fact_relationship WHERE") first <- TRUE if (!missing(domain_concept_id_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(domain_concept_id_1)) { statement <- paste0(statement, " domain_concept_id_1 IS NULL") } else { statement <- paste0(statement, " domain_concept_id_1 = '", domain_concept_id_1,"'") } } if (!missing(fact_id_1)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(fact_id_1)) { statement <- paste0(statement, " fact_id_1 IS NULL") } else { statement <- paste0(statement, " fact_id_1 = '", fact_id_1,"'") } } if (!missing(domain_concept_id_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(domain_concept_id_2)) { statement <- paste0(statement, " domain_concept_id_2 IS NULL") } else { statement <- paste0(statement, " domain_concept_id_2 = '", domain_concept_id_2,"'") } } if (!missing(fact_id_2)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(fact_id_2)) { statement <- paste0(statement, " fact_id_2 IS NULL") } else { statement <- paste0(statement, " fact_id_2 = '", fact_id_2,"'") } } if (!missing(relationship_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(relationship_concept_id)) { statement <- paste0(statement, " relationship_concept_id IS NULL") } else { statement <- paste0(statement, " relationship_concept_id = '", relationship_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_payer_plan_period <- function(rowCount, payer_plan_period_id, person_id, payer_plan_period_start_date, payer_plan_period_end_date, payer_source_value, plan_source_value, family_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect payer_plan_period' AS test, CASE WHEN(SELECT COUNT(*) FROM payer_plan_period WHERE") first <- TRUE if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(payer_plan_period_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_start_date)) { statement <- paste0(statement, " payer_plan_period_start_date IS NULL") } else { statement <- paste0(statement, " payer_plan_period_start_date = '", payer_plan_period_start_date,"'") } } if (!missing(payer_plan_period_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_end_date)) { statement <- paste0(statement, " payer_plan_period_end_date IS NULL") } else { statement <- paste0(statement, " payer_plan_period_end_date = '", payer_plan_period_end_date,"'") } } if (!missing(payer_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_source_value)) { statement <- paste0(statement, " payer_source_value IS NULL") } else { statement <- paste0(statement, " payer_source_value = '", payer_source_value,"'") } } if (!missing(plan_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(plan_source_value)) { statement <- paste0(statement, " plan_source_value IS NULL") } else { statement <- paste0(statement, " plan_source_value = '", plan_source_value,"'") } } if (!missing(family_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(family_source_value)) { statement <- paste0(statement, " family_source_value IS NULL") } else { statement <- paste0(statement, " family_source_value = '", family_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_note <- function(rowCount, note_id, person_id, note_date, note_time, note_type_concept_id, note_text, provider_id, visit_occurrence_id, note_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect note' AS test, CASE WHEN(SELECT COUNT(*) FROM note WHERE") first <- TRUE if (!missing(note_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_id)) { statement <- paste0(statement, " note_id IS NULL") } else { statement <- paste0(statement, " note_id = '", note_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(note_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_date)) { statement <- paste0(statement, " note_date IS NULL") } else { statement <- paste0(statement, " note_date = '", note_date,"'") } } if (!missing(note_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_time)) { statement <- paste0(statement, " note_time IS NULL") } else { statement <- paste0(statement, " note_time = '", note_time,"'") } } if (!missing(note_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_type_concept_id)) { statement <- paste0(statement, " note_type_concept_id IS NULL") } else { statement <- paste0(statement, " note_type_concept_id = '", note_type_concept_id,"'") } } if (!missing(note_text)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_text)) { statement <- paste0(statement, " note_text IS NULL") } else { statement <- paste0(statement, " note_text = '", note_text,"'") } } if (!missing(provider_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(provider_id)) { statement <- paste0(statement, " provider_id IS NULL") } else { statement <- paste0(statement, " provider_id = '", provider_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(note_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(note_source_value)) { statement <- paste0(statement, " note_source_value IS NULL") } else { statement <- paste0(statement, " note_source_value = '", note_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_specimen <- function(rowCount, specimen_id, person_id, specimen_concept_id, specimen_type_concept_id, specimen_date, specimen_time, quantity, unit_concept_id, anatomic_site_concept_id, disease_status_concept_id, specimen_source_id, specimen_source_value, unit_source_value, anatomic_site_source_value, disease_status_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect specimen' AS test, CASE WHEN(SELECT COUNT(*) FROM specimen WHERE") first <- TRUE if (!missing(specimen_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_id)) { statement <- paste0(statement, " specimen_id IS NULL") } else { statement <- paste0(statement, " specimen_id = '", specimen_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(specimen_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_concept_id)) { statement <- paste0(statement, " specimen_concept_id IS NULL") } else { statement <- paste0(statement, " specimen_concept_id = '", specimen_concept_id,"'") } } if (!missing(specimen_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_type_concept_id)) { statement <- paste0(statement, " specimen_type_concept_id IS NULL") } else { statement <- paste0(statement, " specimen_type_concept_id = '", specimen_type_concept_id,"'") } } if (!missing(specimen_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_date)) { statement <- paste0(statement, " specimen_date IS NULL") } else { statement <- paste0(statement, " specimen_date = '", specimen_date,"'") } } if (!missing(specimen_time)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_time)) { statement <- paste0(statement, " specimen_time IS NULL") } else { statement <- paste0(statement, " specimen_time = '", specimen_time,"'") } } if (!missing(quantity)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(quantity)) { statement <- paste0(statement, " quantity IS NULL") } else { statement <- paste0(statement, " quantity = '", quantity,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(anatomic_site_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(anatomic_site_concept_id)) { statement <- paste0(statement, " anatomic_site_concept_id IS NULL") } else { statement <- paste0(statement, " anatomic_site_concept_id = '", anatomic_site_concept_id,"'") } } if (!missing(disease_status_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(disease_status_concept_id)) { statement <- paste0(statement, " disease_status_concept_id IS NULL") } else { statement <- paste0(statement, " disease_status_concept_id = '", disease_status_concept_id,"'") } } if (!missing(specimen_source_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_source_id)) { statement <- paste0(statement, " specimen_source_id IS NULL") } else { statement <- paste0(statement, " specimen_source_id = '", specimen_source_id,"'") } } if (!missing(specimen_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(specimen_source_value)) { statement <- paste0(statement, " specimen_source_value IS NULL") } else { statement <- paste0(statement, " specimen_source_value = '", specimen_source_value,"'") } } if (!missing(unit_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_source_value)) { statement <- paste0(statement, " unit_source_value IS NULL") } else { statement <- paste0(statement, " unit_source_value = '", unit_source_value,"'") } } if (!missing(anatomic_site_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(anatomic_site_source_value)) { statement <- paste0(statement, " anatomic_site_source_value IS NULL") } else { statement <- paste0(statement, " anatomic_site_source_value = '", anatomic_site_source_value,"'") } } if (!missing(disease_status_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(disease_status_source_value)) { statement <- paste0(statement, " disease_status_source_value IS NULL") } else { statement <- paste0(statement, " disease_status_source_value = '", disease_status_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_procedure_cost <- function(rowCount, procedure_cost_id, procedure_occurrence_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, revenue_code_concept_id, payer_plan_period_id, revenue_code_source_value) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect procedure_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM procedure_cost WHERE") first <- TRUE if (!missing(procedure_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_cost_id)) { statement <- paste0(statement, " procedure_cost_id IS NULL") } else { statement <- paste0(statement, " procedure_cost_id = '", procedure_cost_id,"'") } } if (!missing(procedure_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(procedure_occurrence_id)) { statement <- paste0(statement, " procedure_occurrence_id IS NULL") } else { statement <- paste0(statement, " procedure_occurrence_id = '", procedure_occurrence_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(revenue_code_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(revenue_code_concept_id)) { statement <- paste0(statement, " revenue_code_concept_id IS NULL") } else { statement <- paste0(statement, " revenue_code_concept_id = '", revenue_code_concept_id,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } if (!missing(revenue_code_source_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(revenue_code_source_value)) { statement <- paste0(statement, " revenue_code_source_value IS NULL") } else { statement <- paste0(statement, " revenue_code_source_value = '", revenue_code_source_value,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_visit_cost <- function(rowCount, visit_cost_id, visit_occurrence_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect visit_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM visit_cost WHERE") first <- TRUE if (!missing(visit_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_cost_id)) { statement <- paste0(statement, " visit_cost_id IS NULL") } else { statement <- paste0(statement, " visit_cost_id = '", visit_cost_id,"'") } } if (!missing(visit_occurrence_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(visit_occurrence_id)) { statement <- paste0(statement, " visit_occurrence_id IS NULL") } else { statement <- paste0(statement, " visit_occurrence_id = '", visit_occurrence_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_drug_cost <- function(rowCount, drug_cost_id, drug_exposure_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, ingredient_cost, dispensing_fee, average_wholesale_price, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_cost WHERE") first <- TRUE if (!missing(drug_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_cost_id)) { statement <- paste0(statement, " drug_cost_id IS NULL") } else { statement <- paste0(statement, " drug_cost_id = '", drug_cost_id,"'") } } if (!missing(drug_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_id)) { statement <- paste0(statement, " drug_exposure_id IS NULL") } else { statement <- paste0(statement, " drug_exposure_id = '", drug_exposure_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(ingredient_cost)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(ingredient_cost)) { statement <- paste0(statement, " ingredient_cost IS NULL") } else { statement <- paste0(statement, " ingredient_cost = '", ingredient_cost,"'") } } if (!missing(dispensing_fee)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dispensing_fee)) { statement <- paste0(statement, " dispensing_fee IS NULL") } else { statement <- paste0(statement, " dispensing_fee = '", dispensing_fee,"'") } } if (!missing(average_wholesale_price)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(average_wholesale_price)) { statement <- paste0(statement, " average_wholesale_price IS NULL") } else { statement <- paste0(statement, " average_wholesale_price = '", average_wholesale_price,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_device_cost <- function(rowCount, device_cost_id, device_exposure_id, currency_concept_id, paid_copay, paid_coinsurance, paid_toward_deductible, paid_by_payer, paid_by_coordination_benefits, total_out_of_pocket, total_paid, payer_plan_period_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect device_cost' AS test, CASE WHEN(SELECT COUNT(*) FROM device_cost WHERE") first <- TRUE if (!missing(device_cost_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_cost_id)) { statement <- paste0(statement, " device_cost_id IS NULL") } else { statement <- paste0(statement, " device_cost_id = '", device_cost_id,"'") } } if (!missing(device_exposure_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(device_exposure_id)) { statement <- paste0(statement, " device_exposure_id IS NULL") } else { statement <- paste0(statement, " device_exposure_id = '", device_exposure_id,"'") } } if (!missing(currency_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(currency_concept_id)) { statement <- paste0(statement, " currency_concept_id IS NULL") } else { statement <- paste0(statement, " currency_concept_id = '", currency_concept_id,"'") } } if (!missing(paid_copay)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_copay)) { statement <- paste0(statement, " paid_copay IS NULL") } else { statement <- paste0(statement, " paid_copay = '", paid_copay,"'") } } if (!missing(paid_coinsurance)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_coinsurance)) { statement <- paste0(statement, " paid_coinsurance IS NULL") } else { statement <- paste0(statement, " paid_coinsurance = '", paid_coinsurance,"'") } } if (!missing(paid_toward_deductible)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_toward_deductible)) { statement <- paste0(statement, " paid_toward_deductible IS NULL") } else { statement <- paste0(statement, " paid_toward_deductible = '", paid_toward_deductible,"'") } } if (!missing(paid_by_payer)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_payer)) { statement <- paste0(statement, " paid_by_payer IS NULL") } else { statement <- paste0(statement, " paid_by_payer = '", paid_by_payer,"'") } } if (!missing(paid_by_coordination_benefits)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(paid_by_coordination_benefits)) { statement <- paste0(statement, " paid_by_coordination_benefits IS NULL") } else { statement <- paste0(statement, " paid_by_coordination_benefits = '", paid_by_coordination_benefits,"'") } } if (!missing(total_out_of_pocket)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_out_of_pocket)) { statement <- paste0(statement, " total_out_of_pocket IS NULL") } else { statement <- paste0(statement, " total_out_of_pocket = '", total_out_of_pocket,"'") } } if (!missing(total_paid)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(total_paid)) { statement <- paste0(statement, " total_paid IS NULL") } else { statement <- paste0(statement, " total_paid = '", total_paid,"'") } } if (!missing(payer_plan_period_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(payer_plan_period_id)) { statement <- paste0(statement, " payer_plan_period_id IS NULL") } else { statement <- paste0(statement, " payer_plan_period_id = '", payer_plan_period_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_drug_era <- function(rowCount, drug_era_id, person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, drug_exposure_count, gap_days) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect drug_era' AS test, CASE WHEN(SELECT COUNT(*) FROM drug_era WHERE") first <- TRUE if (!missing(drug_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_id)) { statement <- paste0(statement, " drug_era_id IS NULL") } else { statement <- paste0(statement, " drug_era_id = '", drug_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(drug_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_start_date)) { statement <- paste0(statement, " drug_era_start_date IS NULL") } else { statement <- paste0(statement, " drug_era_start_date = '", drug_era_start_date,"'") } } if (!missing(drug_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_era_end_date)) { statement <- paste0(statement, " drug_era_end_date IS NULL") } else { statement <- paste0(statement, " drug_era_end_date = '", drug_era_end_date,"'") } } if (!missing(drug_exposure_count)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_exposure_count)) { statement <- paste0(statement, " drug_exposure_count IS NULL") } else { statement <- paste0(statement, " drug_exposure_count = '", drug_exposure_count,"'") } } if (!missing(gap_days)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(gap_days)) { statement <- paste0(statement, " gap_days IS NULL") } else { statement <- paste0(statement, " gap_days = '", gap_days,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_dose_era <- function(rowCount, dose_era_id, person_id, drug_concept_id, unit_concept_id, dose_value, dose_era_start_date, dose_era_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect dose_era' AS test, CASE WHEN(SELECT COUNT(*) FROM dose_era WHERE") first <- TRUE if (!missing(dose_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_id)) { statement <- paste0(statement, " dose_era_id IS NULL") } else { statement <- paste0(statement, " dose_era_id = '", dose_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(drug_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(drug_concept_id)) { statement <- paste0(statement, " drug_concept_id IS NULL") } else { statement <- paste0(statement, " drug_concept_id = '", drug_concept_id,"'") } } if (!missing(unit_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(unit_concept_id)) { statement <- paste0(statement, " unit_concept_id IS NULL") } else { statement <- paste0(statement, " unit_concept_id = '", unit_concept_id,"'") } } if (!missing(dose_value)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_value)) { statement <- paste0(statement, " dose_value IS NULL") } else { statement <- paste0(statement, " dose_value = '", dose_value,"'") } } if (!missing(dose_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_start_date)) { statement <- paste0(statement, " dose_era_start_date IS NULL") } else { statement <- paste0(statement, " dose_era_start_date = '", dose_era_start_date,"'") } } if (!missing(dose_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(dose_era_end_date)) { statement <- paste0(statement, " dose_era_end_date IS NULL") } else { statement <- paste0(statement, " dose_era_end_date = '", dose_era_end_date,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_condition_era <- function(rowCount, condition_era_id, person_id, condition_concept_id, condition_era_start_date, condition_era_end_date, condition_occurrence_count) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect condition_era' AS test, CASE WHEN(SELECT COUNT(*) FROM condition_era WHERE") first <- TRUE if (!missing(condition_era_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_id)) { statement <- paste0(statement, " condition_era_id IS NULL") } else { statement <- paste0(statement, " condition_era_id = '", condition_era_id,"'") } } if (!missing(person_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(person_id)) { statement <- paste0(statement, " person_id IS NULL") } else { statement <- paste0(statement, " person_id = '", person_id,"'") } } if (!missing(condition_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_concept_id)) { statement <- paste0(statement, " condition_concept_id IS NULL") } else { statement <- paste0(statement, " condition_concept_id = '", condition_concept_id,"'") } } if (!missing(condition_era_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_start_date)) { statement <- paste0(statement, " condition_era_start_date IS NULL") } else { statement <- paste0(statement, " condition_era_start_date = '", condition_era_start_date,"'") } } if (!missing(condition_era_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_era_end_date)) { statement <- paste0(statement, " condition_era_end_date IS NULL") } else { statement <- paste0(statement, " condition_era_end_date = '", condition_era_end_date,"'") } } if (!missing(condition_occurrence_count)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(condition_occurrence_count)) { statement <- paste0(statement, " condition_occurrence_count IS NULL") } else { statement <- paste0(statement, " condition_occurrence_count = '", condition_occurrence_count,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_cdm_source <- function(rowCount, cdm_source_name, cdm_source_abbreviation, cdm_holder, source_description, source_documentation_reference, cdm_etl_reference, source_release_date, cdm_release_date, cdm_version, vocabulary_version) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cdm_source' AS test, CASE WHEN(SELECT COUNT(*) FROM cdm_source WHERE") first <- TRUE if (!missing(cdm_source_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_source_name)) { statement <- paste0(statement, " cdm_source_name IS NULL") } else { statement <- paste0(statement, " cdm_source_name = '", cdm_source_name,"'") } } if (!missing(cdm_source_abbreviation)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_source_abbreviation)) { statement <- paste0(statement, " cdm_source_abbreviation IS NULL") } else { statement <- paste0(statement, " cdm_source_abbreviation = '", cdm_source_abbreviation,"'") } } if (!missing(cdm_holder)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_holder)) { statement <- paste0(statement, " cdm_holder IS NULL") } else { statement <- paste0(statement, " cdm_holder = '", cdm_holder,"'") } } if (!missing(source_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_description)) { statement <- paste0(statement, " source_description IS NULL") } else { statement <- paste0(statement, " source_description = '", source_description,"'") } } if (!missing(source_documentation_reference)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_documentation_reference)) { statement <- paste0(statement, " source_documentation_reference IS NULL") } else { statement <- paste0(statement, " source_documentation_reference = '", source_documentation_reference,"'") } } if (!missing(cdm_etl_reference)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_etl_reference)) { statement <- paste0(statement, " cdm_etl_reference IS NULL") } else { statement <- paste0(statement, " cdm_etl_reference = '", cdm_etl_reference,"'") } } if (!missing(source_release_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(source_release_date)) { statement <- paste0(statement, " source_release_date IS NULL") } else { statement <- paste0(statement, " source_release_date = '", source_release_date,"'") } } if (!missing(cdm_release_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_release_date)) { statement <- paste0(statement, " cdm_release_date IS NULL") } else { statement <- paste0(statement, " cdm_release_date = '", cdm_release_date,"'") } } if (!missing(cdm_version)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cdm_version)) { statement <- paste0(statement, " cdm_version IS NULL") } else { statement <- paste0(statement, " cdm_version = '", cdm_version,"'") } } if (!missing(vocabulary_version)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(vocabulary_version)) { statement <- paste0(statement, " vocabulary_version IS NULL") } else { statement <- paste0(statement, " vocabulary_version = '", vocabulary_version,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_cohort <- function(rowCount, cohort_definition_id, subject_id, cohort_start_date, cohort_end_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(subject_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_id)) { statement <- paste0(statement, " subject_id IS NULL") } else { statement <- paste0(statement, " subject_id = '", subject_id,"'") } } if (!missing(cohort_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_start_date)) { statement <- paste0(statement, " cohort_start_date IS NULL") } else { statement <- paste0(statement, " cohort_start_date = '", cohort_start_date,"'") } } if (!missing(cohort_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_end_date)) { statement <- paste0(statement, " cohort_end_date IS NULL") } else { statement <- paste0(statement, " cohort_end_date = '", cohort_end_date,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_cohort_definition <- function(rowCount, cohort_definition_id, cohort_definition_name, cohort_definition_description, definition_type_concept_id, cohort_definition_syntax, subject_concept_id, cohort_instantiation_date) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort_definition' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort_definition WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(cohort_definition_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_name)) { statement <- paste0(statement, " cohort_definition_name IS NULL") } else { statement <- paste0(statement, " cohort_definition_name = '", cohort_definition_name,"'") } } if (!missing(cohort_definition_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_description)) { statement <- paste0(statement, " cohort_definition_description IS NULL") } else { statement <- paste0(statement, " cohort_definition_description = '", cohort_definition_description,"'") } } if (!missing(definition_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(definition_type_concept_id)) { statement <- paste0(statement, " definition_type_concept_id IS NULL") } else { statement <- paste0(statement, " definition_type_concept_id = '", definition_type_concept_id,"'") } } if (!missing(cohort_definition_syntax)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_syntax)) { statement <- paste0(statement, " cohort_definition_syntax IS NULL") } else { statement <- paste0(statement, " cohort_definition_syntax = '", cohort_definition_syntax,"'") } } if (!missing(subject_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_concept_id)) { statement <- paste0(statement, " subject_concept_id IS NULL") } else { statement <- paste0(statement, " subject_concept_id = '", subject_concept_id,"'") } } if (!missing(cohort_instantiation_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_instantiation_date)) { statement <- paste0(statement, " cohort_instantiation_date IS NULL") } else { statement <- paste0(statement, " cohort_instantiation_date = '", cohort_instantiation_date,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_cohort_attribute <- function(rowCount, cohort_definition_id, cohort_start_date, cohort_end_date, subject_id, attribute_definition_id, value_as_number, value_as_concept_id) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect cohort_attribute' AS test, CASE WHEN(SELECT COUNT(*) FROM cohort_attribute WHERE") first <- TRUE if (!missing(cohort_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_definition_id)) { statement <- paste0(statement, " cohort_definition_id IS NULL") } else { statement <- paste0(statement, " cohort_definition_id = '", cohort_definition_id,"'") } } if (!missing(cohort_start_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_start_date)) { statement <- paste0(statement, " cohort_start_date IS NULL") } else { statement <- paste0(statement, " cohort_start_date = '", cohort_start_date,"'") } } if (!missing(cohort_end_date)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(cohort_end_date)) { statement <- paste0(statement, " cohort_end_date IS NULL") } else { statement <- paste0(statement, " cohort_end_date = '", cohort_end_date,"'") } } if (!missing(subject_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(subject_id)) { statement <- paste0(statement, " subject_id IS NULL") } else { statement <- paste0(statement, " subject_id = '", subject_id,"'") } } if (!missing(attribute_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_definition_id)) { statement <- paste0(statement, " attribute_definition_id IS NULL") } else { statement <- paste0(statement, " attribute_definition_id = '", attribute_definition_id,"'") } } if (!missing(value_as_number)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_number)) { statement <- paste0(statement, " value_as_number IS NULL") } else { statement <- paste0(statement, " value_as_number = '", value_as_number,"'") } } if (!missing(value_as_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(value_as_concept_id)) { statement <- paste0(statement, " value_as_concept_id IS NULL") } else { statement <- paste0(statement, " value_as_concept_id = '", value_as_concept_id,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) } expect_count_attribute_definition <- function(rowCount, attribute_definition_id, attribute_name, attribute_description, attribute_type_concept_id, attribute_syntax) { statement <- paste0("INSERT INTO test_results SELECT ", frameworkContext$testId, " AS id, '", frameworkContext$testDescription, "' AS description, 'Expect attribute_definition' AS test, CASE WHEN(SELECT COUNT(*) FROM attribute_definition WHERE") first <- TRUE if (!missing(attribute_definition_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_definition_id)) { statement <- paste0(statement, " attribute_definition_id IS NULL") } else { statement <- paste0(statement, " attribute_definition_id = '", attribute_definition_id,"'") } } if (!missing(attribute_name)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_name)) { statement <- paste0(statement, " attribute_name IS NULL") } else { statement <- paste0(statement, " attribute_name = '", attribute_name,"'") } } if (!missing(attribute_description)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_description)) { statement <- paste0(statement, " attribute_description IS NULL") } else { statement <- paste0(statement, " attribute_description = '", attribute_description,"'") } } if (!missing(attribute_type_concept_id)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_type_concept_id)) { statement <- paste0(statement, " attribute_type_concept_id IS NULL") } else { statement <- paste0(statement, " attribute_type_concept_id = '", attribute_type_concept_id,"'") } } if (!missing(attribute_syntax)) { if (first) { first <- FALSE } else { statement <- paste0(statement, " AND") } if (is.null(attribute_syntax)) { statement <- paste0(statement, " attribute_syntax IS NULL") } else { statement <- paste0(statement, " attribute_syntax = '", attribute_syntax,"'") } } statement <- paste0(statement, ") != ",rowCount ," THEN 'FAIL' ELSE 'PASS' END AS status;") frameworkContext$testSql = c(frameworkContext$testSql, statement); invisible(statement) }
77063e2dfec2a65c4ed7ee1dddd57f971cd91744
63083d152778be7c5e30d0ebc3e073d8a645e7eb
/tests/testthat/test-nearest_stations_ogimet.R
328c15063f8cee7ddcc61e9fe6b6882f685185cf
[]
no_license
cran/climate
0cf4e64785a87081773626b76e303cb295158b9f
ef0ccd4da3a94488674bd1be34ab1b402086b721
refs/heads/master
2022-08-19T10:18:59.929179
2022-08-09T15:00:11
2022-08-09T15:00:11
236,571,855
0
0
null
null
null
null
UTF-8
R
false
false
814
r
test-nearest_stations_ogimet.R
context("meteo_imgw") test_that("nearest_stations_ogimet works!", { x <- nearest_stations_ogimet(country = "United+Kingdom", point = c(10, 50), add_map = FALSE, no_of_stations = 10) x <- nearest_stations_ogimet(country = "United+Kingdom", point = c(10, 50), add_map = TRUE, no_of_stations = 10) x <- nearest_stations_ogimet(country = "United+Kingdom", point = c(-10, -50), add_map = TRUE, no_of_stations = 10) x <- nearest_stations_ogimet(country = "Poland", point = c(10, 50), add_map = TRUE, no_of_stations = 10) # expected error testthat::expect_error(nearest_stations_ogimet(country = "Pland", point = c(10, 50), add_map = TRUE, no_of_stations = 10)) x <- nearest_stations_ogimet(country = c("United+Kingdom", "Poland"), point = c(0, 0), add_map = TRUE, no_of_stations = 150) })
dd067c6f34bee0dae9f0e98edc8b49e5ced44525
6e1e34b7a10ceff84608053a4aaea1eed1ca98ea
/inst/app-visualize/ui/ui_bar_plot_1.R
e85375e72cd869e3709143dbeb36c7ca5968fc2d
[]
no_license
cran/xplorerr
c88cfe0f6ab1162fbc1b51aad949407dcd8352a7
b3f6db79da83568ad1ae89e657f3ccff94de43de
refs/heads/master
2021-06-08T06:09:44.106519
2021-05-21T03:50:02
2021-05-21T03:50:02
164,905,699
0
0
null
null
null
null
UTF-8
R
false
false
3,530
r
ui_bar_plot_1.R
tabPanel('Bar Plot', value = 'tab_bar_plot_1', fluidPage( fluidRow( column(12, align = 'left', h4('Bar Plot - I') ) ), hr(), fluidRow( column(12, tabsetPanel(type = 'tabs', tabPanel('plotly', fluidRow( column(2, selectInput('barly1_select_x', 'Variable: ', choices = "", selected = ""), textInput(inputId = "barly1_xlabel", label = "X Axes Label: ", value = "label"), textInput(inputId = "barly1_color", label = "Color: ", value = "blue") ), column(2, textInput(inputId = "barly1_title", label = "Title: ", value = "title"), textInput(inputId = "barly1_ylabel", label = "Y Axes Label: ", value = "label"), textInput(inputId = "barly1_btext", label = "Text: ", value = "") ), column(8, align = 'center', plotly::plotlyOutput('barly1_plot_1', height = '600px') ) ) ), tabPanel('rbokeh', fluidRow( column(2, selectInput('bobar1_select_x', 'Variable: ', choices = "", selected = ""), textInput(inputId = "bobar1_xlabel", label = "X Axes Label: ", value = "label"), textInput(inputId = "bobar1_color", label = "Color: ", value = ""), selectInput('bobar1_hover', 'Hover: ', choices = c("TRUE" = TRUE, "FALSE" = FALSE), selected = "TRUE" ), textInput(inputId = "bobar1_lcolor", label = "Line Color: ", value = ""), selectInput('bobar1_xgrid', 'X Axis Grid: ', choices = c("TRUE" = TRUE, "FALSE" = FALSE), selected = "TRUE" ) ), column(2, textInput(inputId = "bobar1_title", label = "Title: ", value = "title"), textInput(inputId = "bobar1_ylabel", label = "Y Axes Label: ", value = "label"), numericInput(inputId = "bobar1_alpha", label = "Alpha: ", value = 1, min = 0, max = 1, step = 0.1), numericInput(inputId = "bobar1_width", label = "Width: ", value = 0.9, min = 0, step = 0.1), numericInput(inputId = "bobar1_lalpha", label = "Line Alpha: ", value = 1, min = 0, max = 1, step = 0.1), selectInput('bobar1_ygrid', 'Y Axis Grid: ', choices = c("TRUE" = TRUE, "FALSE" = FALSE), selected = "TRUE" ) ), column(8, align = 'center', rbokeh::rbokehOutput('bobar1_plot_1', height = '600px') ) ) ), tabPanel('highcharts', fluidRow( column(2, selectInput('hibar1_select_x', 'Variable: ', choices = "", selected = ""), textInput(inputId = "hibar1_xlabel", label = "X Axes Label: ", value = "label") ), column(2, textInput(inputId = "hibar1_title", label = "Title: ", value = "title"), textInput(inputId = "hibar1_ylabel", label = "Y Axes Label: ", value = "label") ), column(8, align = 'center', highcharter::highchartOutput('hibar1_plot_1', height = '600px') ) ) ) ) ) ) ) )
158a5dae0f4092d6a95a81327486bf0f82c4a741
1d5d7db989e58b33420349b25831a1ed842f72d7
/12_barplots_pvalues.R
dff6c70250c3f2748a52cecfa2e0f83a3f8e5901
[ "MIT" ]
permissive
piquelab/murine_scRNA
b5aeae17800e1a2abb3f0467fe2fe664cc280c9e
fd293c575e6a261d7d33aa31be9cfab09ac98ec0
refs/heads/main
2023-04-17T19:08:03.768414
2022-11-18T17:07:33
2022-11-18T17:07:33
477,785,328
0
0
null
null
null
null
UTF-8
R
false
false
4,469
r
12_barplots_pvalues.R
library(Seurat) library(Matrix) library(tidyverse) library(future) library(harmony) ####################################################################### #cell count / DEGs comparison between E.coli and control ####################################################################### outFolder="12_comparison_DEGs_cellcounts/" system(paste0("mkdir -p ", outFolder)) future::plan(strategy = 'multicore', workers = 16) options(future.globals.maxSize = 30 * 1024 ^ 3) ########################################### # annotation cell.type.annotation<-read.delim("cell-type.annotation.txt") clust2Names<-cell.type.annotation$Cell.type clust2Names<-paste0(cell.type.annotation$Cluster,"_",clust2Names) names(clust2Names)<-cell.type.annotation$Cluster clust2Name<-cell.type.annotation$Cell.type clust2Name<-paste0(c(0:30),"_",clust2Name) names(clust2Name)<-c(0:30) # seurat obj sc <- read_rds("4_harmony_cellClass_soupx_doubletfinder_chrM/sc.NormByLibrary.cellclassify_newfilter-res0.5.2021-06-28.rds") ####################################### # cell count compariosn E.coli vs pbs ####################################### aa <- FetchData(sc,c("seurat_clusters","Location","Condition","status","Library")) aa$seurat_clusters <- clust2Name[aa$seurat_clusters] aa<-aa %>% mutate(Pregnancy_ID=str_match(Library,"[0-9]+")) # per location ccdiff_all<-lapply( unique(aa$Location),function(locationx){ #locationx <-"Myometrium" aa2<-aa %>% filter(Location==locationx) cc <- aa2 %>% group_by(seurat_clusters,Condition,Pregnancy_ID) %>% summarize(n=n()) %>% group_by(seurat_clusters) %>% mutate(p0=sum(n)/nrow(aa2)) %>% group_by(Pregnancy_ID) %>% mutate(nt=sum(n),p=n/nt,z=(p-p0)/sqrt(p0*(1-p0)*(1/nt+1/nrow(aa2)))) cluster_filter<-cc %>% group_by(seurat_clusters)%>% summarise(count_control=count(Condition=="Control"), count_ecoli=count(Condition=="E. coli"))%>% filter (count_control>=2 & count_ecoli>=2) %>% select (seurat_clusters) %>% unlist %>% unique() ccdiff <- cc %>% filter(seurat_clusters%in% cluster_filter) %>% group_by(seurat_clusters) %>% summarize(wilcox.pval = wilcox.test(p ~ Condition)$p.value, test.t = t.test(z ~ Condition)$statistic) %>% ungroup() %>% mutate(wilcox.padj = p.adjust(wilcox.pval)) ccdiff_filtered<-ccdiff %>% filter(wilcox.padj<0.1) #ccdiff$Location<-locationx # return(ccdiff_filtered) write.csv(ccdiff,file=paste0(outFolder,"/wilcox_result_cellcount_",locationx,".csv")) } ) ###################################################################### # up-regulated vs down-regulated ###################################################################### res <- read_tsv("./7_outputs_DESeq_ConditionsByCluster_res0.5/ALL.combined.2021-06-29.tsv") res<-res %>% filter(padj<0.1) res <- res %>% separate(cname,c("Location","Cell_type"),sep="_",remove=FALSE) res$Cell_type<-clust2Names[res$Cell_type] sc@meta.data$cluster_name <- clust2Names[sc@meta.data$seurat_clusters] binom.test.locs<-lapply( unique(aa$Location),function(locationx){ res_loc<-res %>% filter (Location==locationx) resDE<-res_loc %>% filter(padj<0.1 & !is.na(padj)) #single cell fdr 0.1 total<-table(resDE$Cell_type) res_up<-resDE%>%filter(log2FoldChange>0) upregulated<-rep(0,length(total)) names(upregulated)<-names(total) upregulated[names(table(res_up$Cell_type))]<-table(res_up$Cell_type) binom.test.res<-c() sc_loc<-subset(sc,Location==locationx) cell_counts<-table(sc_loc$cluster_name) for( x in unique(resDE$Cell_type)) { btest<-binom.test(upregulated[x],total[x],0.5) if(is.na(upregulated[x])) upregulated[x]<-0 rb<-as.numeric(c(cell_counts[x],upregulated[x], (total[x]-upregulated[x]),total[x],btest$p.value)) binom.test.res<-rbind(binom.test.res,rb) print(x) print(btest$p.value) } rownames(binom.test.res)<-unique(resDE$Cell_type) colnames(binom.test.res)<-c("Cell-counts","Up-regulated","Down-regulated","Total","P-value") binom.test.res<-as.data.frame(binom.test.res) binom.test.res$padj<-p.adjust(binom.test.res$`P-value`,"fdr") binom.test.res<-binom.test.res[order(binom.test.res[,"padj"],decreasing = FALSE),] binom.test.res$Location<-locationx write.csv(binom.test.res,file=paste0(outFolder,"binom.test.DEGs.",locationx,".csv")) return(binom.test.res) }) binom.test.all<-do.call(rbind,binom.test.locs)
f945b97b4b48d1a686241460f0973cc6c3b0b7ff
eedafd67512fc0146ee0d9d2910764978f541802
/man/count_map.Rd
d149b927d25bc56ccb06cb5d7c6f4aa2fa592a47
[ "MIT" ]
permissive
MSKCC-Epi-Bio/bstfun
e1e3925278d3f18ab62501bdc5930b4d2b768dd4
532465ec4a7097d8cf2e4aea50f0add44f361320
refs/heads/main
2023-06-27T13:02:47.872731
2023-06-26T18:04:43
2023-06-26T18:04:43
237,299,694
7
3
NOASSERTION
2023-06-26T18:04:45
2020-01-30T20:30:30
R
UTF-8
R
false
true
539
rd
count_map.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/count_map.R \name{count_map} \alias{count_map} \title{Check variable derivations} \usage{ count_map(data, ...) } \arguments{ \item{data}{data frame} \item{...}{sets of variables to check. variables that are checked together are included in the same vector. See example below.} } \description{ Function assists in checking the values of new, derived variables against the raw, source variables. } \examples{ count_map( mtcars, c(cyl, am), c(gear, carb) ) }
5eb4c2520ca1488fd39727e02e01de3252b7b710
967fedcd8b7636103273d344e9df41e48a1cc58d
/day16.R
d78a46f828767f5373c300c3f10ee1c7590eae4e
[]
no_license
HHoofs/AoC2020
8ee3205e0075c1284d7a36bead0b7520d084a92a
369591c8604693380b4eb28a85751d0e911d964c
refs/heads/main
2023-02-11T19:49:46.399255
2021-01-07T15:26:36
2021-01-07T15:26:36
319,048,608
1
0
null
null
null
null
UTF-8
R
false
false
2,222
r
day16.R
### Input -------------------------- inp = readLines('inp/day16_inp.txt') # Determine where the new entries start cuts = which(inp == '') # Retrieve entries rules = inp[1:(cuts[1]-1)] ticket = inp[(cuts[1]+2):(cuts[2]-1)] ticket = as.numeric(strsplit(ticket, ",")[[1]]) nearby_tickets = inp[(cuts[2]+2):(length(inp))] nearby_tickets = lapply(nearby_tickets, function(x) as.numeric(strsplit(x, ",")[[1]])) # Parse rules all_rules = list() for (rule in rules) { parsed_rule = strsplit(rule, ": ")[[1]] rule_range = c() for(min_max in strsplit(parsed_rule[[2]], " or ")[[1]]) { min_max_parsed = as.numeric(strsplit(min_max,'-')[[1]]) rule_range = c(rule_range, (min_max_parsed[1]:min_max_parsed[2])) } all_rules[[parsed_rule[1]]] = rule_range } ### Star 1 ------------ cat(paste('Solution to part 1 is:', sum(unlist(lapply(nearby_tickets, function(x) x[!x %in% unlist(all_rules)]))), sep='\n')) cat('\n====\n') ### Start 2 ----------- # Filter out invalid tickets nearby_tickets = nearby_tickets[which(unlist(lapply(nearby_tickets, function(x) length(x[!x %in% unlist(all_rules)]))) == 0)] # Retrieve all options for each information point in a ticket ticket_option = list() for(nearby_ticket in nearby_tickets){ ticket_option[[length(ticket_option) + 1]] = matrix(unlist(lapply(nearby_ticket, function(i) lapply(all_rules, function(x) any(x == i)))), ncol=length(all_rules), byrow = TRUE) } ticket_option = lapply(ticket_option, function(x) apply(x, 1, function(y) which(y))) valid_options = list() for(i in seq(length(all_rules))){ valid_options[[length(valid_options) + 1]] = Reduce(intersect,lapply(ticket_option, function(x) x[[i]])) } valid_option = valid_options while(TRUE){ singles = unlist(lapply(valid_option, function(x) length(x) == 1)) single_values = unlist(valid_option[singles]) valid_option = lapply(valid_option, function(x) { if(length(x) == 1){ x } else { x[!(x %in% single_values)] } }) if(all(unlist(lapply(valid_option, function(x) length(x) == 1)))){ break() } } cat(paste('Solution to part 2 is:', prod(ticket[which(unlist(valid_option) %in% c(1,2,3,4,5,6))]), sep='\n'))
a44d67202abc88176d4870069466a61f3f59b4e6
a7045f6708f8bd65a54a946a544682325a4ae004
/R/varRename.R
1ddffb0ffc81a1a9aa72b314c6fe3f540f4b47b6
[]
no_license
jjcurtin/lmSupport
a621e2a38211e4aacd4e41597d92df6ac303f97c
1ba8feed959abd9c01c7041f8457d775cb59bb24
refs/heads/main
2023-04-06T01:36:59.490682
2021-05-06T02:12:53
2021-05-06T02:12:53
364,758,953
2
0
null
null
null
null
UTF-8
R
false
false
499
r
varRename.R
varRename <- function(Data, From, To) #2010-10-11: released, JJC { if (length(From) != length(To)) stop("Length of 'From' and 'To' vectors must match") for (i in 1:length(From) ) { if(is.element(From[i], names(Data))){ if (!is.element(To[i],names(Data))) names(Data)[names(Data)==From[i]] = To[i] else stop('Variable name already exists in dataframe') } else warning (sprintf('Variable name does not exist: %s', From[i])) } return(Data) }
bf6d7f9148f03f6d8ca2eeed9c4729c6c0da1398
dfa07b04688eb0edf2869b26807c1c00e1d71949
/cursomultivarinble/primera_practica_R.R
c4de1e246a129089b44e0732ec3a62b97caf29c1
[]
no_license
gitaprendiendoaprogramar/diferentes_trabajos_R_PY
0964cecc406c368255032d537543d2539a567723
a0c89eb3f9164092558b0fec9f84987c0ed2bd6d
refs/heads/master
2023-01-21T11:23:14.289333
2020-12-01T14:26:03
2020-12-01T14:26:03
317,566,051
0
0
null
null
null
null
ISO-8859-2
R
false
false
5,908
r
primera_practica_R.R
iris <- data.frame(iris) write.csv(iris,"iris.csv") #################### iris <- iris[,2:6] dim(iris) ncol_iris <- dim(iris)[2] nrow_iris <- dim(iris)[1] #################### ######### BOXPLOTS par(mfrow=c(1,1)) ## hace divisiones del lienzo, por filas y columnas, el primero aon filas y el segundo columnas boxplot(iris[,1:4],main="titulo de lagrafica",xlab="etiqueta",col="blue") ## boxplot solo recive numericos.... # para documentacion # ? boxplot ######### colores <- c("blue", "red", "green", "yellow") cajas <- function(j){ ## crear una funcion que me haga un boxplot para cada columna boxplot(iris[,j],main=colnames(iris)[j],xlab="",col= colores[j]) } par(mfrow=c(2,2)) # divide el lienzo en dos por dos sapply(c(1:4),cajas) # sapply parece un for pero mas sofisticado # la familia de funciones aplay es muy importante en todo R ######## BOXPLOTS por especie cajas_especies <- function(j){ boxplot(iris[,j]~iris[,5],main=colnames(iris)[j],xlab="",col=colores[j]) } # ~ significa pero clasificada por par(mfrow=c(2,2)) sapply(c(1:4),cajas_especies)# repito funciona como un for, aplica la funcion cajas... a cada variable ######## BAGPLOTS #intall.packages("aplpack", depedence = T) #install.packages("aplpack") library(aplpack) par(mfrow=c(1,1)) bagplot(iris$Sepal.Length,iris$Sepal.Width, xlab="Longitud Sépalo", ylab="Ancho Sépalo", main="Bagplot") ######## HISTOGRAMAS par(mfrow=c(1,1)) hist(iris[,2],main = "Ejemplo de histograma", xlab="", col="blue", breaks = "Sturges")# con esto controlo el ancho de las vandas ######## histos <- function(x){ hist(iris[,x],main = colnames(iris)[x], xlab="", col="blue", breaks = "Sturges") } par(mfrow=c(2,2)) sapply(1:4,histos) ######## summary(iris$Species) setosa <- iris[iris$Species == "setosa",] versicolor <- iris[iris$Species == "versicolor",] virginica <- iris[iris$Species == "virginica",] par(mfrow=c(1,3)) hist(setosa[,1],main = "Setosa (sl)", xlab="",col="blue",breaks = "Sturges") hist(versicolor[,1],main = "Versicolor (sl)", xlab="",col="red",breaks = "Sturges") hist(virginica[,1],main = "Virginicia (sl)", xlab="",col="green",breaks = "Sturges") ######## DENSIDADES KERNEL den_ker <- function(x){ plot(density(iris[,x],kernel = "gaussian"), main = colnames(iris)[x],xlab="", col="blue",lwd=2) } par(mfrow=c(2,2)) sapply(1:4,den_ker) ######## install.packages("sm") library(sm) cyl.f <- factor(iris$Species, labels = unique(iris$Species)) par(mfrow=c(1,1)) sm.density.compare(iris$Sepal.Length,iris$Species) # sm.density.compare(columna, clasificador) colfill<-c(2:(2+length(levels(cyl.f)))) # con este codigo se pone la leyenda en el cursos, donde uno quiera legend(locator(1), levels(cyl.f),fill=colfill) ####### SCATTERPLOT library(ggplot2) ggplot(data = iris) + geom_point(mapping = aes(x=Sepal.Length,y=Petal.Length,color = Species),size=5,alpha=0.5)+ theme_bw() ######## Scatterplot 3d install.packages("scatterplot3d") library(scatterplot3d) # para hacer graficas en 3 D scatterplot3d(iris$Sepal.Length,iris$Petal.Length,iris$Petal.Width,pch=19,color=c("blue","green","orange")[iris[,5]]) scatterplot3d(iris$Sepal.Length,iris$Petal.Length,iris$Petal.Width,pch=19,color=c("blue","green","orange")[iris[,5]],type="h") ######## scatter matrix pairs(iris[,1:4],pch=19,col=c("blue","green","orange")[iris[,5]]) ####### COORDENADAS PARALELAS install.packages("MASS") library(MASS) parcoord(iris[,1:4],col=c("blue","green","orange")[iris[,5]]) # para controlar el orden de la columnas parcoord(iris[,c(1,3,2,4)],col=c("blue","green","orange")[iris[,5]], main = "Hola mundo de R") ############################################### ############################################### ######## Medidas descriptivas MEDIDAS DESCRIPTIVAS ############################################### ############################################### # medidas promedios de las la columnas que le de comer medias <- colMeans(iris[,1:4], na.rm = TRUE) medias[3] # tambien funciona para sumas, colSum() # para omitir los NA es na.rm = TRUE summary(iris) ### MEDIANA install.packages("Gmedian") # library(Gmedian) Gmedian(iris[,1:4]) medias Gmedian(iris[,c(1,2)]) par(mfrow=c(1,1)) plot(iris$Sepal.Length,iris$Sepal.Width,xlab="long sépalo",ylab="ancho sépalo",pch=19,col=c("blue","green","orange")[iris[,5]]) points(Gmedian(iris[,c(1,2)])[1],Gmedian(iris[,c(1,2)])[2],pch=19,col="red",lwd=10) ############################################## mediana_setosa <- Gmedian(setosa[,c(1,2)]) mediana_versicolor <- Gmedian(versicolor[,c(1,2)]) mediana_virginicia <- Gmedian(virginica[,c(1,2)]) par(mfrow=c(1,1)) plot(iris$Sepal.Length,iris$Sepal.Width,xlab="long sépalo",ylab="ancho sépalo",pch=19,col=c("blue","green","orange")[iris[,5]]) points(Gmedian(iris[,c(1,2)])[1],Gmedian(iris[,c(1,2)])[2],pch=19,col="yellow",lwd=10) points(Gmedian(setosa[,c(1,2)])[1],Gmedian(setosa[,c(1,2)])[2],pch=19,col="blue",lwd=10) points(Gmedian(versicolor[,c(1,2)])[1],Gmedian(versicolor[,c(1,2)])[2],pch=19,col="green",lwd=10) points(Gmedian(virginica[,c(1,2)])[1],Gmedian(virginica[,c(1,2)])[2],pch=19,col="red",lwd=10) ############################################# MATRIZ DE COVARIANZA Cov_iris <- cov(iris[,1:4]) Corr_iris <- cor(iris[,1:4]) install.packages("reshape2") library(reshape2) library(tidyverse) Corr_iris_arreglada <- melt(Corr_iris) # prepara los datos para que los pueda graficar melt Cov_iris_arreglada <- melt(Cov_iris) ggplot(data=Corr_iris_arreglada) + geom_tile(mapping = aes(x=Var2,y=Var1,fill=value)) ggplot(data=Cov_iris_arreglada) + geom_tile(mapping = aes(x=Var1,y=Var2,fill=value)) ############################################ ########## Referencia útil: ## https://rua.ua.es/dspace/bitstream/10045/69767/1/Modulo_4_-_Graficos_avanzados_con_ggplot2.pdf
726c6e848254e2ca0ae883feaa185fe3bb50f02e
ac727c693ba0899b59859a399f8dc3b6b3a5e01d
/man/Qaux.beta.Rd
cf4163cfb0b2fb02c547834996ac8a9562554039
[ "MIT" ]
permissive
htso/Hext
2fb2d3cb74e88fe032a0d6f82b6a1bb5a7f0a42e
8f4d99d20019a0bdd4522873ee20d758e2cb8187
refs/heads/master
2021-01-17T07:30:58.919595
2020-01-30T22:08:20
2020-01-30T22:08:20
83,738,303
0
0
null
null
null
null
UTF-8
R
false
true
437
rd
Qaux.beta.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/auxQ_func.R \name{Qaux.beta} \alias{Qaux.beta} \title{Compute EM Auxiliary Q function for beta distribution} \usage{ Qaux.beta(theta, x, wt) } \arguments{ \item{theta}{the shape parameters of beta distribution} \item{x}{numeric vector to evaluate Aux Q function} \item{wt}{weight vector} } \value{ numeric value of Aux Q function } \description{ See ref }
ff61f93638c047129984c46587179c2f84578901
b58c7bc0a6a611622634e883b17ddf188967695b
/ui.R
ee29f3f1afd9302a60c11f4254937df2d746b8eb
[]
no_license
jjames2/asthmacdc500citiesshinyapp
4cd5e7322a34c0caafedc8f4a0f696b052b6f2f1
b7440ba195c566308afc016d0a12ad92070a0637
refs/heads/master
2020-04-13T16:37:52.719343
2019-02-27T17:48:31
2019-02-27T17:48:31
163,326,176
0
0
null
null
null
null
UTF-8
R
false
false
1,407
r
ui.R
library(leaflet) choices <- c("Current Asthma", "Current Smoking", "Obesity") levels <- c("City", "Census Tract") tabPanel("Interactive map", div(class="outer", tags$head( # Include our custom CSS includeCSS("styles.css") ), # If not using custom CSS, set height of leafletOutput to a number instead of percent leafletOutput("map", width="100%", height="100%"), absolutePanel(id = "controls", class = "panel panel-default", fixed = TRUE, draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto", width = 330, height = "auto", h2("Asthma Data Explorer"), selectInput("geographicLevel", "Geographic Level", levels, selected = "City"), selectInput("colorBy", "Color", choices, selected = "Current Asthma"), selectInput("sizeBy", "Size", choices, selected = "Obesity"), sliderInput("circlesize", "Circle Size", min = 0, max = 100, value = 50), plotOutput("scatterplot", height = 250) )))
7a231f56ce29b26673950d3cac190a20f6c8e619
259421358681edd4ec4f9b8db2051a579a0380cf
/R/ocd_divisions.R
7f0c0d162901b00da095dc63addc1bc424c7c322
[ "MIT" ]
permissive
willdebras/googlecivic
df5493528dfe0865fc63ba4b2c0836a969c501b9
58bbbef3d5545c2f32dd7f2562a30e5aa5acebab
refs/heads/master
2021-08-16T14:13:00.459536
2021-02-10T20:32:55
2021-02-10T20:32:55
243,639,743
3
4
NOASSERTION
2020-04-19T18:32:24
2020-02-27T23:45:09
R
UTF-8
R
false
false
713
r
ocd_divisions.R
#' Open Civic Data Division Identifiers #' #' A data frame of Open Civic Data division identifiers. The IDs are suitable #' passing to Google Civic Information API's `representativeInfoByDivision` #' endpoint. Searching for relevant strings in `name` can help locate relevant #' IDs. #' #' @format A data frame with 193,493 row and 13 columns, including #' #' - id #' - name #' - sameAs #' - sameAsNote #' - validThrough #' - census_geoid #' - census_geoid_12 #' - census_geoid_14 #' - openstates_district #' - placeholder_id #' - sch_dist_stateid #' - state_id #' - validFrom #' #' @source [OpenCivicData](https://github.com/opencivicdata/ocd-division-ids/blob/master/identifiers/country-us.csv) "ocd_divisions"
a7024e2bc8fbc83c948ecb7ffb8b50e88be4d548
4124f2d134ae5dd7c907ae1214b709798db22d20
/program/pizzaNewton_update.R
1abf2be22131e3b39257568f482aa96dfe9cf641
[]
no_license
hsssgddtc/pizzaPred
2bfb55afc6929e74333c6f79071dac6943feae40
579bbdf2a76885d9954dd3989497db05a4bb5f9c
refs/heads/master
2016-09-06T03:47:21.616516
2014-06-26T14:54:26
2014-06-26T14:54:26
null
0
0
null
null
null
null
UTF-8
R
false
false
1,867
r
pizzaNewton_update.R
setwd("G:\\Project\\R\\Workspace") rm(list=ls()) library(matlab) load_data <- function(){ X_train <<- read.table("data/X.dat",header=F,sep=""); y_train <<- read.table("data/y.dat",header=F,sep=""); } repmat <- function(X,m,n){ ##R equivalent of repmat (matlab) mx = dim(X)[1] nx = dim(X)[2] matrix(t(matrix(X,mx,nx*n)),mx*m,nx*n,byrow=T) } lwlr <- function(X,y,x,tau){ m = nrow(X)/nrow(x); n = ncol(X)/ncol(x); theta = matrix(0,ncol(X),1); X = as.matrix(X); x = as.matrix(x); #compute weights #w = as.matrix(exp(as.matrix(-rowSums((X-repmat(x,m,n))^2)) / (2*tau))); w = as.matrix(exp(as.matrix(-rowSums((X-x)^2)) / (2*tau))); #perform Newton's method g = matrix(1,n,1); while(norm(g) > 1e-6){ h = 1 / (1+exp(-X %*% theta)); g = t(X) %*% (w * as.matrix(y - h)) - 1e-4*theta; H = -t(X) %*% diag(as.vector(w*h*(1-h))) %*% X - 1e-4*diag(ncol(X)); theta = theta - solve(H) %*% g; } #return predicted new y return(as.double(x%*%theta-10)); } plot_lwlr <- function(X,y,tau,res){ x = matrix(0,2,1); pred = matrix(0,res,res); for(i in 1:res){ for(j in 1:res){ x[1] = 2*(i-1)/(res-1) - 1; x[2] = 2*(j-1)/(res-1) - 1; pred[j,i] = lwlr(X,y,x,tau); } } imagesc(pred,main=paste("tau=",tau)) } par(mfrow=c(2,3)) load_data() pred <- lwlr(subPizzaReddit_X,subPizzaReddit_y,subPizzaReddit_X,0.01); pizzaReddit <- cbind(pizzaReddit,pred) pizzaReddit$pre <- ifelse(pizzaReddit$requester_received_pizza,1,0) p <- subset(pizzaReddit,pizzaReddit$request_id %in% pizzaReddit_test$request_id ,c("request_id","pred","pre")) sum(ifelse(p$pre == p$pred,1,0))/nrow(p) names(p) <- c("request_id","requester_received_pizza","Real Value") write.csv(p,"G:\\Project\\GitHub\\pizzaPred\\data\\result.csv",row.names=F)
8ea1ac8fc6c6f8ad7912ef23dd7adbde016f7f0b
d0bde1b4c9396b13252c0f1f7fbceb49887ff155
/R/saveOutReports.R
2128c8d31dcc948779df52e073f42e672dfcbc4c
[]
no_license
bpb824/orcycler
eec3335cc07bea7f3e2f1620145fcdb6d6fe5f73
22f571100905c322a291283e33d404509f97d077
refs/heads/master
2021-01-01T05:48:22.208599
2015-10-18T21:16:05
2015-10-18T21:16:05
42,019,202
0
0
null
null
null
null
UTF-8
R
false
false
2,173
r
saveOutReports.R
#' Save Report Summary to Excel #' #' @param crashSummary Crash report summary table #' @param issueSummary Issue report summary table #' @param notes Note table from SQL database #' @param saveFolder Relative or Absolute path to output folder #' #' @return None #' @export saveReportsToExcel=function(crashSummary,issueSummary,notes,saveFolder){ crashSheet = data.frame(matrix(nrow=nrow(crashSummary),ncol = ncol(crashSummary)+3)) colnames(crashSheet)=c("latitude","longitude","googleLink",colnames(crashSummary)) crashSheet$latitude = notes$latitude[notes$id %in% crashSummary$note_id] crashSheet$longitude = notes$longitude[notes$id %in% crashSummary$note_id] crashSheet$googleLink = paste0("http://maps.google.com/maps?q=",crashSheet$latitude,",",crashSheet$longitude,"&ll=",crashSheet$latitude,",",crashSheet$longitude,"&z=16") crashSheet[,colnames(crashSummary)]=crashSummary issueSheet = data.frame(matrix(nrow=nrow(issueSummary),ncol = ncol(issueSummary)+3)) colnames(issueSheet)=c("latitude","longitude","googleLink",colnames(issueSummary)) issueSheet$latitude = notes$latitude[notes$id %in% issueSummary$note_id] issueSheet$longitude = notes$longitude[notes$id %in% issueSummary$note_id] issueSheet$googleLink = paste0("http://maps.google.com/maps?q=",issueSheet$latitude,",",issueSheet$longitude,"&ll=",issueSheet$latitude,",",issueSheet$longitude,"&z=16") issueSheet[,colnames(issueSummary)]=issueSummary ###Function code taken from http://www.r-bloggers.com/quickly-export-multiple-r-objects-to-an-excel-workbook/ save.xlsx <- function (file, ...) { require(xlsx, quietly = TRUE) objects <- list(...) fargs <- as.list(match.call(expand.dots = TRUE)) objnames <- as.character(fargs)[-c(1, 2)] nobjects <- length(objects) for (i in 1:nobjects) { if (i == 1) write.xlsx(objects[[i]], file, sheetName = objnames[i],row.names = FALSE) else write.xlsx(objects[[i]], file, sheetName = objnames[i], append = TRUE) } print(paste("Workbook", file, "has", nobjects, "worksheets.")) } save.xlsx(paste0(saveFolder,"/reportSheet.xlsx"),crashSheet,issueSheet) }
7224add7651523fb48a3060a3f9224cf7791c927
bb8f4d4f7c52259fb58b99a0a956ec3e57e14410
/Ltac_shiny/app.R
b00e46fa83b098b2b2ff976a24a08970826d9ba8
[]
no_license
mirjamlaager/Ltac_simulations
ef4d65c75e33e3311cb68d9f3029f1c3a2b9be20
6413de6c96eb28ca89e0ce2bc0f22914c78e523f
refs/heads/master
2021-10-16T15:07:22.950538
2019-02-11T19:16:07
2019-02-11T19:16:07
168,308,713
0
0
null
null
null
null
UTF-8
R
false
false
12,235
r
app.R
library(shiny) library(shinythemes) source("run_simulations_shiny.R") library(ggplot2) library(gtable) ui <- fluidPage(theme = shinytheme("journal"), title = "Long Time Acute Care Simulations", titlePanel("Long Time Acute Care Simulations"), fluidRow( column(3, h3("Baseline Scenario"), p("This is the baseline scenario.") ), column(3, h3("Scenario 1"), p("This is scenario 1.") ) ), fluidRow( column(3, h4("Ward Setup Baseline"), sliderInput("n_standard_wards_baseline", "Number of standard wards:", min = 1,max = 10,value = 7), sliderInput("beds_per_standard_ward_baseline", "Number of beds per standard ward:", min = 1,max = 20,value = 15), sliderInput("n_ltac_wards_baseline", "Number of ltac wards:", min = 0,max = 5,value = 0), sliderInput("beds_per_ltac_ward_baseline", "Number of beds per ltac ward:", min = 1,max = 20,value = 5), sliderInput("mean_length_of_stay_baseline", "Mean length of stay:", min = 1,max = 14,value = 4) ), column(3, h4("Ward Setup Scenario 1"), sliderInput("n_standard_wards_s1", "Number of standard wards:", min = 1,max = 10,value = 5), sliderInput("beds_per_standard_ward_s1", "Number of beds per standard ward:", min = 1,max = 20,value = 15), sliderInput("n_ltac_wards_s1", "Number of ltac wards:", min = 0,max = 5,value = 2), sliderInput("beds_per_ltac_ward_s1", "Number of beds per ltac ward:", min = 1,max = 20,value = 15), sliderInput("mean_length_of_stay_s1", "Mean length of stay:", min = 1,max = 14,value = 4) ), column(6, plotOutput("distPlot") ) ), fluidRow( column(3, h4("Transmission Setup Baseline"), sliderInput("within_ward_transmission_rate_baseline", "within ward transmission rate:", min = 0,max = 0.2,value = 0.02,step=0.001), sliderInput("importation_probability_baseline", "proportion positive on admission:", min = 0,max = 1,value = 0.1,step=0.01) ), column(3, h4("Transmission Setup Scenario 1"), sliderInput("within_ward_transmission_rate_s1", "within ward transmission rate:", min = 0,max = 0.2,value = 0.02,step=0.001), sliderInput("importation_probability_s1", "proportion positive on admission:", min = 0,max = 1,value = 0.1,step=0.01) ) ), fluidRow( column(10, h3("Simulation Setup"), sliderInput("n_days", "Number of days:", min = 1,max = 500,value = 50,step=10), sliderInput("n_runs", "Number of simulation runs:", min = 1,max = 100,value = 20), actionButton("goButton", "Run Simulations")) ) ) # Define server logic required to draw a histogram server <- function(input, output) { output$distPlot <- renderPlot({ if (input$goButton == 0) return() input$goButton isolate({ n_patients_baseline <- rep(0,input$n_runs) n_patients_short_baseline <- rep(0,input$n_runs) n_patients_medium_baseline <- rep(0,input$n_runs) n_patients_long_baseline <- rep(0,input$n_runs) n_bed_days_standard_ward_baseline <-rep(0,input$n_runs) n_bed_days_ltac_ward_baseline <- rep(1,input$n_runs) n_patients_s1 <- rep(0,input$n_runs) n_patients_short_s1 <- rep(0,input$n_runs) n_patients_medium_s1 <- rep(0,input$n_runs) n_patients_long_s1 <- rep(0,input$n_runs) n_bed_days_standard_ward_s1 <-rep(0,input$n_runs) n_bed_days_ltac_ward_s1 <- rep(0,input$n_runs) col_while_in_standard_ward_baseline <- rep(0,input$n_runs) col_while_in_standard_ward_s1 <- rep(0,input$n_runs) col_while_in_ltac_ward_baseline <- rep(0,input$n_runs) col_while_in_ltac_ward_s1 <- rep(0,input$n_runs) col_and_short_stay_baseline <- rep(0,input$n_runs) col_and_medium_stay_baseline <- rep(0,input$n_runs) col_and_long_stay_baseline <- rep(0,input$n_runs) col_and_short_stay_s1 <- rep(0,input$n_runs) col_and_medium_stay_s1 <- rep(0,input$n_runs) col_and_long_stay_s1 <- rep(0,input$n_runs) withProgress(message = 'Running Baseline', value = 0, { for (k in 1:input$n_runs){ simulation_output <- run_simulations_shiny(input$n_standard_wards_baseline, input$n_ltac_wards_baseline, input$beds_per_standard_ward_baseline, input$beds_per_ltac_ward_baseline, input$n_days, input$mean_length_of_stay_baseline,input$importation_probability_baseline, input$within_ward_transmission_rate_baseline) ptLog <- as.data.frame(simulation_output[1]) wardLog <- as.data.frame(simulation_output[2]) n_patients_baseline[k] <- nrow(ptLog) n_bed_days_standard_ward_baseline[k] <- sum(pmin(ptLog$discharge,ptLog$transfer_to_ltac,na.rm = T) - ptLog$admission +1) col_while_in_standard_ward_baseline[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & (is.na(ptLog$transfer_to_ltac) | ptLog$colonisation <= ptLog$transfer_to_ltac)) n_patients_short_baseline[k] <- sum(ptLog$discharge - ptLog$admission <= 2) n_patients_medium_baseline[k] <- sum(ptLog$discharge - ptLog$admission > 2 & ptLog$discharge - ptLog$admission <= 7) n_patients_long_baseline[k] <- sum( ptLog$discharge - ptLog$admission > 7) col_and_short_stay_baseline[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & ptLog$discharge - ptLog$admission <=2) col_and_medium_stay_baseline[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & ptLog$discharge - ptLog$admission >2 &ptLog$discharge - ptLog$admission <=7 ) col_and_long_stay_baseline[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & ptLog$discharge - ptLog$admission >7) incProgress(1/input$n_runs, detail = paste("Simulation", k)) } }) withProgress(message = 'Running Scenario 1', value = 0, { for (k in 1:input$n_runs){ simulation_output <- run_simulations_shiny(input$n_standard_wards_s1, input$n_ltac_wards_s1, input$beds_per_standard_ward_s1, input$beds_per_ltac_ward_s1, input$n_days, input$mean_length_of_stay_s1,input$importation_probability_s1, input$within_ward_transmission_rate_s1) ptLog <- as.data.frame(simulation_output[1]) wardLog <- as.data.frame(simulation_output[2]) n_patients_s1[k] <- nrow(ptLog) n_bed_days_standard_ward_s1[k] <- sum(pmin(ptLog$discharge,ptLog$transfer_to_ltac,na.rm = T) - ptLog$admission +1) n_bed_days_ltac_ward_s1[k] <- sum(ptLog$discharge - ptLog$transfer_to_ltac,na.rm = T) col_while_in_standard_ward_s1[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & (is.na(ptLog$transfer_to_ltac) | ptLog$colonisation <= ptLog$transfer_to_ltac)) col_while_in_ltac_ward_s1[k] <- sum(is.na(ptLog$ltac_ward)==FALSE & ptLog$colonisation > ptLog$transfer_to_ltac & + ptLog$discharge >= ptLog$colonisation) n_patients_short_s1[k] <- sum(ptLog$discharge - ptLog$admission <= 2) n_patients_medium_s1[k] <- sum(ptLog$discharge - ptLog$admission > 2 & ptLog$discharge - ptLog$admission <= 7) n_patients_long_s1[k] <- sum( ptLog$discharge - ptLog$admission > 7) col_and_short_stay_s1[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & ptLog$discharge - ptLog$admission <=2) col_and_medium_stay_s1[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & ptLog$discharge - ptLog$admission >2 &ptLog$discharge - ptLog$admission <=7 ) col_and_long_stay_s1[k] <- sum(ptLog$colonisation >= ptLog$admission & ptLog$colonisation <= ptLog$discharge & ptLog$discharge - ptLog$admission >7) incProgress(1/input$n_runs, detail = paste("Simulation", k)) } }) #plot acquisitions per patient in the different groups scenarios <- rep(c("baseline","scenario 1"),each=(input$n_runs)*4) subgroup <- rep(c("0 - 3","4 - 7","8+","total","0 - 3","4 - 7","8+","total"),each=input$n_runs) proportion <- c(col_and_short_stay_baseline/n_patients_short_baseline,col_and_medium_stay_baseline/n_patients_medium_baseline, col_and_long_stay_baseline/n_patients_long_baseline,(col_while_in_standard_ward_baseline+col_while_in_ltac_ward_baseline)/n_patients_baseline, col_and_short_stay_s1/n_patients_short_s1, col_and_medium_stay_s1/n_patients_medium_s1, col_and_long_stay_s1/n_patients_long_s1, (col_while_in_ltac_ward_s1+col_while_in_standard_ward_s1)/n_patients_s1) data <- data.frame(scenarios, subgroup, proportion) ggplot(data, aes(x=scenarios, y=proportion, fill=subgroup)) + geom_boxplot() + ylab("acquisionts/patients") + ggtitle("acquisitions by length of stay") }) }) } # Run the application shinyApp(ui = ui, server = server)
c512530a5544c54d3c88b02a21b5cd6c84fbd3cb
8865b563ebd8d1d9d045e04c9686ce46970ab3a1
/notes/reese_code.R
2141396aa25d2be22eb43dc1088dbcfc25e9447b
[]
no_license
zachmwhite/research
6ffa3c877b670199aad547dff5ba410a19322375
e1efc6be8ebdbc89d44a4b417577aac02245b825
refs/heads/master
2020-07-19T06:00:58.806225
2018-03-11T01:37:39
2018-03-11T01:37:39
94,335,281
0
0
null
null
null
null
UTF-8
R
false
false
4,143
r
reese_code.R
# Basic GP code. Stolen shamelessly form Dr. Reese at BYU. https://madison.byu.edu/bayes/OurGP.R library(MASS) #################### nreal<-50 np<-1000 phi10<-0.5 xx<-seq(0,1,length=np) dd<-dist(xx,upper=T,diag=T)^2 Sig<-exp(-phi10*as.matrix(dd)) gpreal<-mvrnorm(nreal,rep(0,np),Sig) matplot(t(gpreal),type="l",main=expression(paste(phi,'=',phi10))) ######################## mysimfunc<-function(x){ out<-16*x^2*(1-x)^2 out[x>=0.7]<- out[x>=0.7] +32*(x[x>=0.7]-0.7)^3 return(out) } nrep<-1000 ndat<-6 np<-100 mydatx<-runif(ndat) #mydatx<-seq(0,1,length=ndat) mydaty<-mysimfunc(mydatx)+rnorm(length(mydatx),0,sqrt(0.01)) phi<-10 xx<-seq(0,1,length=np) dd<-dist(xx,upper=T,diag=T) Sig<-exp(-phi*as.matrix(dd^2)) yy<-mvrnorm(20,rep(0,np),Sig) matplot(t(yy),type="l") Sigxx<-exp(-phi*as.matrix(dist(mydatx,upper=T,diag=T)^2)) mypostmean<-rep(0,np) signoise<-0.01 smallk1<-matrix(0,ncol=np,nrow=ndat) smallk2<-matrix(0,ncol=ndat,nrow=np) for(i in 1:np){ smallk1[,i]<-exp(-phi*(xx[i]-mydatx)^2) } for(i in 1:ndat){ smallk2[,i]<-exp(-phi*(mydatx[i]-xx)^2) } covinv<-solve(Sigxx+diag(signoise,ndat)) mumat<-t(smallk1)%*%covinv%*%mydaty sigmat<-Sig-t(smallk1)%*%covinv%*%t(smallk2) yfit<-mvrnorm(nrep,mumat,sigmat) meany<-apply(yfit,2,mean) plot(mydatx,mydaty,pch=1,cex=2.5,xlim=c(0,1),ylim=c(0,2)) for(i in 1:nrep){ lines(xx,yfit[i,],col="lightgray") } lines(xx,meany,col="blue",lwd=3) points(mydatx,mydaty,pch=1,cex=1.8) ####################### mysimfunc<-function(x){ out<-16*x^2*(1-x)^2 out[x>=0.7]<- out[x>=0.7] +32*(x[x>=0.7]-0.7)^3 out<-out+rnorm(length(x),0,.01) return(out) } #phi<-10 np<-50 xx<-seq(0,1,length=np) dd<-dist(xx,upper=T,diag=T) #Sig<-exp(-phi[i-1]*as.matrix(dd^2)) #yy<-mvrnorm(20,rep(0,np),Sig) #matplot(t(yy),type="l") nrep<-1000 ndat<-6 mydatx<-runif(ndat) mydaty<-mysimfunc(mydatx) mypostmean<-rep(0,np) smallk1<-matrix(0,ncol=np,nrow=ndat) smallk2<-matrix(0,ncol=ndat,nrow=np) niter<-100 signoise<-rep(0.000001,niter) phi<-rep(10,niter) ar.phi<-ar.sig<-0 cs.phi<-0.001 cs.sig<-0.001 for(i in 2:niter){ Sigxx<-exp(-phi[i-1]*as.matrix(dist(mydatx,upper=T,diag=T)^2)) Sig<-exp(-phi[i-1]*as.matrix(dd^2)) for(j in 1:np){ smallk1[,j]<-exp(-phi[i-1]*(xx[j]-mydatx)^2) } for(j in 1:ndat){ smallk2[,j]<-exp(-phi[i-1]*(mydatx[j]-xx)^2) } covinv<-solve(Sigxx+diag(signoise[i-1],ndat)) mumat<-t(smallk1)%*%covinv%*%mydaty sigmat<-Sig-t(smallk1)%*%covinv%*%t(smallk2) yfit<-mvrnorm(1,mumat,sigmat) #METROPOLIS HASTINGS FOR PHI phi[i]<-phi[i-1] llo<--np/2*det(sigmat,log=T)-0.5*t(yfit-mumat)%*%solve(sigmat)%*%(yfit-mumat)+dgamma(phi[i],10,1,log=T) cand<-rnorm(1,phi[i-1],cs.phi) Sigxx<-exp(-cand*as.matrix(dist(mydatx,upper=T,diag=T)^2)) Sig<-exp(-cand*as.matrix(dd^2)) for(i in 1:np){ smallk1[,i]<-exp(-cand*(xx[i]-mydatx)^2) } for(i in 1:ndat){ smallk2[,i]<-exp(-cand*(mydatx[i]-xx)^2) } covinv<-solve(Sigxx+diag(signoise[i-1],ndat)) mumat<-t(smallk1)%*%covinv%*%mydaty sigmat<-Sig-t(smallk1)%*%covinv%*%t(smallk2) lln<--np/2*det(sigmat,log=T)-0.5*t(yfit-mumat)%*%solve(sigmat)%*%(yfit-mumat)+dgamma(cand,10,1,log=T) if((lln-llo)>log(runif(1))){phi[i]<-cand;ar.phi<-ar.phi+1} #METROPOLIS HASTINGS FOR PHI signoise[i]<-signoise[i-1] llo<--np/2*det(sigmat,log=T)-0.5*t(yfit-mumat)%*%solve(sigmat)%*%(yfit-mumat)+dgamma(phi[i],10,1,log=T) cand<-rnorm(1,signoise[i-1],cs.sig) Sigxx<-exp(-phi[i]*as.matrix(dist(mydatx,upper=T,diag=T)^2)) Sig<-exp(-phi[i]*as.matrix(dd^2)) for(i in 1:np){ smallk1[,i]<-exp(-phi[i]*(xx[i]-mydatx)^2) } for(i in 1:ndat){ smallk2[,i]<-exp(-phi[i]*(mydatx[i]-xx)^2) } covinv<-solve(Sigxx+diag(signoise[i],ndat)) mumat<-t(smallk1)%*%covinv%*%mydaty sigmat<-Sig-t(smallk1)%*%covinv%*%t(smallk2) lln<--np/2*det(sigmat,log=T)-0.5*t(yfit-mumat)%*%solve(sigmat)%*%(yfit-mumat)+dgamma(cand,10,1,log=T) if((lln-llo)>log(runif(1))){signoise[i]<-cand;ar.sig<-ar.sig+1} } meany<-apply(yfit,2,mean) plot(mydatx,mydaty,pch=1,cex=2.5,xlim=c(0,1),ylim=c(0,2)) for(i in 1:nrep){ lines(xx,yfit[i,],col="lightgray") } lines(xx,meany,col="blue",lwd=3)
977e757b493abf8e4322f4609113f3d8031d0ecf
302489278ac5ba1ce25c60a23f22043044dc08e0
/R/calculate_csi.R
38be693101367a64687b5f36490d205f5a0ef2c9
[]
no_license
crsky1023/scFunctions
8bab4a8643dcaab45ed067d64f9ff6ae8a2658f3
07c34da4db10d63d8123b21685d8974f98740948
refs/heads/master
2023-05-06T16:38:03.623814
2021-05-28T14:42:16
2021-05-28T14:42:16
null
0
0
null
null
null
null
UTF-8
R
false
false
2,519
r
calculate_csi.R
#' Calculates CSI values for all regulon pairs #' #' @param regulonAUC The AUC values for all regulons as calculated by SCENIC (content of file:3.4_regulonAUC.Rds). #' @keywords SCENIC, regulons, binary activity, kmeans, thresholds #' @import SCENIC #' @import tidyverse #' @import svMisc #' @export #' @examples #' \donttest{ #' regulon_thresholds <- auc_thresh_kmeans(regulonAUC) #' } calculate_csi <- function(regulonAUC, calc_extended = FALSE, verbose = FALSE){ compare_pcc <- function(vector_of_pcc,pcc){ pcc_larger <- length(vector_of_pcc[vector_of_pcc > pcc]) if(pcc_larger == length(vector_of_pcc)){ return(0) }else{ return(length(vector_of_pcc)) } } calc_csi <- function(reg,reg2,pearson_cor){ test_cor <- pearson_cor[reg,reg2] total_n <- ncol(pearson_cor) pearson_cor_sub <- subset(pearson_cor,rownames(pearson_cor) == reg | rownames(pearson_cor) == reg2) sums <- apply(pearson_cor_sub,MARGIN = 2, FUN = compare_pcc, pcc = test_cor) fraction_lower <- length(sums[sums == nrow(pearson_cor_sub)]) / total_n return(fraction_lower) } regulonAUC_sub <- regulonAUC@assays@data@listData$AUC if(calc_extended == TRUE){ regulonAUC_sub <- subset(regulonAUC_sub,grepl("extended",rownames(regulonAUC_sub))) } else if (calc_extended == FALSE){ regulonAUC_sub <- subset(regulonAUC_sub,!grepl("extended",rownames(regulonAUC_sub))) } regulonAUC_sub <- t(regulonAUC_sub) pearson_cor <- cor(regulonAUC_sub) pearson_cor_df <- as.data.frame(pearson_cor) pearson_cor_df$regulon_1 <- rownames(pearson_cor_df) pearson_cor_long <- pearson_cor_df %>% gather(regulon_2,pcc,-regulon_1) %>% mutate("regulon_pair" = paste(regulon_1,regulon_2,sep="_")) regulon_names <- unique(colnames(pearson_cor)) num_of_calculations <- length(regulon_names)*length(regulon_names) csi_regulons <- data.frame(matrix(nrow=num_of_calculations,ncol = 3)) colnames(csi_regulons) <- c("regulon_1", "regulon_2", "CSI") num_regulons <- length(regulon_names) f <- 0 for(reg in regulon_names){ ## Check if user wants to print info if(verbose == TRUE){ print(reg) } for(reg2 in regulon_names){ f <- f + 1 fraction_lower <- calc_csi(reg,reg2,pearson_cor) csi_regulons[f,] <- c(reg,reg2,fraction_lower) } } csi_regulons$CSI <- as.numeric(csi_regulons$CSI) return(csi_regulons) }
a8d5639adbe04487024cce1b44eb7645a8a14082
216b7cbdcd61f0cdfc5a8f74e8a24d68b56c3057
/R_scripts/which_grid_cell_function.R
4da5e3193986c82a185c623deb4e80f90a17e04e
[]
no_license
Preetis17/CapstoneProject
7e0ebb9e02958ea100cc8153e625b4fe27644997
c026bc5369b77d9d46ffffb2f5f7c629d62ea4ad
refs/heads/master
2020-03-23T01:08:46.791202
2018-12-13T01:26:08
2018-12-13T01:26:08
140,902,835
0
2
null
2018-12-12T04:50:34
2018-07-14T00:07:43
Jupyter Notebook
UTF-8
R
false
false
2,311
r
which_grid_cell_function.R
# ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # ... file : which_grid_cell_function.R # ... # ... find closest grid point (cell centroid) to data value location # ... # ... ref : https://stackoverflow.com/questions/21977720/ # ... r-finding-closest-neighboring-point-and-number-of-neighbors-within-a-given-rad # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # ... 21-sep-2018 # ... # ... patrick.mcdevitt@smu.edu # ... # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- library(sp) library(rgeos) library(geosphere) library(dplyr) library(tictoc) printf <- function(...) invisible(cat(sprintf(...))) which_grid_cell <- function(grid_centroid, df_to_map) { # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # ... transform to spatial objects # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- sp.df_to_map <- df_to_map coordinates(sp.df_to_map) <- ~long+lat sp.grid_centroid <- grid_centroid coordinates(sp.grid_centroid) <- ~long+lat # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # ... calculate distance pairs between all point pairs # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- dist_pair <- gDistance(sp.grid_centroid, sp.df_to_map, byid = TRUE) # ... mid distance is closest point min_dist <- apply(dist_pair, 1, function(x) order(x, decreasing = FALSE)[1]) # ... define corresponding columns from grid data frame dist <- dist_pair[min_dist] cell_id <- grid_centroid[min_dist, 3] lat_cell <- grid_centroid[min_dist, 4] long_cell <- grid_centroid[min_dist, 5] hood <- grid_centroid[min_dist, 9] hood_id <- grid_centroid[min_dist, 10] # ... new data frame ... all prior columns + grid centroid identifiers and coords df_mapped_to_grid <- cbind(df_to_map, dist, cell_id, lat_cell, long_cell, hood, hood_id) return (df_mapped_to_grid) } # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # ... end_of_file # ... -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
0323fb28fde07c23a37472c2fee26c0ae6c591fb
fe0ee8318230706a087eb33e98b32e2c7e9e3af1
/plot4.R
44e2db97eb4bd813e1f702b91193cecb010aa3da
[]
no_license
maxmoro/ExData_Plotting1
181965fd26aeaba71be2770db93e6dbed1783327
e0906916f1c0feae67d4c9cdbddb9f2ad7eea427
refs/heads/master
2021-01-18T03:10:15.945974
2014-11-08T16:09:12
2014-11-08T16:09:12
26,354,655
1
0
null
null
null
null
UTF-8
R
false
false
1,304
r
plot4.R
#Read full file exdata-data-household_power_consumption.zip saved in the workdir file=unz("exdata-data-household_power_consumption.zip","household_power_consumption.txt") DTOri=read.csv(file,sep=";",na.string="?") #subset file and create full_date DT=subset(DTOri,Date %in% c("1/2/2007","2/2/2007")) DT$Full_Date=strptime(paste(DT$Date,DT$Time),format="%d/%m/%Y %H:%M:%S") #open dev and set parameters png(file="plot4.png",width=480,height=480) par(ps=12) par(mfrow = c(2, 2)) #plot1 plot(DT$Full_Date, DT$Global_active_power, type = "l", ylab = "Global Active Power", xlab = '') #plot2 plot(DT$Full_Date, DT$Voltage, type = "l", xlab = "datetime",ylab = "Voltage") #plot3 plot(DT$Full_Date, DT$Sub_metering_1, type = "l", col = "black", ylab = "Energy sub metering", xlab = "") points(DT$Full_Date, DT$Sub_metering_2, type = "l", col = "red" , xlab = "", ylab = "Sub_metering_2") points(DT$Full_Date, DT$Sub_metering_3, type = "l", col = "blue", xlab = "", ylab = "Sub_metering_3") legend("topright", lty = 1, col = c("black", "red", "blue"), legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), bty = "n",xjust = 1, yjust = 1) #plot4 plot(DT$Full_Date, DT$Global_reactive_power, type = "l", xlab = "datetime", ylab = "Global_reactive_power", ylim = c(0, 0.5)) #close device dev.off()
0f00d21b65fc7414b65fe4326b9ae2af4870f573
5bd4b82811be11bcf9dd855e871ce8a77af7442f
/kinship/inst/tests/test/chtest.R
0cbe5c76484dd29d9a8b5491050cc5dd07f6f924
[]
no_license
jinghuazhao/R
a1de5df9edd46e53b9dc90090dec0bd06ee10c52
8269532031fd57097674a9539493d418a342907c
refs/heads/master
2023-08-27T07:14:59.397913
2023-08-21T16:35:51
2023-08-21T16:35:51
61,349,892
10
8
null
2022-11-24T11:25:51
2016-06-17T06:11:36
R
UTF-8
R
false
false
1,097
r
chtest.R
# # Test out the Cholesky # aeq <- function(x,y) all.equal(as.vector(x), as.vector(y)) tmat <- bdsmatrix(c(3,2,2,4), c(22,1,2,21,3,20,19,4,18,17,5,16,15,6,7, 8,14,9,10,13,11,12), matrix(c(1,0,1,1,0,0,1,1,0,1,0,10,0, 0,1,1,0,1,1,0,1,1,0,1,0,10), ncol=2)) dimnames(tmat) <- list(NULL, letters[1:13]) smat <- as.matrix(tmat) yy <- c(30,35,42,56,34,45,32,37,78,56,40,52,39) aeq(diag(tmat), diag(smat)) zz <- seq(1,13,2) aeq(as.matrix(tmat[zz,zz]), smat[zz,zz]) ch0 <- chol(smat) ch1 <- gchol(smat) ch2 <- gchol(tmat) # The gchol routines use the composition LDL', where L is lower triangular # with a diagonal of 1's, and D is diagonal. chol() uses U'U where U is # upper trangular. # The as.matrix function returns L and the diag function returns D. # Convert and compare aeq(diag(ch1), diag(ch2)) temp <- as.matrix(ch2) aeq(temp, as.matrix(ch1)) temp3 <- temp %*% diag(sqrt(diag(ch2))) aeq(temp3, t(ch0)) zz0 <- solve(smat, yy) zz1 <- solve(ch1, yy) zz2 <- solve(tmat, yy) aeq(zz1, zz2) aeq(zz0, zz1) rm(zz1, zz2, zz, temp, temp3, ch0, ch1, ch2)
22f3ab5f437e7f5435a0cbef57d262a29cb2d0d9
8fda7334773928c884f4813efbbde9921ef13b53
/poissonModel4.R
fb956662fad48dacf0cbd82b7ad2b43b4ca03ef6
[]
no_license
jazose/flows
606afb322e1312f69420f1f568e5d684b3657584
4feb02feabb0cb44385252acbb58776602e301ac
refs/heads/master
2021-01-19T00:46:14.399732
2013-09-04T22:23:43
2013-09-04T22:23:43
null
0
0
null
null
null
null
UTF-8
R
false
false
5,105
r
poissonModel4.R
#Run a simulated Poisson hierarchical model. #Model 4 takes log(lambda) to be a linear combination of log(previous flow + 1), log(pop. at origin), and log(pop. at destination) library(rjags);library(coda); ############### #Read in data.# ############### setup=function(){ if(file.exists("C:/Users/jonazose")){ setwd("C:/Users/jonazose/Dropbox/RA/Code/flows/") }else if(file.exists("C:/Users/Jon-Everyday")){ setwd("C:/Users/Jon-Everyday/Dropbox/RA/Code/flows/flows_git/") }else{ setwd("/homes/jonazose/RA/flows_git/flows/") } #Read in data rawDat=scan("./Abel/flows_Decadal.txt") countryList<<-scan("./Abel/countryList_Decadal.txt",what="",sep=" ") flowArray<<-array(rawDat[4:length(rawDat)],dim=rawDat[1:3]) rm(rawDat) rawPopDat=scan("./Abel/popDatMatrix_Decadal.txt"); popDatMatrix<<-matrix(rawPopDat[3:length(rawPopDat)],nrow=rawPopDat[1],ncol=rawPopDat[2]) #Toss out some countries that aren't in the CEPII database. #Guam (GUM), Mayotte (MYT), and US Virgin Islands (VIR) tossOutIndices=which(countryList %in% c("GUM","MYT","VIR")) flowArray<<-flowArray[-tossOutIndices,-tossOutIndices,]; shortCountryList<<-countryList[-tossOutIndices]; popDatMatrix<<-popDatMatrix[-tossOutIndices,] nm=length(shortCountryList); ##################### #Read in CEPII stuff# ##################### if(!file.exists("distanceArray.txt")){#If we didn't already make the distance array distData=read.csv("dist_cepii.csv",header=TRUE) modifiedCountryList=shortCountryList; modifiedCountryList[which(shortCountryList=="COD")]="ZAR"#COD in WorldBank is ZAR in CEPII modifiedCountryList[which(shortCountryList=="TLS")]="TMP"#TLS in WorldBank is TMP in CEPII modifiedCountryList[which(shortCountryList=="PSE")]="PAL"#PSE in WorldBank is PAL in CEPII distanceArray<<-array(0,dim=c(nm,nm,12)) cat("Constructing distance matrix\n") for(i in 1:nm){ cat(i,"\n") for(j in 1:nm){ distanceArray[i,j,]=as.numeric(distData[which(distData$iso_o==modifiedCountryList[i] & distData$iso_d==modifiedCountryList[j]), 3:14]) } } write(dim(distanceArray),"distanceArray.txt") write(distanceArray,"distanceArray.txt",append=TRUE) }else{#If we did make the distance array already, just read it in. distanceArrayDat=scan("distanceArray.txt") distanceArray<<-array(distanceArrayDat[4:length(distanceArrayDat)], dim=distanceArrayDat[1:3]); } #Convert everything to vector form vectorLength=nm*(nm-1);#Keep track of the length of a single year's worth of data flowMatrix<<-matrix(0,nrow=dim(flowArray)[3],ncol=vectorLength);#Construct a matrix #where each row is a single year's data for(i in 1:dim(flowArray)[3]){ M=flowArray[,,i]; flowMatrix[i,]=M[row(M)!=col(M)] } flowMatrix<<-flowMatrix; originMatrix<<-matrix(rep(shortCountryList,nm),nrow=nm,byrow=FALSE); originVector<<-originMatrix[row(originMatrix)!=col(originMatrix)]; destMatrix<<-t(originMatrix); destVector<<-destMatrix[row(destMatrix)!=col(destMatrix)]; distanceMatrix<<-matrix(0,nrow=12,ncol=vectorLength); for(i in 1:12){ M=distanceArray[,,i]; distanceMatrix[i,]=M[row(M)!=col(M)]; } distanceMatrix<<-distanceMatrix; } setup(); #Use for annual data #y=as.vector(flowMatrix[c(15,25,35),]) #x=as.vector(flowMatrix[c(5,15,25),]) #Use for decadal data y=as.vector(flowMatrix[c(2,3,4),]); x=as.vector(flowMatrix[c(1,2,3),]); #Construct vectors of origin and destination populations at beginning of the decade oVec=numeric(0); dVec=numeric(0); for(j in 1:3){ temp=rep(0,length(originVector)); for(i in 1:length(originVector)){ countryIndex=which(shortCountryList==originVector[i]) temp[i]=popDatMatrix[countryIndex,j] } oVec=c(oVec,temp); temp=rep(0,length(destVector)); for(i in 1:length(destVector)){ countryIndex=which(shortCountryList==destVector[i]) temp[i]=popDatMatrix[countryIndex,j] } dVec=c(dVec,temp); } #Choose a small sample from the y and x vectors sampleFraction=1 #Use all of the data for fitting compressedDataSize=floor(sampleFraction*length(y)) compressedDataIndices=sort(sample.int(n=length(y),size=compressedDataSize)) smallY=y[compressedDataIndices]; smallX=x[compressedDataIndices]; ################## #Run through JAGS# ################## #The compressed version jags <- jags.model('model4.bug.R', data=list('n' = compressedDataSize, 'hist' = smallX, 'f' = smallY, 'o' = oVec, 'd' = dVec), n.chains = 4, n.adapt = 100) update(jags, 500) samples=coda.samples(jags, c('alpha1','alpha2','alpha3','beta'), 1000, thin=5) sampleData=as.matrix(rbind(samples[[1]],samples[[2]],samples[[3]],samples[[4]])) write(sampleData,"./Output/model4output.txt")
b938fbce4e1808cdb6c88a2004b0cfe885eec6be
acf095499a8283654b2cacf546124b04febb350e
/classify/man/gpcm.bug.Rd
6327830c038963d7cb36e7d1653d95ebf5eb1433
[]
no_license
cbwheadon/classify
6831fbd214cb69127b219d58385d7bb6e2701fa4
72c4c1b0e744e6b15353135e9c5315f30156b6d0
refs/heads/master
2016-09-08T05:09:13.811832
2014-08-17T09:42:38
2014-08-17T09:42:38
null
0
0
null
null
null
null
UTF-8
R
false
false
769
rd
gpcm.bug.Rd
\name{gpcm.bug} \alias{gpcm.bug} \title{ Extract IRT Model Parameters from Bugs Models } \description{ Internal function which draws heavily on Curtis, S.M.(2010). } \usage{ gpcm.bug(v, cats, mdl, gibbs=c("bugs","jags")) } \arguments{ \item{v}{Bugs sims matrix} \item{cats}{Numeric vector of item categories} \item{mdl}{Bugs file: Partial Credit Model - "pcm.bug" or Generalised Partial Credit Model - "gpcm.bug" or Rasch model - "rasch.bug" or 2pl model "tpl.bug"} \item{gibbs}{Gibbs sampler: "bugs" or "jags"} } \details{Extracts IRT Model Parameters from Bugs Models} \value{ List with theta and beta parameters } \references{ Curtis, S.M.(2010) BUGS Code for Item Response Theory, \emph{Journal of Statistical Software}, Code Snippets, \bold{36(1)},1--34 }
e6c4b20a16d204b489b4d216bf9c1905cff560d1
6dbb5242837e7210e9e1abb8497706e29c252098
/plot2.R
148d4bbb0a22a5be82603e9ac374a60c0dfe002a
[]
no_license
jasminchia/ExData_Plotting1
54feb064c54d2bdea395ed6ebf84eef04bb105fe
4443cdc52a7846759bf916a435d3cf80d4054e2e
refs/heads/master
2021-01-16T22:28:31.566652
2014-11-09T16:52:35
2014-11-09T16:52:35
null
0
0
null
null
null
null
UTF-8
R
false
false
813
r
plot2.R
#read all data from file full_data <- read.csv("./household_power_consumption.txt", header=T, sep=';', na.string="?", nrows=2075259, check.names=F, stringsAsFactors=F, comment.char="") #reformat the date into standard format full_data$Date <- as.Date(full_data$Date, format="%d/%m/%Y") #subset data from 2007-02-01 to 2007-02-02 chart2_data <- subset(full_data, Date >= "2007-02-01" & Date <= "2007-02-02") #remove all data to release memory rm(full_data) #re-format the datetime datetime <- paste(as.Date(chart2_data$Date), chart2_data$Time) chart2_data$Datetime <- as.POSIXct(datetime) ## Plot 2 plot(chart2_data$Global_active_power~chart2_data$Datetime, type="l", ylab="Global Active Power (kilowatts)", xlab="") dev.copy(png, file="plot2.png", height=480, width=480) dev.off()
6f033bf57cb958c74135c58e23f2d5c1754f441f
bd5f1f295766b7a22a51273650855c592a1a037e
/R/deprecated/compare_miseq_clones.R
a4c3355517a670ace376076296b4935b618cc197
[]
no_license
tebbej/ArGa_MHC_DQB_R
bbdc1598f1dfeadf1c3c1b2a8653e41b3f5ea983
191feb360e4364edeb224743dc217c9ea77c3726
refs/heads/main
2023-04-11T10:32:17.169374
2022-10-06T12:55:10
2022-10-06T12:55:10
474,030,764
0
0
null
null
null
null
UTF-8
R
false
false
7,305
r
compare_miseq_clones.R
## NGS AND CLONING DATA COMPARISON (HEATMAP?) ## miseq_data <- readDNAStringSet("data/ArGa-DQB-NGS_Artemis_20210301.fas") miseq_data <- miseq_data[-length(miseq_data)] miseq_info <- read.table(file = "data/ngs/Acacia_data_artemis.txt", header = T)[1:21,] clone_genotypes <- readDNAStringSet("data/ArGa-DQB_clone-alleles_20210430.fas") #order by occurence frequency in cloning seqs # in case allele ordering is desired to be after actual genotypes: # clone_genotypes <- readDNAStringSet("data/allele_order_from_genotypes.fas") #assign frequency values from plot to correct alleles (unsorted ngs alleles) freq_info <- data.frame(ngs_alleles = names(miseq_data), freq = miseq_info$freq[1:21]/100) # freq = c(.15,.08,.10,.07,.11,.08,.07,.05,.06,.04,.02, # .03,.02,.03,.01,.02,.02,.02,.00,.01,.01)) # along sequences in miseq_data, compare the sequences in miseq_data with # sequences in clone_genotypes and create a matrix with 1's indicating correspondence # of sequences and 0's non-correspondence miseq_in_genotypes <- as.array(sapply(seq_along(miseq_data), function(x) vcountPattern(as.vector(miseq_data[x]), clone_genotypes))) # adjust col and row names according to their corresponding data.frame of origin colnames(miseq_in_genotypes) <- names(miseq_data) rownames(miseq_in_genotypes) <- names(clone_genotypes) miseq_in_genotypes <- miseq_in_genotypes %>% # convert matrix to long data frame for ggplot heatmap format as.data.frame() %>% rownames_to_column("clone_alleles") %>% pivot_longer(-c(clone_alleles), names_to = "ngs_alleles", values_to = "counts") %>% mutate(., clone_alleles = factor(clone_alleles, levels = str_sort(unique(clone_alleles), numeric = T)), ngs_alleles = factor(ngs_alleles, levels = rev(str_sort(unique(ngs_alleles), numeric = T)))) %>% arrange(., desc(ngs_alleles)) %>% #sort both alleles for tidy plotting arrange(., clone_alleles) %>% # create column with information whether one or both of the listed allele is a putative artefact or not mutate(., artefact_ngs = ifelse((ngs_alleles %in% paste0("ArGa-DQB*", c(15,20,21))) == T, 1, 0)) %>% mutate(., artefact_clone = ifelse((clone_alleles %in% paste0("ArGa-DQB*", 20:30)) == T, 1,0)) shared_alleles <- miseq_in_genotypes[-which(miseq_in_genotypes$counts != 1),] shared_alleles <- miseq_in_genotypes[-which(miseq_in_genotypes$counts != 1),1:2] %>% mutate(sequence = as.vector( miseq_data[na.omit( match(shared_alleles$ngs_alleles, names(miseq_data)))])) # double check whether sequences now coincide iter_bin <- vector(length=dim(shared_alleles)[1]) for (i in seq_along(shared_alleles[[3]])) { iter_bin[i] <- str_detect(as.character(clone_genotypes[i]), shared_alleles[[3]][[i]]) } if (any(iter_bin != T)) { warning("Allele matches share erroneous sequences") } else { message("Allele sequences coincide") } # update frequency of occurences of MiSeq alleles and overwrite names in clone allele manner # (miseq alleles, are named according to their matching clone allele sequence) miseq_alleles <- shared_alleles %>% mutate( freq = miseq_info$freq[na.omit(match(shared_alleles$ngs_alleles, miseq_info$allele))]/100, variant_count = miseq_info$count[na.omit(match(shared_alleles$ngs_alleles, miseq_info$allele))] ) %>% mutate(ngs_alleles = clone_alleles) %>% select(!(clone_alleles)) miseq_alleles <- as.data.frame(miseq_alleles) miseq_alleles_variant_counter <- unlist(sapply(miseq_alleles$variant_count, function(x) 1:x)) miseq_alleles_expand <- as.data.frame(lapply(miseq_alleles, rep, miseq_alleles$variant_count)) %>% mutate(., variant_counter = miseq_alleles_variant_counter) miseq_alleles_expand <- miseq_alleles_expand %>% mutate(mutate(.,variant_no = sapply( miseq_alleles_expand$ngs_alleles, function(x) { stringr::str_split(x, "\\*")[[1]][2] %>% paste0(., collapse = "\\*") %>% as.numeric() }))) figures[[7]] <- ggplot(miseq_alleles_expand, aes(x = variant_no, group = desc(variant_counter), fill = variant_counter)) + geom_bar(aes(y = stat(count) / sum(count))) + scale_y_continuous(labels = scales::label_percent(accuracy = 1), limits = c(0,0.2), #swapped x & y values for reversing! expand = c(0,0)) + scale_fill_viridis_c(option = "cividis", begin = 0, end = 1) + ylab("Frequency\n'MiSeq'\n") + labs(fill = "Allele\ncounts") + scale_x_continuous(breaks = seq_along(unique(miseq_alleles$ngs_alleles)), labels = str_sort(unique(miseq_alleles$ngs_alleles), numeric = T), expand = c(0, 0.3)) + theme_minimal() + theme(panel.grid = element_line(color = "white"), panel.grid.minor = element_blank(), panel.grid.major.x = element_blank(), axis.line = element_line(color = "black"), axis.text = element_text(color = "black"), axis.title = element_text(color = "black", margin = margin(10,10,20,10)), axis.ticks = element_line(color = "black", size = 0.2), axis.line.x = element_line(color = "black"), axis.ticks.x = element_blank(), axis.title.x = element_blank(), axis.text.x.bottom = element_text(angle = 45, vjust = 1, hjust = 1, size = 11), axis.line.y = element_line(color = "black"), axis.title.y = element_text(size = 15.5), axis.ticks.y = element_blank(), axis.ticks.length = unit(.15,"cm"), plot.background = element_rect(color = "white", fill = "white"), legend.position = "none", plot.margin = unit(c(0.5,0.5,0.5,0.5), "cm") ) figures[[7]] ggsave(filename = "graphics/allele_frequency_ngs_artemis_preliminary_scale.png", figures[[7]], dpi = 400) freq_compare <- data.frame(clone_freq = alleles$frequency[1:19]/100, ngs_freq =miseq_alleles$freq) ngs_clone_correlation <- ggplot(freq_compare, aes(x=ngs_freq, y=clone_freq)) + geom_point(shape = 15, size = 3) + geom_smooth(method = "lm", se = T, colour = "orange") + scale_y_continuous(name = "Allele frequency\ncloning data\n", limits = c(0,0.2), expand = c(0,0)) + scale_x_continuous(name = "\nAllele frequency\nMiSeq data", limits = c(0,0.2), expand = c(0,0)) + annotate(geom = "text", x = 0.181, y = 0.01, label = "italic(R²)==0.84", parse = T) + theme_bw() + theme( panel.grid.minor = element_blank(), panel.grid.major = element_blank(), plot.margin = unit(c(0.5,0.5,0.5,0,5), "cm"), axis.title = element_text(color = "black", margin = margin(10,10,20,10)) ) ngs_clone_correlation ggsave("graphics/freq_correlation.png", ngs_clone_correlation, dpi = 400) corr <- lm(ngs_freq~clone_freq, data = freq_compare) summary(corr)
225877e2ddaa0f868f9de9af0bcf9277b7241ad6
dc3642ea21337063e725441e3a6a719aa9906484
/DevInit/R/experiments/logins.R
0485d7eed8af09916f546a35e7417507151905f8
[]
no_license
akmiller01/alexm-util
9bbcf613384fe9eefd49e26b0c841819b6c0e1a5
440198b9811dcc62c3eb531db95abef8dbd2cbc7
refs/heads/master
2021-01-18T01:51:53.120742
2020-09-03T15:55:13
2020-09-03T15:55:13
23,363,946
0
7
null
null
null
null
UTF-8
R
false
false
103
r
logins.R
wd <- "C:/Users/alexm/Documents" setwd(wd) #Read dat <- read.csv("logins.txt",header=FALSE,as.is=TRUE)
32d14e89856d957d02b2e8ffe6be0110914c4da0
7c6deaad20a9507e809a70c694975bb31da5d5f0
/Breast_cancer.R
6c579ab5ac75b22923ce559b747ea24d3f55e090
[]
no_license
Zeev17/Median-knn_imputation
771ae10fbb6b6afccb7732512acbef9ece58c86e
0a3e55838682946095774a97a022a898819498db
refs/heads/master
2020-03-29T22:03:39.977914
2018-09-26T09:24:39
2018-09-26T09:24:39
null
0
0
null
null
null
null
UTF-8
R
false
false
2,117
r
Breast_cancer.R
#setwd("C:/Users/Install/Desktop/CASE_R_september") load("BreastCancer.RData") #This dataset is interesting because many of the predictors contain missing values #and most rows of the dataset have at least one missing value library(caret) library(RANN) myControl<- trainControl(method = "cv", number = 10, verboseIter = TRUE) #################################################################### #Median Uputation #################################################################### # Apply median imputation: model model <- train( x = breast_cancer_x, y = breast_cancer_y, method = "glm", trControl = myControl, preProcess = "medianImpute" ) # Print model to console model #################################################################### #KNN imputatin #################################################################### # Apply KNN imputation: model2 model2 <- train( x = breast_cancer_x, y = breast_cancer_y, method = "glm", trControl = myControl, preProcess = "knnImpute" ) # Print model to console model2 #################################################################### #Compare KNN and median imputation #################################################################### median_model <- model knn_model <- model2 resamples <- resamples(x = list(median_model = median_model, knn_model = knn_model)) #Plot to see dotplot(resamples, metric = "Accuracy") #knn model is slightly better. #################################################################### #Combining preprocessing methods #################################################################### # Fit glm with median imputation: model1 model1 <- train( x = breast_cancer_x, y = breast_cancer_y, method = "glm", trControl = myControl, preProcess = "medianImpute" ) # Print model1 model1 # Fit glm with median imputation and standardization: model2 model2 <- train( x = breast_cancer_x, y = breast_cancer_y, method = "glm", trControl = myControl, preProcess = c("medianImpute", "center", "scale") ) # Print model2 model2
348600ea63ed50a2d3b41793fcd8f0fa1ac6d612
d1452f430d7f5b28380ca6d5a68bf2d3b51e7443
/hhold_cons.R
11967fb073dcea7e080379d9e7d867a2b2b73203
[]
no_license
julianflowers/ex-data
c8a6909e911d9e174bf88e7c636739ae39e2d630
f20c7b124113c4b950eff06cdbf426f26ab34b72
refs/heads/master
2021-01-20T13:49:02.756602
2015-09-20T07:54:58
2015-09-20T07:54:58
42,403,001
0
0
null
null
null
null
UTF-8
R
false
false
814
r
hhold_cons.R
library(lubridate) url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(url, destfile = "hh.zip") unzip("hh.zip") hh <- read.csv("household_power_consumption.txt", header = TRUE, sep = ";", stringsAsFactors = FALSE) ## turns out that file is ; separated hh$datetime <- with(hh, paste(Date,"",Time)) ##create a new datetime variable hh$datetime <- dmy_hms(hh$datetime) ## convert to date time from character to POSIXct format hh_s <- subset(hh, dmy(Date) == "2007-02-01" | dmy(Date) == "2007-02-02") ## subset the data set for 1st and 2nd Feb and store to a new variable hh_s1 <-apply(hh_s[, 3:8], 2, function(x) as.numeric(x)) ## convert character data back to numeric hh_s1 <- cbind(as.data.frame(hh_s1), hh_s[,c(9:10)]) ## recombine back into data frame
b651342a0ad348df57d178e11a915a19063977bc
9594d219126402ec4f5a58d32c8a57c82cab1e25
/man/BandLevelFlatSpectrum.Rd
0624e39eb14a9e7fbbc9901b04b4433c39d6a624
[]
no_license
ctdClub/sonar
037ade64e0c4efab690a1bc3c0ec1bd598be25b0
c054c140714acb507a7e9d9d481149c9b3c38143
refs/heads/master
2022-02-01T17:43:37.739473
2016-09-15T15:46:37
2016-09-15T15:46:37
null
0
0
null
null
null
null
UTF-8
R
false
false
592
rd
BandLevelFlatSpectrum.Rd
% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/sonar.R \name{BandLevelFlatSpectrum} \alias{BandLevelFlatSpectrum} \title{band level (BL) for flat spectrum} \usage{ BandLevelFlatSpectrum(SpL, deltaf) } \arguments{ \item{SpL}{spectrum level} \item{deltaf}{band frequency} } \value{ band level (BL) } \description{ Returns the total intensity of the sound in a band for flat spectrum } \examples{ BandLevelFlatSpectrum( 3, 2 ) } \author{ Jose Gama } \references{ Waite A. D., 2002 Sonar for Practising Engineers, 3rd Edition Chichester: Wiley. pp. 10. }
4d8ffae32749941f0006a2abbec7808aacd7950e
5434a6fc0d011064b575b321e93a3519db5e786a
/man/checkRunningRemote.Rd
c8e7c91c694ae889c640b74ac501d3ef5a5644e6
[ "MIT" ]
permissive
cytoscape/RCy3
4813de06aacbaa9a3f0269c0ab8824a6e276bad9
18d5fac035e1f0701e870150c55231c75309bdb7
refs/heads/devel
2023-09-01T18:23:28.246389
2023-08-23T07:57:19
2023-08-23T07:57:19
118,533,442
47
22
MIT
2023-04-03T17:52:34
2018-01-23T00:21:43
R
UTF-8
R
false
true
769
rd
checkRunningRemote.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RCy3-notebook.R \name{checkRunningRemote} \alias{checkRunningRemote} \title{checkRunningRemote} \usage{ checkRunningRemote() } \value{ None } \description{ Determine whether we're running locally or on a remote server. If locally (either via raw R or via a locally installed Notebook), we prefer to connect to Cytoscape over a local socket. If remote, we have to connect over Jupyter-Bridge. Either way, we can determine which by whether Cytoscape answers to a version check. If Cytoscape doesn't answer, we have no information ... and we have to wait until Cytoscape is started and becomes reachable before we can determine local vs remote. } \examples{ \donttest{ checkRunningRemote() } }
9a0a5ddfbf955edf0a9948079de4c4bc17c3988c
10c62818f4b83b7338e29799869aa3dc051fd6b4
/src/svm/dual_svm.R
2daa23c46adbb59ac17d273a9357330967d0cfc5
[ "Apache-2.0" ]
permissive
chianwei/MachineLearning-memo
e27426d3121dfe3f81e80928af301fa5071e76cd
29284ca24041969eeb59851a43ab6c28c685fae5
refs/heads/master
2020-03-16T19:27:01.105127
2017-01-18T07:50:09
2017-01-18T07:50:09
null
0
0
null
null
null
null
UTF-8
R
false
false
1,029
r
dual_svm.R
############# # dual SVM n <- 5 Y <- c(-1,-1,-1,1,1) data <- matrix(c(-2, 1, 0, 0, 2, 2, 2, 0, 3, 0),2,n) #Dmat <- Y %o% Y * t(data) %*% data m <- matrix(0, n, n) for(i in 1:n){ for(j in 1:n){ m[i,j] <- Y[i]*Y[j]*t(data[, i]) %*% data[, j] } } Dmat <- m dvec <- rep(-1, n) bvec <- rep(0, n) #https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20080901/637ba8c6/attachment.pl #Amat <- matrix(0, n, n) #diag(Amat) <- Y #A=matrix(1:1,1, n) #for(i in 1:3){ # A[,i] <- -1 #} A <- matrix(Y, 1) #http://d.hatena.ne.jp/repose/20080917/1221580572 library(kernlab) res <- ipop(c = dvec, H = Dmat, A=A, b=0, l=rep(0, n),u=rep(10000,length=n), r=0, sigf=7) sol <- res@primal SV <- sol > 0.1 #simulate = 0 w <- apply(sol[SV] * Y[SV] * data[, SV], MARGIN = 1, sum) b <- Y[SV] - t(w) %*% data[,SV] b <- b[1,1] f <- function(x) { return(-(b + w[1]*x)/w[2]) } plot(-5:5, f(-5:5), type="l") points(c(-2,0,2),c(1,0,2), pch = "x", col="red") points(c(2,3),c(0,0), pch = "o", col="blue")
ebc4504d1e1e95ee080b623fc4364ad9ed7722b3
f26fd7932132c77d1f0ced4339f5eac3c974ebae
/R/plot-cpue.R
f69946e1973c331c29fb70e602d3196c8a15202a
[]
no_license
szuwalski/gmr
687f86e8e125b5dca96b6ff677eedf3212b24cc4
92abdaffccbd6d39ea7466529af9e6ea79b891c4
refs/heads/main
2023-01-09T13:07:24.481235
2020-11-05T20:00:14
2020-11-05T20:00:14
306,703,007
1
0
null
null
null
null
UTF-8
R
false
false
6,346
r
plot-cpue.R
#' Get cpue or other indices #' #' @param M List object created by read_admb function #' @return dataframe of observed and predicted indices and residuals #' @author SJD Martell, D'Arcy N. Webber #' @export #' .get_cpue_df <- function(M) { n <- length(M) mdf <- NULL for (i in 1:n) { A <- M[[i]] df <- data.frame(Model = names(M)[i], as.data.frame(A$dSurveyData)) colnames(df) <- c("Model","Index","year","seas","fleet","sex","mature","cpue","cv","units") df$sex <- .SEX[df$sex+1] df$fleet <- .FLEET[df$fleet] sd <- sqrt(log(1 + df$cv^2)) df$lb <- exp(log(df$cpue) - 1.96*sd) df$ub <- exp(log(df$cpue) + 1.96*sd) df$cvest <- na.exclude(as.vector(t(A$cpue_cv_add))) sde <- sqrt(log(1 + df$cvest^2)) df$lbe <- exp(log(df$cpue) - 1.96*sde) df$ube <- exp(log(df$cpue) + 1.96*sde) df$pred <- na.exclude(as.vector(t(A$pre_cpue))) df$resd <- na.exclude(as.vector(t(A$res_cpue))) mdf <- rbind(mdf, df) } return(mdf) } #' Plot cpue or other indices #' #' @param M list object created by read_admb function #' @param subsetby the fleet to subset the data to #' @param xlab the x-axis label for the plot #' @param ylab the y-axis label for the plot #' @param ShowEstErr Shows errorbars from estimated CVs as well #' @param logy Plot the CPUE in log-space #' @param slab the sex label for the plot that appears above the key #' @return plot of all observed and predicted incices #' @export #' plot_cpue <- function(M, subsetby = "", xlab = "Year", ylab = "CPUE", slab = "Sex", ShowEstErr = FALSE, logy = FALSE) { mdf <- .get_cpue_df(M) if (subsetby != "") mdf <- subset(mdf, fleet == subsetby) if (logy) { mdf$cpue <- log(mdf$cpue) mdf$lb <- log(mdf$lb) mdf$ub <- log(mdf$ub) mdf$lbe <- log(mdf$lbe) mdf$ube <- log(mdf$ube) mdf$pred <- log(mdf$pred) ylab <- paste0("log(", ylab, ")") } xlab <- paste0("\n", xlab) ylab <- paste0(ylab, "\n") p <- ggplot(mdf, aes(year, cpue)) + expand_limits(y = 0) + geom_pointrange(aes(year, cpue, ymax = ub, ymin = lb), col = "black") if (ShowEstErr) { if (length(M) == 1 && length(unique(mdf$sex)) == 1) { p <- p + geom_pointrange(aes(year, cpue, ymax = ube, ymin = lbe), color = "red", shape = 1, linetype = "dotted", position = position_dodge(width = 1)) } else if (length(M) != 1 && length(unique(mdf$sex)) == 1) { p <- p + geom_pointrange(aes(year, cpue, ymax = ube, ymin = lbe, col = Model), shape = 1, linetype = "dotted", position = position_dodge(width = 1)) } else if (length(M) == 1 && length(unique(mdf$sex)) != 1) { p <- p + geom_pointrange(aes(year, cpue, ymax = ube, ymin = lbe, col = sex), shape = 1, linetype = "dotted", position = position_dodge(width = 1)) } else { p <- p + geom_pointrange(aes(year, cpue, ymax = ube, ymin = lbe, col = Model), shape = 1, linetype = "dotted", position = position_dodge(width = 1)) } } if (.OVERLAY) { if (length(M) == 1 && length(unique(mdf$sex)) == 1) { p <- p + geom_line(data = mdf, aes(year, pred)) + facet_wrap(~fleet, scales = "free_y",ncol=1) } else if (length(M) != 1 && length(unique(mdf$sex)) == 1) { p <- p + geom_line(data = mdf, aes(year, pred, color = Model, linetype = Model)) + facet_wrap(~fleet, scales = "free_y",ncol=1) } else if (length(M) == 1 && length(unique(mdf$sex)) != 1) { p <- p + geom_line(data = mdf, aes(year, pred, color = sex)) + labs(col = slab) + facet_wrap(~fleet + sex, scales = "free_y",ncol=1) } else { p <- p + geom_line(data = mdf, aes(year, pred, color = Model, linetype = Model)) + facet_wrap(~fleet + sex, scales = "free_y",ncol=1) } } else { p <- p + geom_line(data = mdf, aes(year, pred)) p <- p + facet_wrap(~fleet + sex + Model, scales = "free_y",ncol=1) } p <- p + labs(x = xlab, y = ylab) print(p + .THEME + theme(legend.position=c(.7,.85))) } #' Plot residuals of cpue or other indices #' #' @param M List object created by read_admb function #' @param subsetby the fleet or fleets to plot #' @param xlab the x-axis label for the plot #' @param ylab the y-axis label for the plot #' @param slab the sex label for the plot that appears above the key #' @return plot of fit indices residuals #' @export #' plot_cpue_res <- function(M, subsetby = "", xlab = "Year", ylab = "Residual", slab = "Sex") { xlab <- paste0("\n", xlab) ylab <- paste0(ylab, "\n") mdf <- .get_cpue_df(M) if (subsetby != "") mdf <- subset(mdf, fleet == subsetby) p <- ggplot(data = mdf, aes(year, resd)) + geom_hline(aes(yintercept = 0)) if (length(M) == 1 && length(unique(mdf$sex)) == 1) { p <- p + geom_point(data = mdf, aes(year, resd), position = position_dodge(0.5)) + geom_linerange(aes(ymin = 0, ymax = resd), position = position_dodge(0.5)) + facet_wrap(~fleet, scales = "free_y") } else if (length(M) != 1 && length(unique(mdf$sex)) == 1) { p <- p + geom_point(data = mdf, aes(year, resd, color = Model, shape = Model), position = position_dodge(0.5)) + geom_linerange(aes(ymin = 0, ymax = resd, color = Model), position = position_dodge(0.5)) + facet_wrap(~fleet, scales = "free_y") } else if (length(M) == 1 && length(unique(mdf$sex)) != 1) { p <- p + geom_point(data = mdf, aes(year, resd, color = sex, shape = sex), position = position_dodge(0.5)) + labs(col = slab) + geom_linerange(aes(ymin = 0, ymax = resd, color = sex), position = position_dodge(0.5)) + facet_wrap(~fleet + sex, scales = "free_y") } else { p <- p + geom_point(data = mdf, aes(year, resd, color = Model, shape = Model), position = position_dodge(0.5)) + geom_linerange(aes(ymin = 0, ymax = resd, color = Model), position = position_dodge(0.5)) + facet_wrap(~fleet + sex, scales = "free_y") } p <- p + labs(x = xlab, y = ylab, fill = slab) print(p + .THEME) }
a773b21d214c22c1f7c454c8cd308479c07cf3bd
3ae7ca784edd942e246357a7a8a55c07dbfe3f38
/src/clean.R
3dcd00f21e0e280d3c0adc052d749621fdafde48
[ "MIT" ]
permissive
HFAnalyticsLab/HES_pipeline
a4acbdf6dce34ba7cf18af74ae627828509791e8
cab20a88e584d42a0c3c3d89898bfef89e102344
refs/heads/master
2023-04-16T10:20:56.933701
2023-03-22T09:48:09
2023-03-22T09:48:09
206,582,339
31
6
MIT
2021-01-25T09:51:19
2019-09-05T14:21:15
R
UTF-8
R
false
false
7,280
r
clean.R
# If a column is present in dataframe apply provided function. # Warnings generated by 'one_of' when col not found are supressed. # Requires a dataframe, a column name as a string and a function to # recursively apply to the column if present. # Returns dataframe with modifed column. mutate_if_present <- function(data, cols, fn) { return(suppressWarnings(data %>% mutate_at(vars(one_of(cols)), fn))) } # Parse columns (or single column) converting a specifc value to NA # Requires a dataframe, a vector of column names as strings and a value to convert # to NA. # Returns a modified dataframe. convert_to_NA <- function(data, cols, v) { return(data %>% mutate_if_present(cols, ~na_if(., v))) } # Parse columns (or single column) converting strings to date format, # e.g. 2010-31-01. # Requires a dataframe, a vector of column names as strings and a date format e.g. "%Y%m%d. # Returns a modified dataframe. convert_date <- function(data, cols) { return(data %>% mutate_if_present(cols, as.Date)) } # Parse columns (or single column) converting values to integers. # Requires a dataframe, and a vector of column names as strings. # Returns a modified dataframe. convert_to_int <- function(data, cols) { return(mutate_if_present(data, cols, as.integer)) } # Parse columns (or single column) converting a set of values (or single # value) to a new set of values (or single value). # Requires a dataframe, a vector of column names as strings, a vector of values to be replaced # and a vector of values to replace with. # Returns a modified dataframe. convert_vals <- function(data, cols, old_vals, new_vals) { return(data %>% mutate_if_present(cols, ~plyr::mapvalues(., old_vals, new_vals))) } # Generates a vector of headers corresponding to the provided string with numbers 01 to # n appended, n times # Requires a string and a maximum number # Returns a character vector generate_numbered_headers <- function(string, n) { return(c(str_c(string, "0", 1:9), str_c(string, 10:n))) } # Parse columns, where present, into required data formats. # Requires a dataframe. # Returns a modifed dataframe. parse_HES <- function(data) { return(data %>% convert_to_NA(c("ADMINCAT", "ADMINCATST", "ADMISORC", "DISDEST", "RTTPERSTAT", "EPIORDER"), 98) %>% convert_to_NA(c("ADMINCAT", "ADMINCATST", "ADMISORC" ,"CARERSI", "DISDEST", "EPIORDER", "LOCCLASS", "REFSOURC", "RTTPERSTAT", "STAFFTYP", "AEATTENDDISP", "AEDEPTTYPE", "AEINCLOCTYPE", "AEPATGROUP", "AEREFSOURCE", "ccapcrel"), 99) %>% convert_to_NA(c("ATENTYPE"), 13) %>% convert_to_NA(c("AEARRIVALMODE", "AEATTENDCAT", "CLASSPAT", "DISMETH", "INTMANIG", "NEOCARE", "OPERSTAT", "ATTENDED", "OUTCOME", "PRIORITY", "SERVTYPE", "STAFFTYP"), 9) %>% convert_to_NA(c("CLASSPAT", "INTMANIG", "NEOCARE", "OPERSTAT", "STAFFTYP"), 8) %>% convert_to_NA(c("SEX"), 0) %>% convert_to_NA(c("ARRIVALTIME", "CONCLTIME", "DEPTIME", "INITTIME", "TRETTIME"), 3000) %>% convert_to_NA(c("ARRIVALTIME", "CONCLTIME", "DEPTIME", "INITTIME", "TRETTIME"), 4000) %>% convert_to_NA(c("FIRSTATT"), "9") %>% convert_to_NA(c("ADMIMETH"), "98") %>% convert_to_NA(c("ADMIMETH", "ETHNOS"), "99") %>% convert_to_NA(c("PROCODE", "SITETRET"), "89999") %>% convert_to_NA(c("PROCODE", "SITETRET"), "89997") %>% convert_to_NA(c("AEKEY"), "0") %>% convert_to_NA(c("ETHNOS", "FIRSTATT"), "X") %>% convert_to_NA(c("ETHNOS"), "Z") %>% convert_to_NA(generate_numbered_headers("OPERTN_", n = 24), "-") %>% convert_to_NA(c(c("ARRIVALDATE", "ADMIDATE", "DISDATE", "DISREADYDATE", "ELECDATE", "EPIEND", "EPISTART", "RTTPEREND", "RTTPERSTART", "SUBDATE", "APPTDATE", "DNADATE", "REQDATE", "DOD", "DOR", "DISDATE", "ccdisdate", "ccdisrdydate", "ccstartdate"), generate_numbered_headers("OPDATE_", n = 24)), "1800-01-01") %>% convert_to_NA(c(c("ARRIVALDATE", "ADMIDATE", "DISDATE", "DISREADYDATE", "ELECDATE", "EPIEND", "EPISTART", "RTTPEREND", "RTTPERSTART", "SUBDATE", "APPTDATE", "DNADATE", "REQDATE", "DOD", "DOR", "DISDATE", "ccdisdate", "ccdisrdydate", "ccstartdate"), generate_numbered_headers("OPDATE_", n = 24)), "1801-01-01") %>% convert_to_NA(c(c("ARRIVALDATE", "ADMIDATE", "DISDATE", "DISREADYDATE", "ELECDATE", "EPIEND", "EPISTART", "RTTPEREND", "RTTPERSTART", "SUBDATE", "APPTDATE", "DNADATE", "REQDATE", "DOD", "DOR", "DISDATE", "ccdisdate", "ccdisrdydate", "ccstartdate"), generate_numbered_headers("OPDATE_", n = 24)), "1600-01-01") %>% convert_to_NA(c(c("ARRIVALDATE", "ADMIDATE", "DISDATE", "DISREADYDATE", "ELECDATE", "EPIEND", "EPISTART", "RTTPEREND", "RTTPERSTART", "SUBDATE", "APPTDATE", "DNADATE", "REQDATE", "DOD", "DOR", "DISDATE", "ccdisdate", "ccdisrdydate", "ccstartdate"), generate_numbered_headers("OPDATE_", n = 24)), "1582-10-15") %>% convert_to_NA(c("APPTDATE", "ARRIVALDATE"), "18000101") %>% convert_to_NA(c("APPTDATE", "ARRIVALDATE"), "18010101") %>% convert_to_NA(c(c("DOMPROC", "GPPRAC", "MAINSPEF", "TRETSPEF"), generate_numbered_headers("OPERTN_", n = 24)), "&") %>% convert_to_NA(generate_numbered_headers("OPERTN_", n = 24), "X999") %>% convert_to_NA(generate_numbered_headers("OPERTN_", n = 24), "X998") %>% convert_to_NA(generate_numbered_headers("OPERTN_", n = 24), "X997") %>% convert_to_NA(c("REFERORG"), "X99998") %>% convert_to_NA(c("REFERORG"), "X99999") %>% convert_to_NA(c("GPPRAC"), "V81998") %>% convert_to_NA(c("GPPRAC"), "V81997") %>% convert_to_NA(c("GPPRAC"), "V81999") %>% convert_to_NA(c("LSOA11"), "Z99999999") %>% convert_to_NA(generate_numbered_headers("DIAG_", n = 20), "R69X") %>% convert_to_NA(generate_numbered_headers("DIAG_", n = 20), "R69X6") %>% convert_to_NA(generate_numbered_headers("DIAG_", n = 20), "R69X8") %>% convert_to_NA(generate_numbered_headers("DIAG_", n = 20), "R69X3") %>% convert_vals(c("ADMIMETH"), old_vals = c("2A", "2B", "2C", "2D"), new_vals = c("66", "67", "68", "69")) %>% convert_vals(c("DOMPROC"), old_vals = c("-"), new_vals = c("None")) %>% convert_vals(c("SPELEND"), old_vals = c("N", "Y"), new_vals = c(0, 1)) %>% convert_vals(c("STARTAGE", "APPTAGE", "ARRIVALAGE"), old_vals = 7001:7007, new_vals = seq(0, 0, length.out = (7007-7000))) %>% convert_to_int(c("ADMIMETH", "FIRSTATT")) ) }
824eb3f66e1e371dc0960b997ba2cc243687a946
8dc93e785685daea5eee3bc467b5ccadc0b7db69
/mkt_share_est.R
84e7c0bd2648ef3d54e43bd71ddfdb6a24434dfe
[]
no_license
probmetrics/BLP_R_demo
1ae7edd58f27fac16d74771aa905ce9c914f4a23
ebea55986f633145bcd7548310c19137d63bf7c4
refs/heads/master
2020-06-01T02:46:11.857110
2019-06-06T15:26:24
2019-06-06T15:26:24
190,603,119
0
0
null
null
null
null
UTF-8
R
false
false
1,848
r
mkt_share_est.R
## ## Functions for estimating market share in BLP model ## ## Shu Xu, <May, 2019> ## share_per_mkt <- function(delta, alpha, sigma, p, X, y, vshk) { # # ** Estimating market share in a single market ** # # Inputs: # delta, -- J vector # X, -- J x K matrix # y, -- S vector of income y_i # p, -- J vector of price p_j # vshk, -- K x S matrix # alpha, -- scalar, coef of price/income # sigma, -- K vector # # Output: # J x 1 vector of estimated market share # require(matrixStats) # ubar <- delta - alpha * outer(p, y, "/") + X %*% sigma %*% vshk ubar <- delta - alpha * outer(p, y, "/") + X %*% (sigma * vshk) #<-- J by S matrix ubars <- cbind(0, t(ubar)) #<-- S x (J + 1) matrix prob <- exp(ubars - rowLogSumExps(ubars))[, -1] share <- colMeans(prob) return(share) } mkt_share_est <- function(mkt_idx, delta, alpha, sigma, price, X, yshk, vshk){ # # ** Estimating market share for all markets ** # # Inputs: # mkt_idx -- index indicating diff. markets # delta, -- J x M vector # X, -- JM x K matrix # yshk -- M x S matrix of income y_i # p, -- JM vector of price p_j # vshk, -- (K x S x M) 3D array # alpha, -- scalar, coef of price/income # sigma, -- K vector # # Output: # JM x 1 vector of estimated market shares # mid <- unique(mkt_idx) mshr_fun <- function(i) { midx <- mkt_idx == mid[i] mshr <- share_per_mkt(delta[midx], alpha, sigma, price[midx], X[midx, ], yshk[i, ], vshk[, , i]) return(mshr) } share_list <- sapply(1:length(mid), mshr_fun) mkt_share <- unlist(share_list) return(mkt_share) }
420d61cf313570a39a95209f276dc23d986e9c92
d62d96ab238bbd3fde1554b9b3a933333a8ff068
/script.R
6138f9f468a224eba3ae2dbd8e903b150f10902d
[]
no_license
rfael0cm/AchimTalk
9748855e4a57dcd14a6b1bf67ce9f62716c5d052
5eec71c955784901f531f83ac14c9423297245ca
refs/heads/master
2020-03-15T13:56:25.840120
2018-05-04T19:06:17
2018-05-04T19:06:17
132,178,823
0
0
null
null
null
null
UTF-8
R
false
false
7,221
r
script.R
## requires: gplots, MASS, Gviz ## work with vignette es ### Course in bdHMM ## 1. load a bdHMM object and see its characteristics ## 2. Generate 10^4 time points from the model ## 3. Fit a standar HMM model to the generated Data ## 4. See some characteristics ## 5. Fit a bdHMM ## 6. Compare it with the HMM and bdHMM # 1. LOAD A bdHMM OBJECT AND SEE ITS CHARACTERISTICS library(STAN) library(gplots) load('/home/campos/Desktop/Achim_talk/bdhmm_fitted_class.RData') bdhmm_fitted # This bdHMM model has been fitted to a set of 10 different tracks, 2 of them directional. bdhmm_fitted$loglik # We can see the last 10 iteration during Baum-Welch Method bdhmm_fitted$stateLabel # Name of the states, this model was fitted for 12 states 5 directional (F/R 1:5) and 2 undirectional (U1, U2) bdhmm_fitted$hmm@directedObs # Directionality of the Data we have 8 tracks undirectional (TF, histone modification,...) coded by 0 and 2 directional (strand specific RNA-seq data) coded by 1 bdhmm_fitted$hmm@initProb # Initial Probabilities bdhmm_fitted$hmm@transMat # transition Matrix between states source('/home/campos/Desktop/Achim_talk/MeanHeatMap_function.R') MeanHeatMap(bdhmm_fitted, bdhmm_yeast) heat=c('dark grey','steelblue', 'yellow','gold', 'orange', 'dark orange',rep('red',10),rep('white',200)) colfct = colorRampPalette(heat) colpal = colfct(200) heatmap.2(bdhmm_fitted$hmm@transMat, col=colpal,trace="none", cexCol=0.9, cexRow=0.9, notecol="black", dendrogram="none", Rowv=F, Colv=FALSE, notecex=0.9) ## GENERATE 10^3 OBSERVATIONS source('/home/campos/Desktop/CreateData/Function/GenerateData_function.R') Data_G<-GenerateData(1299, bdhmm_fitted) colnames(Data_G$observation)<-names(bdhmm_yeast@emission@parameters$mean[[1]]) table(Data_G$viterbi) ChrMatrix<-list() ChrMatrix$chr<-Data_G$observation ## GENERATE HMM MODEL nStates=7 myMat = ChrMatrix$chr[apply(ChrMatrix$chr, 1, function(x) all(! is.na(x))),] myMat[, c("YPDexprW", "YPDexprC")] = t(apply(myMat[, c("YPDexprW", "YPDexprC")], 1, sort, decreasing=TRUE)) km = kmeans(myMat, centers=7, iter.max=1000, nstart=100)$centers Mean_hmm <- lapply(1:nrow(km), function(x)km[x,]) Covs_hmm<-cov(myMat[complete.cases(myMat),]) Covs_hmm<-lapply(1:nStates, function(x)Covs_hmm) gaussEmission = HMMEmission(type="Gaussian", parameters=list(mean=Mean_hmm, cov=new_Colapsed$hmm@emission@parameters$cov), nStates=nStates) transMat = matrix(1/nStates, nrow=nStates, ncol=nStates) initProb = rep(1/nStates, nStates) hmm = HMM(initProb=initProb, transMat=transMat, emission=gaussEmission, nStates=nStates, status="initial") hmm_fitted<-fitHMM(ChrMatrix, hmm) hmm_viterbi<-getViterbi(hmm_fitted$hmm,ChrMatrix ) table(hmm_viterbi$chr, Data_G$viterbi) names(hmm@emission@parameters$mean[[1]])<-colnames(Data_G$observation) MeanHeatMap(hmm_fitted, hmm) heat=c('dark grey','steelblue', 'yellow','gold', 'orange', 'dark orange',rep('red',10),rep('white',200)) colfct = colorRampPalette(heat) colpal = colfct(200) heatmap.2(hmm_fitted$hmm@transMat, col=colpal,trace="none", cexCol=0.9, cexRow=0.9, notecol="black", dendrogram="none", Rowv=F, Colv=FALSE, notecex=0.9) ## GENERATE bdHMM MODEL nStates<- 11 stateLabel<-bdhmm_fitted$hmm@stateLabel myMat = ChrMatrix$chr[apply(ChrMatrix$chr, 1, function(x) all(! is.na(x))),] myMat[, c("YPDexprW", "YPDexprC")] = t(apply(myMat[, c("YPDexprW", "YPDexprC")], 1, sort, decreasing=TRUE)) km = kmeans(myMat, centers=7, iter.max=1000, nstart=100)$centers km<-rbind(km, km[c(1:4),]) km<-km[c(1:4,8:11,5,6,7),] Mean_bdhmm <- lapply(1:nrow(km), function(x)km[x,]) for (i in 5:8){ Mean_bdhmm[[i]]<-Mean_bdhmm[[i]][c(1:8,10,9)] names(Mean_bdhmm[[i]])<-names(Mean_bdhmm[[1]]) } Covs_hmm<-cov(myMat[complete.cases(myMat),]) Covs_hmm<-lapply(1:nStates, function(x)Covs_hmm) gaussEmission <- HMMEmission(type="Gaussian", parameters=list(mean=bdhmm_fitted$hmm@emission@parameters$mean, cov=bdhmm_fitted$hmm@emission@parameters$cov), nStates=nStates) dirobs = as.integer(c(rep(0,8), 1, 1)) transMat <- bdhmm_fitted$hmm@transMat initProb <-bdhmm_fitted$hmm@initProb bdhmm_GD = bdHMM(initProb=initProb, transMat=transMat, emission=gaussEmission, nStates=nStates, status="initial", stateLabel=stateLabel, transitionsOptim="analytical", directedObs=dirobs) bdhmm_fittedGD = fitHMM(ChrMatrix, bdhmm_yeast, maxIters=100, verbose=FALSE) viterbiGD = getViterbi(bdhmm_fittedGD$hmm, ChrMatrix) table(viterbiGD$chr,Data_G$viterbi ) MeanHeatMap(bdhmm_fittedGD, bdhmm_GD) ## PLOT WITH TRACKS library(Gviz) ucscChromosomeNames=FALSE gtrack<-GenomeAxisTrack() names(faccols) = colnames(Data_G$observation) chr = "chrIV" gen = "sacCer3" gtrack <- GenomeAxisTrack() faccols = hcl(h = seq(15, 375 - 360/dim(ChrMatrix$chr)[2], length = dim(ChrMatrix$chr)[2])%%360, c = 100, l = 65) names(faccols) = colnames(ChrMatrix$chr) dlist=list() for(n in colnames(ChrMatrix$chr)) { dlist[[n]] = DataTrack(data = ChrMatrix$chr[,n], start = yeastTF_probeAnno_ex$chr04, end = yeastTF_probeAnno_ex$chr04+8, chromosome = "chrIV", genome=gen, name = n, type="h", col=faccols[n]) } library(GenomicRanges) library(IRanges) myViterbiDirs = list(F=c("F1", "F2", "F3", "F4"), U=c("U1", "U2","U3"), R=c("R1", "R2", "R3", "R4")) myViterbiPanels = list() cols = rainbow(7) cols = cols[c(1:5,1:5,6:7)] names(cols) = stateLabel myHiddenStates = list() for(dir in c("F", "U", "R")) { myPos = yeastTF_probeAnno_ex$chr04 >= 1217060 & yeastTF_probeAnno_ex$chr04 <= 1225000 myRle = Rle(viterbiGD$chr[myPos]) currItems = which(myRle@values %in% myViterbiDirs[[dir]]) start = yeastTF_probeAnno_ex$chr04[myPos][start(myRle)][currItems] width = myRle@lengths[currItems] ids = as.character(myRle@values[currItems]) values = as.character(myRle@values[currItems]) myViterbiPanels[[dir]] = AnnotationTrack(range=GRanges(seqnames=rep("chrIV", length(currItems)), ranges=IRanges(start=start, width=width*8, names=values)), genome=gen, chromosome=chr, name=paste("Viterbi\n", "(", dir, ")", sep=""), id=ids[order(start)], shape="box",fill=cols[values[order(start)]], col="black", stacking="dense") } for(dir in c("F", "U", "R")) { myPos = yeastTF_probeAnno_ex$chr04 >= 1217060 & yeastTF_probeAnno_ex$chr04 <= 1225000 myRle = Rle(Data_G$viterbi[myPos]) currItems = which(myRle@values %in% myViterbiDirs[[dir]]) start = yeastTF_probeAnno_ex$chr04[myPos][start(myRle)][currItems] width = myRle@lengths[currItems] ids = as.character(myRle@values[currItems]) values = as.character(myRle@values[currItems]) myHiddenStates[[dir]] = AnnotationTrack(range=GRanges(seqnames=rep("chrIV", length(currItems)), ranges=IRanges(start=start, width=width*8, names=values)), genome=gen, chromosome=chr, name=paste("Hidden States\n", "(", dir, ")", sep=""), id=ids[order(start)], shape="box",fill=cols[values[order(start)]], col="black", stacking="dense") } sizes = rep(1,16) sizes[12:16] = 0.7 plotTracks(c( dlist, myViterbiPanels, myHiddenStates), from=1217060, to=1225000, sizes=sizes, showFeatureId=TRUE, featureAnnotation="id", fontcolor.feature="black", cex.feature=0.7, background.title="darkgrey", showId=TRUE)
5bc2519aa9ef2cd799cce6da18bfeda20270103a
035229c811d57d91a11e3d43bc4b71dc58222f3b
/analysis/revision/tcell_klk3_exp.R
73be02070e64f82b22507218214970fb5713983c
[]
no_license
Limour-dev/scRNA
d40580541e7ceef1a4ff875628a1a619e2912db7
834ec5c0c4323b521c96ca86db973b170831f2da
refs/heads/master
2023-06-15T13:40:41.843619
2021-07-17T14:44:22
2021-07-17T14:44:22
null
0
0
null
null
null
null
UTF-8
R
false
false
8,678
r
tcell_klk3_exp.R
library(BoutrosLab.plotting.general); library(Seurat); library(reshape); library(plyr); setwd('/cluster/projects/hansengroup/sujunc/scRNA/primary/scran/revision/tcell'); seurat.all <- readRDS('/cluster/projects/hansengroup/sujunc/scRNA/primary/scran/normalize_data/objects/2019-07-25_seurat_manual_all.rds'); name <- 'all'; seurat.all@meta.data$type <- gsub('Macrophage|Myeloid', 'Monolytic', seurat.all@meta.data$type); seurat.all@meta.data$type <- gsub('Myofibroblast', 'Fibroblast', seurat.all@meta.data$type); seurat.all <- SetAllIdent(seurat.all, id = 'type'); myexp <- data.frame(exp = seurat.all@data['KLK3', ]); myexp$type <- seurat.all@meta.data$type; myexp <- myexp[myexp$exp>0, ] myexp$group <- 'epithelia'; myexp[myexp$type%in%c('Endothelia', 'Fibroblast'), ]$group <- 'stroma'; myexp[!myexp$type%in%c('Endothelia', 'Fibroblast', 'Basal/intermediate', 'Luminal'), ]$group <- 'immune'; myexp$group <- factor(myexp$group); #myexp <- ddply(myexp, 'group', numcolwise(mean)); #myexp$pos <- seq(3) pval1 <- scientific.notation(wilcox.test(myexp[myexp$group=='epithelia', ]$exp, myexp[myexp$group=='immune', ]$exp)$p.value); pval1 <- ifelse(pval1==0, expression('< 2.2'%*%10^-16, )); pval2 <- scientific.notation(wilcox.test(myexp[myexp$group=='stroma', ]$exp, myexp[myexp$group=='immune', ]$exp)$p.value) create.boxplot( formula = exp~group, data = myexp, #add.stripplot = TRUE, xlab.label = 'Type', ylab.label = 'KLK3 abundance', ylimits = c(0, 8), add.text = TRUE, text.x = c(1.5, 2.5), text.y = 7.8, text.labels = c(pval1, pval2), text.cex = 1.5, xaxis.cex = 2, yaxis.cex =2, filename = generate.filename('exp_klk3p', 'type_all', 'pdf'), style = 'Nature' ); ### to.plot <- data.frame(exp = seurat.all@data['KLK3', ], type = seurat.all@meta.data$type, samp = 'sample13'); to.plot <- to.plot[to.plot$type!='Epithelia', ] to.plot.m <- data.frame(reshape::cast(to.plot, type~samp, mean, value = 'exp', fill = 0)); to.plot.f <- data.frame(reshape::cast(to.plot[to.plot$exp>0, ], type~samp, length, value = 'exp', fill = 0)); to.plot.n <- data.frame(reshape::cast(to.plot, type~samp, length, value = 'exp', fill = 0)); # to.plot.n$group <- 'all'; to.plot.f$group <- 'pos'; to.plot <- rbind(to.plot.f, to.plot.n); to.plot.f[, 2] <- round(100*to.plot.f[, 2]/to.plot.n[, 2]); to.plot.n$group <- 'all'; to.plot.f$group <- 'pos'; to.plot <- rbind(to.plot.f, to.plot.n); to.plot.f[, 2:4] <- sapply(seq(3), function(x) 100*to.plot.f[, (x+1)]/to.plot.n[, (x+1)]); to.plot.f[, 2:4] <- round(to.plot.f[, 2:4]) to.plot.f[6, 3] <- 'NA'; create.barplot( data = to.plot[, c('type', 'S5.LEFT.2', 'group')], formula = S5.LEFT.2~type, groups = to.plot$group, col = default.colours(2), style = 'Nature', #xaxis.lab = c('R', 'L', 'T'), xlab.label = '', ylab.labe = '# cells', xaxis.cex = 2, yaxis.cex = 2, xaxis.rot = 45, ylimits = c(0, 9000), height = 4, width = 8, add.text = TRUE, text.x = seq(10), text.y = to.plot[11:20, ]$S5.LEFT.2 + 500, text.labels = paste0(to.plot.f$S5.LEFT.2, '%'), text.cex = 1.5, text.fontface = 'plain', key = list( text = list( lab = c('All', 'KLK3 positive'), col = default.colours(2) ), points = list( pch = 22, fill = default.colours(2), col = 'black' ), x = 0.02, y = 0.9 ), filename = generate.filename('number_cells', 'samp3p1_left', 'pdf') ); ### iseurat <- readRDS('/cluster/projects/hansengroup/sujunc/scRNA/primary/scran/samp3p1/objects/AllSample_GraphClust.seuset.rds'); mytype <- read.table('/cluster/projects/hansengroup/sujunc/scRNA/primary/scran//samp3p1/objects/CellType_Rename.txt', header = TRUE); iseurat@meta.data$type <- mytype[match(rownames(iseurat@meta.data), mytype$Cell), ]$Cluster; iseurat@meta.data$type <- gsub('Cell$', '', iseurat@meta.data$type); iseurat@meta.data$type <- gsub('Macrophage|^DC', 'Monocytic', iseurat@meta.data$type); imyexp <- data.frame(exp = iseurat@data['KLK3', ]); imyexp$type <- iseurat@meta.data$type; imyexp <- imyexp[grepl('LEFT', rownames(imyexp))&imyexp$exp>0, ]; imyexp$group <- 'epithelia'; imyexp[imyexp$type%in%c('Endothelia', 'Fibroblast'), ]$group <- 'stroma'; imyexp[!imyexp$type%in%c('Endothelia', 'Fibroblast', 'Epithelia'), ]$group <- 'immune'; #imyexp <- ddply(imyexp, 'group', numcolwise(mean)); pval1 <- scientific.notation(wilcox.test(imyexp[imyexp$group=='epithelia', ]$exp, imyexp[imyexp$group=='immune', ]$exp)$p.value); pval1 <- ifelse(pval1==0, expression('< 2.2'%*%10^-16, )); pval2 <- scientific.notation(wilcox.test(imyexp[imyexp$group=='stroma', ]$exp, imyexp[imyexp$group=='immune', ]$exp)$p.value) create.boxplot( formula = exp~group, data = imyexp, #add.stripplot = TRUE, xlab.label = 'Type', ylab.label = 'KLK3 abundance', add.text = TRUE, text.x = c(1.5, 2.5), text.y = 6.5, text.labels = c(pval1, pval2), text.cex = 1.5, xaxis.cex = 2, yaxis.cex =2, filename = generate.filename('exp_klk3p', 'type_left', 'pdf'), style = 'Nature' ); #### #### imyexp <- data.frame(exp = iseurat@data['KLK3', ]); imyexp$type <- iseurat@meta.data$type; imyexp <- imyexp[grepl('TUMOR', rownames(imyexp))&imyexp$exp>0, ]; imyexp$group <- 'epithelia'; imyexp[imyexp$type%in%c('Endothelia', 'Fibroblast'), ]$group <- 'stroma'; imyexp[!imyexp$type%in%c('Endothelia', 'Fibroblast', 'Epithelia'), ]$group <- 'immune'; #imyexp <- ddply(imyexp, 'group', numcolwise(mean)); pval1 <- scientific.notation(wilcox.test(imyexp[imyexp$group=='epithelia', ]$exp, imyexp[imyexp$group=='immune', ]$exp)$p.value); pval1 <- ifelse(pval1==0, expression('< 2.2'%*%10^-16, )); pval2 <- scientific.notation(wilcox.test(imyexp[imyexp$group=='stroma', ]$exp, imyexp[imyexp$group=='immune', ]$exp)$p.value) create.boxplot( formula = exp~group, data = imyexp, #add.stripplot = TRUE, xlab.label = 'Type', ylab.label = 'KLK3 abundance', add.text = TRUE, text.x = c(1.5, 2.5), text.y = 6.2, text.labels = c(pval1, pval2), text.cex = 1.5, xaxis.cex = 2, yaxis.cex =2, filename = generate.filename('exp_klk3p', 'type_tumor', 'pdf'), style = 'Nature', #width = 4.5, #height = 4.5 ); ### summary(data.frame(t(iseurat@data[c('TP63', 'KRT14', 'KRT5'), iseurat@meta.data$orig.ident=='S6.TUMOR.M'&iseurat@meta.data$type=='Epithelia']))) imyexp <- data.frame(t(as.matrix(iseurat@data[c('TP63', 'KRT14', 'KRT5'), ]))); imyexp$type <- iseurat@meta.data$type; imyexp$orig.ident <- iseurat@meta.data$orig.ident; imyexp <- imyexp[imyexp$type=='Epithelia', ]; to.plot <- data.frame(exp = iseurat@data['KLK3', ], type = iseurat@meta.data$type, samp = iseurat@meta.data$orig.ident); to.plot <- to.plot[to.plot$type!='Epithelia', ] to.plot.m <- data.frame(reshape::cast(to.plot, type~samp, mean, value = 'exp', fill = 0)); to.plot.f <- data.frame(reshape::cast(to.plot[to.plot$exp>0, ], type~samp, length, value = 'exp', fill = 0)); to.plot.n <- data.frame(reshape::cast(to.plot, type~samp, length, value = 'exp', fill = 0)); # to.plot.n$group <- 'all'; to.plot.f$group <- 'pos'; to.plot <- rbind(to.plot.f, to.plot.n); to.plot.f[, 2:4] <- sapply(seq(3), function(x) 100*to.plot.f[, (x+1)]/to.plot.n[, (x+1)]); to.plot.f[, 2:4] <- round(to.plot.f[, 2:4]) to.plot.f[6, 3] <- 'NA'; create.barplot( data = to.plot[, c('type', 'S5.LEFT.2', 'group')], formula = S5.LEFT.2~type, groups = to.plot$group, col = default.colours(2), style = 'Nature', #xaxis.lab = c('R', 'L', 'T'), xlab.label = '', ylab.labe = '# cells', xaxis.cex = 2, yaxis.cex = 2, xaxis.rot = 45, ylimits = c(0, 9000), height = 4, width = 8, add.text = TRUE, text.x = seq(10), text.y = to.plot[11:20, ]$S5.LEFT.2 + 500, text.labels = paste0(to.plot.f$S5.LEFT.2, '%'), text.cex = 1.5, text.fontface = 'plain', key = list( text = list( lab = c('All', 'KLK3 positive'), col = default.colours(2) ), points = list( pch = 22, fill = default.colours(2), col = 'black' ), x = 0.02, y = 0.9 ), filename = generate.filename('number_cells', 'samp3p1_left', 'pdf') ); create.barplot( data = to.plot[, c('type', 'S6.TUMOR.M', 'group')], formula = S6.TUMOR.M~type, groups = to.plot$group, col = default.colours(2), style = 'Nature', #xaxis.lab = c('R', 'L', 'T'), xlab.label = '', ylab.labe = '# cells', xaxis.cex = 2, yaxis.cex = 2, xaxis.rot = 45, ylimits = c(0, 9000), height = 4, width = 8, add.text = TRUE, text.x = seq(10), text.y = to.plot[11:20, ]$S6.TUMOR.M + 500, text.labels = paste0(to.plot.f$S6.TUMOR.M, '%'), text.cex = 1.5, text.fontface = 'plain', key = list( text = list( lab = c('All', 'KLK3 positive'), col = default.colours(2) ), points = list( pch = 22, fill = default.colours(2), col = 'black' ), x = 0.02, y = 0.9 ), filename = generate.filename('number_cells', 'samp3p1_tumor', 'pdf') );
e5c34f14716186523bc2effda07f395659f1eda5
7afbb148ec11b3105aaead6bdd900f847e49eb18
/tests/testthat/test-hyperbolic.R
86c0dbb9a0ca2f72efe6bbe8ca438f35a2e1b3d2
[ "MIT" ]
permissive
tidymodels/recipes
88135cc131b4ff538a670d956cf6622fa8440639
eb12d1818397ad8780fdfd13ea14d0839fbb44bd
refs/heads/main
2023-08-15T18:12:46.038289
2023-08-11T12:32:05
2023-08-11T12:32:05
76,614,863
383
123
NOASSERTION
2023-08-26T13:43:51
2016-12-16T02:40:24
R
UTF-8
R
false
false
3,055
r
test-hyperbolic.R
library(testthat) library(recipes) n <- 20 set.seed(1) ex_dat <- data.frame( x1 = runif(n, min = -1, max = 1), x2 = runif(n, min = -1, max = 1) ) set.seed(2) ex_dat1 <- data.frame( x1 = runif(n, min = 1, max = 5), x2 = runif(n, min = 1, max = 5) ) get_exp <- function(x, f) { as_tibble(lapply(x, f)) } test_that("simple hyperbolic trans", { for (func in c("sinh", "cosh", "tanh")) { rec <- recipe(~., data = ex_dat) %>% step_hyperbolic(x1, x2, func = func, inverse = FALSE) rec_trained <- prep(rec, training = ex_dat, verbose = FALSE) rec_trans <- bake(rec_trained, new_data = ex_dat) foo <- get(func) exp_res <- get_exp(ex_dat, foo) expect_equal(rec_trans, exp_res) } for (func in c("sinh", "tanh")) { rec <- recipe(~., data = ex_dat) %>% step_hyperbolic(x1, x2, func = func, inverse = TRUE) rec_trained <- prep(rec, training = ex_dat, verbose = FALSE) rec_trans <- bake(rec_trained, new_data = ex_dat) foo <- get(paste0("a", func)) exp_res <- get_exp(ex_dat, foo) expect_equal(rec_trans, exp_res) } rec <- recipe(~., data = ex_dat1) %>% step_hyperbolic(x1, x2, func = "cosh", inverse = TRUE) rec_trained <- prep(rec, training = ex_dat1, verbose = FALSE) rec_trans <- bake(rec_trained, new_data = ex_dat1) exp_res <- get_exp(ex_dat1, "acosh") expect_equal(rec_trans, exp_res) }) test_that("wrong function", { rec <- recipe(mpg ~ ., mtcars) expect_snapshot_error(step_hyperbolic(rec, func = "cos")) }) # Infrastructure --------------------------------------------------------------- test_that("bake method errors when needed non-standard role columns are missing", { rec <- recipe(~., data = ex_dat) %>% step_hyperbolic(x1, x2, func = "sinh", inverse = FALSE) %>% update_role(x1, x2, new_role = "potato") %>% update_role_requirements(role = "potato", bake = FALSE) rec_trained <- prep(rec, training = ex_dat, verbose = FALSE) expect_error(bake(rec_trained, new_data = ex_dat[, 2, drop = FALSE]), class = "new_data_missing_column") }) test_that("empty printing", { rec <- recipe(mpg ~ ., mtcars) rec <- step_hyperbolic(rec) expect_snapshot(rec) rec <- prep(rec, mtcars) expect_snapshot(rec) }) test_that("empty selection prep/bake is a no-op", { rec1 <- recipe(mpg ~ ., mtcars) rec2 <- step_hyperbolic(rec1) rec1 <- prep(rec1, mtcars) rec2 <- prep(rec2, mtcars) baked1 <- bake(rec1, mtcars) baked2 <- bake(rec2, mtcars) expect_identical(baked1, baked2) }) test_that("empty selection tidy method works", { rec <- recipe(mpg ~ ., mtcars) rec <- step_hyperbolic(rec) expect <- tibble( terms = character(), inverse = logical(), func = character(), id = character() ) expect_identical(tidy(rec, number = 1), expect) rec <- prep(rec, mtcars) expect_identical(tidy(rec, number = 1), expect) }) test_that("printing", { rec <- recipe(~., data = ex_dat) %>% step_hyperbolic(x1, x2) expect_snapshot(print(rec)) expect_snapshot(prep(rec)) })
f551506676629711ac1e0057678e73fa10cb60e7
0711ce0882fcbeb16113f4bdda073372c94ea4f6
/projects/Alpha101/R/alpha101_12.R
2a29a1db6d348197458c00eb62188b08707f1316
[]
no_license
maxclchen/myStrat.bk
4bc960a04d40fdecbfa7cb0b34c5901a47810c8e
78a8fe055c40d4b9e462ebcb2f8bc7caadfc6d3a
refs/heads/master
2023-03-16T01:53:54.995233
2017-10-17T07:53:02
2017-10-17T07:53:02
null
0
0
null
null
null
null
UTF-8
R
false
false
1,682
r
alpha101_12.R
# ============================================================================== # Ref: "Alpha 101" # Alpha#12: # sign[ delta(volume,1) ] * {-1 * [ delta(close,1) ]} # |------ 1 ----| |------ 1 ----| # |--------- 2 ---------| |---------- 2 ---------| # 算法 # 1.分别计算 Volume 和 close 的价差 # 2. # # 含义 # 如果出现成交量上升,但是收盘价却下跌,则发出买入信号 # # 关联: # # ============================================================================== # ------------------------------------------------------------------------------ ## Alpha Name alphaName <- 'alpha101_12' ## 需要去除的日期 truncatedTD <- 1 # ------------------------------------------------------------------------------ # ==========: 提取dtX =============================================================================== # ------------------------------------------------------------------------------ # dtX # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ dtX <- inSample[, .SD[.N > truncatedTD] , by = 'InstrumentID'] %>% .[,":="( signal1 = sign(volume - shift(volume,1L,type='lag')), signal2 = close - shift(close,1L,type='lag') ) ,by='InstrumentID'] %>% .[!is.na(signal1) & !is.na(signal2)] %>% .[,mySignal := signal1 * signal2] # ==================================================================================================
155c4183b8e4b3b47fac14b463e98189f762bd97
7ace7c36aed23ab7f8b42e890d76fab81fb4787f
/shiny-app/ui.R
06ac010d4d526d3ef519175a60715875819fdc35
[ "MIT" ]
permissive
kngan/us-baby-names
5f284485b29e9287f3de29938f47f8433883ed3e
7ae55b51d933992d18678da50d75276ff0b431a4
refs/heads/master
2021-01-10T08:32:46.436233
2016-02-01T02:17:14
2016-02-01T02:17:14
50,361,628
0
0
null
null
null
null
UTF-8
R
false
false
510
r
ui.R
library(shiny) # Define UI for application that draws a histogram shinyUI(fluidPage( # Application title titlePanel("Prevalence of Baby Names"), # Sidebar with a slider input for the number of bins sidebarLayout( sidebarPanel( sliderInput("picked_year", "Year:", min = 1910, max = 2014, value = 1) ), # Show a plot of the generated distribution mainPanel( plotOutput("mapPlot") ) ) ))
10ad40fa702fc0b53a68901eb8b82f91b39cfe31
92e40da6cc8f28c6af06b13c633b5eb43784ec26
/amto/matrix/htmlpdfr/fs_mat_generate.R
4ad76faba0ad698e1f3f7e32a37917c67c92de10
[ "MIT" ]
permissive
JesusRQP96/R4Econ
4845e4aa94d833cc829a4507606e418d4c873fa9
7275585a7fb3436af9b0fd6727f847c9ca39da42
refs/heads/master
2023-05-22T15:02:04.090757
2021-06-14T01:49:15
2021-06-14T01:49:15
null
0
0
null
null
null
null
UTF-8
R
false
false
2,050
r
fs_mat_generate.R
## ----global_options, include = FALSE---------------------------------------------------------------------------------- try(source("../../.Rprofile")) ## ----fixed matrix----------------------------------------------------------------------------------------------------- ar_row_one <- c(-1,+1) ar_row_two <- c(-3,-2) ar_row_three <- c(0.35,0.75) mt_n_by_2 <- rbind(ar_row_one, ar_row_two, ar_row_three) kable(mt_n_by_2) %>% kable_styling_fc() ## --------------------------------------------------------------------------------------------------------------------- # An empty matrix with Logical NA mt_named <- matrix(data=NA, nrow=2, ncol=2) colnames(mt_named) <- paste0('c', seq(1,2)) rownames(mt_named) <- paste0('r', seq(1,2)) mt_named ## --------------------------------------------------------------------------------------------------------------------- # An empty matrix with Logical NA mt_na <- matrix(data=NA, nrow=2, ncol=2) str(mt_na) # An empty matrix with numerica NA mt_fl_na <- matrix(data=NA_real_, nrow=2, ncol=2) mt_it_na <- matrix(data=NA_integer_, nrow=2, ncol=2) str(mt_fl_na) str(mt_fl_na) ## ----random matrix---------------------------------------------------------------------------------------------------- # Generate 15 random normal, put in 5 rows, and 3 columns mt_rnorm <- matrix(rnorm(15,mean=0,sd=1), nrow=5, ncol=3) # Generate 15 random normal, put in 5 rows, and 3 columns mt_runif <- matrix(runif(15,min=0,max=1), nrow=5, ncol=5) # Combine mt_rnorm_runif <- cbind(mt_rnorm, mt_runif) # Display kable(mt_rnorm_runif) %>% kable_styling_fc_wide() ## --------------------------------------------------------------------------------------------------------------------- fl_new_first_col_val <- 111 fl_new_last_col_val <- 999 mt_with_more_columns <- cbind(rep(fl_new_first_col_val, dim(mt_rnorm_runif)[1]), mt_rnorm_runif, rep(fl_new_last_col_val, dim(mt_rnorm_runif)[1])) # Display kable(mt_with_more_columns) %>% kable_styling_fc_wide()
df90d083301aa18fd7f9ebe1251d7894d86e489f
3686f5b321e9e0c550ae56c3a005b6d81a30d34c
/R/vis.R
159acc6bcb94ea2e4b075964e30260f416ef24f0
[ "MIT" ]
permissive
jenslaufer/artventure-site
fd9848f5c035f5a092b01470230c9a2228c3c133
20f2eb80d7b08d172ce70ea295c68a44784f629c
refs/heads/master
2023-03-28T14:09:44.716264
2021-03-23T13:14:36
2021-03-23T13:14:36
339,119,905
0
0
null
null
null
null
UTF-8
R
false
false
2,324
r
vis.R
library(tidyverse) library(glue) library(bbplot) library(ggthemes) library(aws.s3) library(knitr) library(scales) library(gridExtra) library(emojifont) valueBoxes <- function(data) { data %>% ggplot(aes(x, y, height = h, width = w)) + bbc_style() + geom_tile(aes(fill = color)) + geom_text( color = "white", fontface = "bold", size = 17, aes( label = value, x = x - 2.5, y = y + 1 ), hjust = 0 ) + geom_text( color = "white", fontface = "bold", size = 10, aes( label = info, x = x - 2.5, y = y - 1 ), hjust = 0 ) + geom_text( size = 22, aes( label = shape, family = font_family, x = x + 1, y = y + 1 ), alpha = 0.25 ) + scale_fill_brewer(type = "qual", palette = "Dark2") + coord_fixed() + #theme_void() + guides(fill = FALSE) } plotQual <- function(data, var) { varData <- data %>% mutate(total = n()) %>% group_by(!!sym(var), total) %>% summarise(n = n()) %>% mutate(pct = n / total) %>% arrange(n) %>% #drop_na() %>% ungroup() plot1 <- varData %>% mutate(pct = round(pct * 100, 1)) %>% ggplot(aes(!!sym(var), n)) + geom_bar(stat = "identity", fill = "steelblue") + coord_flip() + geom_text(aes(label = "{pct}%" %>% glue()), hjust = -.05) + scale_x_discrete(limit = varData %>% pull(!!sym(var))) + labs(title = 'Number of Art Pieces for Variable "{var}"' %>% glue()) + bbc_style() plot1 %>% finalise_plot( source = "Source: https://artventure.me, Data Source: https://expressobeans.com", width_pixels = 800, height_pixels = 500, save_filepath = "{var}.jpg" %>% glue() ) } plotQuant <- function(data, var) { plot <- data %>% ggplot(aes(!!sym(var))) + geom_freqpoly() + geom_vline(aes(xintercept = median(!!sym(var), na.rm = T)), color = "steelblue") + bbc_style() plot %>% finalise_plot( source = "Source: https://artventure.me, Data Source: https://expressobeans.com", width_pixels = 800, height_pixels = 500, save_filepath = "{var}.jpg" %>% glue() ) }
8f0395c29af5bd20ed85923ef68f2840ecd1865e
7bbc2f83e7ca8aca63d0610a876780649b3fce95
/Assignment 1.R
5fa178834e0fbf4fd483b49392a28be12ab55a47
[]
no_license
jeunbeen/Introduction-to-Statistics
0c514546e8c81a5bde628d1e635c7faef60b3db6
8d1411a3cd78b3d0ab30eaac80c135bc4e9b74a3
refs/heads/main
2023-07-15T02:08:34.389880
2021-08-29T17:52:11
2021-08-29T17:52:11
401,099,501
0
0
null
2021-08-29T17:37:23
2021-08-29T17:17:36
null
UTF-8
R
false
false
110
r
Assignment 1.R
a=c(1:150) b=c(11:160) c=a+b a+b a*b a/b a-b stem(c) hist(c) boxplot(c) ?stem ?hist ?boxplot
9a171f91b67d54e584b4c88b907540783996ac5e
03c99906a94c70e9a13e7714aad996f461f339c1
/R/FPdivparam.R
7d355a8973a117580cabac4bfda2b2f8686e3aa6
[]
no_license
cran/adiv
6a111f6a1ef39fe302a2f882b9a9d04e7d652c04
d65d6e0301e4611a94a91933299bff1fdc06d96b
refs/heads/master
2022-10-28T08:07:33.352817
2022-10-06T12:40:04
2022-10-06T12:40:04
97,764,074
1
1
null
null
null
null
UTF-8
R
false
false
4,439
r
FPdivparam.R
FPdivparam <- function (comm, disORtree, method = c("KY", "KstarI"), palpha = 2, equivalent = FALSE, option = c("asymmetric", "symmetric"), dmax = NULL, tol = 1e-8) { option <- option[1] method <- method[1] if (!method %in% c("KY", "KstarI")) stop("unconvenient method") if (!inherits(comm, "data.frame") & !inherits(comm, "matrix")) stop("comm must be a data frame or a matrix") comm <- as.matrix(comm) if (any(comm < 0)) stop("Negative value in comm") nsp <- ncol(comm) if (!is.null(disORtree)) { if(inherits(disORtree, "phylo") | inherits(disORtree, "phylo4") | inherits(disORtree, "hclust")){ arg.phyl <- .checkphyloarg(disORtree) phyl.phylo <- arg.phyl$phyl.phylo tre4 <- arg.phyl$phyl if (!hasEdgeLength(tre4)) phyl.phylo <- compute.brlen(phyl.phylo, 1) if(is.ultrametric(phyl.phylo) | option == c("symmetric")) dis <- cophenetic.phylo(phyl.phylo)/2 else dis <- matrix(rep(diag(vcv.phylo(phyl.phylo))), nsp, nsp)-vcv.phylo(phyl.phylo) } else if(inherits(disORtree, "matrix") | inherits(disORtree, "dist") ) dis <- as.matrix(disORtree) else stop("unconvenient definition of disORtree") if(any(!colnames(comm)%in%colnames(dis))) stop("Some species names in comm are missing in disORtree") dis <- dis[colnames(comm), colnames(comm)] dis <- as.dist(dis) } if (is.null(disORtree)) { dis <- as.dist( matrix(1, ncol(comm), ncol(comm)) - diag(rep(1, ncol(comm))) ) } if(method == "KY") { if(max(dis) > 1) { if(!is.null(dmax) && (dmax-max(dis)) < tol) dis <- dis/dmax else dis <- dis/max(dis) } sim <- 1 - as.matrix(dis) FREQ <- sweep(comm, 1, rowSums(comm), "/") FUN <- function(aaa) { divv <- rep(0, nrow(comm)) for (i in 1:nrow(comm)) { if (sum(comm[i, ]) < 1e-16) divv[i] <- 0 else{ FFF <- FREQ[i, FREQ[i, ]> tol] simFFF <- sim[FREQ[i, ]> tol, FREQ[i, ]> tol] if(abs(aaa-1) > tol){ if(equivalent) divv[i] <- (t(FFF) %*% t(((FFF%*% simFFF)^(aaa-1)) ))^(1/(1-aaa)) else divv[i] <- t(FFF) %*% t((1-(FFF%*% simFFF)^(aaa-1)) )/(aaa-1) } else{ divv[i] <- -t(FFF) %*% t(log(FFF%*% simFFF)) if(equivalent) divv[i] <- exp(divv[i]) } } } return(divv) } if(length(palpha)==1){ div <- cbind.data.frame(FUN(palpha)) colnames(div) <- "K" rownames(div) <- rownames(comm) class(div) <- c("FPdivparam", "data.frame") } else{ div <- sapply(palpha, FUN) colnames(div) <- paste("K", 1:length(palpha), sep="_") rownames(div) <- rownames(comm) div <- list(palpha = palpha, div = div) class(div) <- c("FPdivparam", "list") } return(div) } else{ commgardees <- (1:nrow(comm))[rowSums(comm) >= tol] commdiv <- comm[commgardees, ] FREQ <- sweep(commdiv, 1, rowSums(comm), "/") PA <- commdiv PA[PA>0] <- 1 FUN <- function(aaa) { ORIval <- distinctAb(comm = commdiv, disORtree = dis, method = "KstarI", palpha = aaa)[[1]] ORIval[is.na(ORIval)] <- 0 divv <- rowSums(ORIval) if(equivalent){ if(is.null(dmax)) dmax <- max(dis) if((dmax-max(dis)) >= tol) dmax <- max(dis) if(abs(aaa-1) > tol) divv <- (( 1-(aaa-1)*divv/dmax ))^(1/(1-aaa)) else divv <- exp(divv/dmax) } return(divv) } if(length(palpha)==1){ div <- FUN(palpha) names(div) <- rownames(commdiv) DIV <- rep(0, nrow(comm)) names(DIV) <- rownames(comm) DIV[names(div)] <- div class(div) <- c("FPdivparam", "vector") } else{ div <- sapply(palpha, FUN) rownames(div) <- rownames(commdiv) DIV <- matrix(0, nrow(comm), length(palpha)) rownames(DIV) <- rownames(comm) colnames(DIV) <- paste("KstarI", 1:length(palpha), sep="_") DIV[rownames(div), ] <- div div <- DIV div <- list(palpha = palpha, div = DIV) class(div) <- c("FPdivparam", "list") } return(div) } }
094d7fcfdc1ee25443f4492328e55e8f3acbca30
fa6bf9f5bee1627b6158a5e693c8c15969c019ee
/Simulation & Risk/HW 2/Ellie_SR_HW2.R
d1b52ff469d9ae6157ab406d23e3689bbaff8c7d
[]
no_license
gclark422/spring1-orange5
59eb61880226000b9f9a6244a1e653319f0d3e3a
13586f04939ac66f5edf0db4cf34e66be2a81634
refs/heads/master
2020-12-06T23:02:53.183034
2020-02-22T03:27:17
2020-02-22T03:27:17
232,574,947
1
0
null
null
null
null
UTF-8
R
false
false
4,916
r
Ellie_SR_HW2.R
############################### # # # Simulation and Risk: # # Homework 2 # # # # Ellie Caldwell # # # ############################### #Objective: Simulate 1) cost of a single dry well 2)NPV of single wet well ########### LIBRARIES ########### #Load in needed libraries library(readxl) library(metRology) library(graphics) library(ks) library(dplyr) library(car) library(stats) ########### DATA ########### #Load in 100,000 2020 predictions from last phase drilling_costs <- read.csv('C:/Users/Ellie Caldwell/Documents/Simulation and Risk/2020 Predictions.csv') drilling_costs <- drilling_costs[,2] drilling_costs <- as.vector(drilling_costs) drilling_costs <- 1000*drilling_costs #Load in Price Projection data proj <- read_excel("C:/Users/Ellie Caldwell/Documents/Simulation and Risk/Homework2_SR/Analysis_Data.xlsx", sheet = "Price Projections") #Function to set first row to be headers header.true <- function(df) { names(df) <- as.character(unlist(df[1,])) df[-1,] } proj <- proj[-1,] proj <- header.true(proj) proj_2020_2035 <- proj[1:16,] proj_2020_2035 <- as.data.frame(proj_2020_2035) proj_2020_2035 <- as.numeric(proj_2020_2035) ########### DRY WELL ########### #Drilling costs + Lease costs + Seismic Costs + Professional Overhead #Lease costs set.seed(12345) r <- rnorm(n=100000, mean=600, sd=50) Pt_lease <- 960*r #Seismic Costs set.seed(12345) r <- rnorm(n=100000, mean=3, sd=0.35) Pt_seis <- 43000*r #Professional Overhead set.seed(12345) r <- rtri(n=100000, min=172000, max=279500, mode=215000) Pt_prof <- r dry_well = drilling_costs + Pt_lease + Pt_seis + Pt_prof mean(dry_well) sd(dry_well) min(dry_well) max(dry_well) median(dry_well) quantile(dry_well, c(0.05, 0.25, 0.75, 0.95)) hist(dry_well, breaks=50) ########### WET WELL ########### #Drilling costs #Lease costs set.seed(123456) r <- rnorm(n=100000, mean=600, sd=50) Pt_lease <- 960*r #Seismic Costs set.seed(123456) r <- rnorm(n=100000, mean=3, sd=0.35) Pt_seis <- 43000*r #Professional Overhead set.seed(123456) r <- rtri(n=100000, min=172000, max=279500, mode=215000) Pt_prof <- r #Completetion Costs set.seed(123456) r <- rnorm(n=100000, mean=390000, sd=50000) Pt_comp <- r #IP set.seed(12345) r <- rnorm(n=100000, mean=6, sd=0.28) Pt_IP <- exp(r) #Decline rate set.seed(12345) r <- runif(n=100000, min=0.15, max=0.32) Pt_decline <- r #Need Cholesky Decomposition R <- matrix(data=cbind(1,0.64, 0.64, 1), nrow=2) U <- t(chol(R)) standardize <- function(x){ x.std = (x - mean(x))/sd(x) return(x.std) } destandardize <- function(x.std, x){ x.old = (x.std * sd(x)) + mean(x) return(x.old) } Both.r <- cbind(standardize(Pt_decline), standardize(Pt_IP)) dip.r <- U %*% t(Both.r) dip.r <- t(dip.r) final.dip.r <- cbind(destandardize(dip.r[,1], Pt_decline), destandardize(dip.r[,2], Pt_IP)) nri <- rep(0, 100000) #Calculate revenue initial_costs <- drilling_costs + Pt_lease + Pt_seis + Pt_comp + Pt_prof proj_2020_2035[,2] <- as.numeric(proj_2020_2035[,2]) proj_2020_2035[,3] <- as.numeric(proj_2020_2035[,3]) proj_2020_2035[,4] <- as.numeric(proj_2020_2035[,4]) npv <- rep(0,100000) set.seed(12345) for(j in 1:100000) { r_ov <- rep(0,15) r_ye1 <- rep(0,15) r_ye <- rep(0,15) rev <- rep(0,15) op_cos <- rep(0,15) nri <- rep(0,15) royal_pay <- rep(0,15) sev_tax <- rep(0,15) prof_over <- rep(0,15) net_sales <- rep(0,100000) r_ye[1] <- final.dip.r[j,2] r_ye1[1] = final.dip.r[j,2] r_ye[1] = (1- final.dip.r[j,1])*r_ye[1] r_ov[1] = 365 * (0.5 * (r_ye1[1] + r_ye[1])) price <- rtri(n=1, min=proj_2020_2035[1, 3], max=proj_2020_2035[1, 2], mode = proj_2020_2035[1, 4]) rev[1] <- r_ov[1] * price op_cos[1] <- (rnorm(n=1, mean=2.25, sd=0.3)) * r_ov[1] nri[1] <- rnorm(n=1, mean=0.75, sd=0.02) prof_over[1] <- rtri(n=1, min=172000, max=279500, mode=215000) royal_pay[1] <- rev[1] * nri[1] sev_tax[1] <- royal_pay[1] * 0.046 net_sales[1] <- ((rev[1] - prof_over[1] - op_cos[1] - sev_tax[1])/((1+0.1)^1)) for(i in 2:15){ r_ye[i] <- final.dip.r[j,2] r_ye1[i] = r_ye[i-1] r_ye[i] = (1- final.dip.r[j,1])*r_ye[i-1] r_ov[i] = 365 * (0.5 * (r_ye1[i] + r_ye[i])) price <- rtri(n=1, min=proj_2020_2035[i, 3], max=proj_2020_2035[i, 2], mode = proj_2020_2035[i, 4]) rev[i] = r_ov[i] * price op_cos[i] <- (rnorm(n=1, mean=2.25, sd=0.3)) * r_ov[i] nri[i] <- nri[1] prof_over[i] <- prof_over[1] royal_pay[i] <- rev[i] * nri[i] sev_tax[i] <- royal_pay[i] * 0.046 net_sales[i] <- ((rev[i] - prof_over[i] - op_cos[i] - sev_tax[i])/((1+0.1)^i)) } npv[j] = (-1*initial_costs) + sum(net_sales) } mean(npv) sd(npv) median(npv) quantile(npv, c(0, 0.05, 0.25, 0.75, 0.95, 1)) hist(npv, breaks=50, xlim=c(1000000, 105000000))
3d813b00cabc592f067ec0eb555fd5d022e14a97
7a173aaf44b4c01ba9c9dd907862a5fe65e079b3
/R/txt.to.words.R
79cf9e01fe6f5dccf1bd8b35864928d71befe734
[]
no_license
Quares/stylo
221904d14aa516f97b4fe6402d394fc568c084fa
eb42d0de8a3f5cbbcac70c10a33ede40fee8f670
refs/heads/master
2020-04-05T23:23:57.101344
2015-08-23T16:17:59
2015-08-23T16:17:59
41,256,678
0
0
null
2015-08-23T16:18:00
2015-08-23T16:10:34
R
UTF-8
R
false
false
2,556
r
txt.to.words.R
# ################################################# # The generic function for splitting a given input text into # single words (chains of characters delimited with # spaces or punctuation marks). Alternatively, # you can replace it with another rule. # Required argument: name of the text (string) to be split. # ATTENTION: this is (almost) the only piece of coding in this script # that dependens on the operating system used # ################################################# txt.to.words <- function(input.text, splitting.rule = NULL, preserve.case = FALSE) { # converting characters to lowercase if necessary if (!(preserve.case)){ input.text = tryCatch(tolower(input.text), error=function(e) NULL) if(is.null(input.text) == TRUE) { input.text = "empty" cat("turning into lowercase failed!\n") } } # if no custom splitting rule was detected... if(length(splitting.rule) == 0 ) { # splitting into units specified by regular expression; here, # all sequences between non-letter characters are assumed to be words: splitting.rule = paste("[^A-Za-z", # Latin supplement (Western): "\U00C0-\U00FF", # Latin supplement (Eastern): "\U0100-\U01BF", # Latin extended (phonetic): "\U01C4-\U02AF", # modern Greek: "\U0386\U0388-\U03FF", # Cyrillic: "\U0400-\U0481\U048A-\U0527", # Hebrew: "\U05D0-\U05EA\U05F0-\U05F4", # Arabic: "\U0620-\U065F\U066E-\U06D3\U06D5\U06DC", # extended Latin: "\U1E00-\U1EFF", # ancient Greek: "\U1F00-\U1FBC\U1FC2-\U1FCC\U1FD0-\U1FDB\U1FE0-\U1FEC\U1FF2-\U1FFC", # Coptic: "\U03E2-\U03EF\U2C80-\U2CF3", # Georgian: "\U10A0-\U10FF", "]+", sep="") tokenized.text = c(unlist(strsplit(input.text, splitting.rule))) # if custom splitting rule was indicated: } else { # sanity check if(length(splitting.rule) == 1) { # just in case, convert to characters splitting.rule = as.character(splitting.rule) # splitting into units specified by custom regular expression tokenized.text = c(unlist(strsplit(input.text, splitting.rule))) } else { stop("Wrong splitting regexp") } } # getting rid of emtpy strings tokenized.text = tokenized.text[nchar(tokenized.text) > 0] # outputting the results return(tokenized.text) }
a8cdc4efdd0eb7fa7f3c9b021225c3c8e773df6c
edd10cb0ebe95cee716b04778d454ff64039ebe3
/Older Scripts /gradient.R
e28ee86d1904ae0ba0f7baf3a8c0792e75731eaa
[]
no_license
sidAvad/ZIBB-model
7c9d009b50b7b0265c643bcfcb775619cd13ce5c
f244260d34326940778530d7432ac1d8cfdc7cc7
refs/heads/master
2023-02-07T15:18:44.266459
2016-08-30T01:01:59
2016-08-30T01:01:59
null
0
0
null
null
null
null
UTF-8
R
false
false
4,091
r
gradient.R
ds$grad.log.density <- function(theta,y){ ## Evaluates the gradient of the likelihood function of ZIBB ## given theta and the data (y) y <-r lastcol <- ncol(y) y1 <- y[,lastcol] X <- y[,1:ncol(y)-1] ones <- rep(1,nrow(y)) X <- cbind(ones,X) n <- 10 rho <- theta[length(theta)] phi <- (1-rho)/rho B <- theta[c(1:length(theta)-1)] Alpha <- B[c(1,2,3)] Gamma <- B[c(4,5,6)] Beta <- Gamma + exp(Alpha) pi <- sigmoid(X%*%Beta) mupi <- sigmoid(X%*%Gamma) mu <- mupi/pi gradb <- vector() gradt <- vector() P2 <- gamma(n+phi) P1 <- gamma(phi) der <- matrix(nrow=length(y1),ncol=7) for (i in 1:length(y1)){ cb <- (mupi[i]/(pi[i])^2)*(1-pi[i])*(pi[i]) ct <- (1/pi[i])*(mupi[i])*(1-mupi[i]) gradb <- cb*X[i,] ## Derivatives of mu w.r.t beta(gradb) and theta(gradt) gradt <- ct*X[i,] grad <- append(gradb,gradt) if(y1[i] != 0){ a <- phi*mu[i] b <- phi*(1-mu[i]) ## derivative w.r.t thetas ( all params except phi) T2mu <- digamma(y1[i]+a)*(phi*grad) + digamma(n-y1[i]+b)*(-phi*grad) - digamma(a)*(phi*grad) - digamma(b)*(-phi*grad) ## derivative w.r.t phi T2phi <- digamma(y1[i]+a)*mu[i] + digamma(n-y1[i]+b)*(1-mu[i]) - digamma(n+phi) + digamma(phi) - digamma(a)*mu[i] - digamma(b)*(1-mu[i]) app <- append(T2mu,T2phi) der[i,] <- app }else{ R <- beta(y[i]+mu[i]*phi,n-y[i]+phi*(1-mu[i]))/beta(phi*mu[i],phi*(1-mu[i])) A1 <- pi[i]*choose(n,y1[i])/(1-pi[i] + pi[i]*choose(n,y1[i])*R) a <- phi*mu[i] b <- phi*(1-mu[i]) D1 <- gamma(a) D2 <- gamma(b) D3 <- gamma(y1[i]+ a) D4 <- gamma(n-y1[i]+ b) C <- A1*gamma(phi)/gamma(n+phi) ## derivative w.r.t thetas ( all params except phi) T1mu <- (C/(gamma(a)*gamma(b))^2)*( D1*D2*(D3*D4*digamma(n-y1[i]+b)*(-phi*grad) + D4*D3*digamma(y1[i]+a)*(phi*grad)) - D3*D4*(D1*D2*digamma(b)*(-phi*grad) + D2*D1*digamma(a)*(phi*grad)) ) ## derivative w.r.t phi T1phi <- (A1/(gamma(n+phi)*gamma(a)*gamma(b))^2)*(P2*D1*D2*(P1*D3*D4*digamma(n-y1[i]+b)*(1-mu[i]) + P1*D4*D3*digamma(y1[i]+a)*(mu[i]) + D3*D4*P1*digamma(phi)) - P1*D3*D4*(P2*D1*D2*digamma(b)*(1-mu[i]) + P2*D2*D1*digamma(a)*(mu[i]) + D1*D2*P2*digamma(n+phi)) ) der[i,] <- append(T1mu,T1phi) } } derfinal <- colSums(der) derfinal1 <- -derfinal }
10d263818c6348b283da45721496bd4e165e2c21
bbd9ca286fd2289c9576aaea736b5519dab035f4
/Tester3.R
0819c96af394ab36ac34452e9dfdd00e311caafa
[]
no_license
KevLeeKL/Tester3-import-local-pj
791c94803f91959e6dbd7cd2f5bdce8e754905ef
d0d3a716bf19507dd553b6af12a6cb02f93567fe
refs/heads/master
2022-08-05T19:13:42.393428
2020-05-25T19:16:21
2020-05-25T19:16:21
266,860,539
0
0
null
null
null
null
UTF-8
R
false
false
237
r
Tester3.R
mean(mtcars$mpg) library(help='base') head(iris) summary(iris$Species) install.packages('devtools') library(devtools) help(package = 'ggplot2') help(package = 'devtools') sessionInfo() install.packages('KernSmooth') library(KernSmooth)
e33f688d6393fa10ad4ad5c60396151408d44759
696e530b91e3c64a7ffae95f227b31b16c43e9a2
/R/copykat_no_heatmap.R
13ef57f9cea8bcb8002a1d3078749c5e7557b477
[ "MIT" ]
permissive
abelson-lab/scATOMIC
c56520ce594000737ddb242d473a81129c5c8110
bc7adc8486d70b980af149283e85c84e5f7c9abd
refs/heads/main
2023-08-03T08:10:04.592709
2023-07-19T13:18:50
2023-07-19T13:18:50
418,635,282
31
3
null
null
null
null
UTF-8
R
false
false
13,410
r
copykat_no_heatmap.R
#' copy_kat_no_heatmap #' #' @param rawmat matrix of counts #' @param id.type set S if gene names #' @param cell.line set to no for tissues #' @param ngene.chr minimum nchrm, for my tool i use 0 as i want every cell included #' @param LOW.DR minimal population fractions of genes for smoothing. #' @param UP.DR minimal population fractions of genes for segmentation. #' @param win.size minimal window sizes for segmentation. #' @param norm.cell.names vector of normal cells use the blood and stromal from the classifier #' @param KS.cut segmentation parameters, input 0 to 1; larger looser criteria. #' @param sam.name sample name. #' @param distance default eucledian #' @param n.cores for parallel computing #' #' @return returns a CNV matrix for use in create_summary_matrix #' @export #function is code modified from Gao R. 2021 https://github.com/navinlabcode/copykat copy_kat_no_heatmap <- function (rawmat = rawdata,summary_matrix, id.type = "S", cell.line = "no", ngene.chr = 5, LOW.DR = 0.05, UP.DR = 0.1, win.size = 25, KS.cut = 0.1, sam.name = "", distance = "euclidean", n.cores = (detectCores() - 1)) { if(.Platform$OS.type == "windows"){ mc.cores = 1 n.cores = 1 } start_time <- Sys.time() if(length(which(duplicated(row.names(rawmat))))> 0){ rawmat <- rawmat[-which(duplicated(row.names(rawmat))),] } norm.cell.names = row.names(summary_matrix)[which(summary_matrix$layer_1 == "Blood_Cell" | summary_matrix$layer_2 %in% c("Endothelial Cells", "Stromal Cell", "Oligodendrocytes"))] set.seed(1) sample.name <- paste(sam.name, "_copykat_", sep = "") print("step1: read and filter data ...") print(paste(nrow(rawmat), " genes, ", ncol(rawmat), " cells in raw data", sep = "")) genes.raw <- apply(rawmat, 2, function(x) (sum(x > 0))) if (sum(genes.raw > 200) == 0) stop("none cells have more than 200 genes") if (sum(genes.raw < 100) > 1) { rawmat <- rawmat[, -which(genes.raw < 200)] print(paste("filtered out ", sum(genes.raw <= 200), " cells with less than 200 genes; remaining ", ncol(rawmat), " cells", sep = "")) } der <- apply(rawmat, 1, function(x) (sum(x > 0)))/ncol(rawmat) if (sum(der > LOW.DR) >= 1) { rawmat <- rawmat[which(der > LOW.DR), ] print(paste(nrow(rawmat), " genes past LOW.DR filtering", sep = "")) } WNS1 <- "data quality is ok" if (nrow(rawmat) < 7000) { WNS1 <- "low data quality" UP.DR <- LOW.DR print("WARNING: low data quality; assigned LOW.DR to UP.DR...") } print("step 2: annotations gene coordinates ...") anno.mat <- annotateGenes.hg20(mat = rawmat, ID.type = id.type) anno.mat <- anno.mat[order(anno.mat$abspos, decreasing = FALSE), ] HLAs <- anno.mat$hgnc_symbol[grep("^HLA-", anno.mat$hgnc_symbol)] toRev <- which(anno.mat$hgnc_symbol %in% c(as.vector(cyclegenes[[1]]), HLAs)) if (length(toRev) > 0) { anno.mat <- anno.mat[-toRev, ] } ToRemov2 <- NULL for (i in 8:ncol(anno.mat)) { cell <- cbind(anno.mat$chromosome_name, anno.mat[, i]) cell <- cell[cell[, 2] != 0, ] if (length(as.numeric(cell)) < 5) { rm <- colnames(anno.mat)[i] ToRemov2 <- c(ToRemov2, rm) } else if (length(rle(cell[, 1])$length) < 23 | min(rle(cell[, 1])$length) < ngene.chr) { rm <- colnames(anno.mat)[i] ToRemov2 <- c(ToRemov2, rm) } i <- i + 1 } if (length(ToRemov2) == (ncol(anno.mat) - 7)) stop("all cells are filtered") if (length(ToRemov2) > 0) { anno.mat <- anno.mat[, -which(colnames(anno.mat) %in% ToRemov2)] } rawmat3 <- data.matrix(anno.mat[, 8:ncol(anno.mat)]) norm.mat <- log(sqrt(rawmat3) + sqrt(rawmat3 + 1)) norm.mat <- apply(norm.mat, 2, function(x) (x <- x - mean(x))) colnames(norm.mat) <- colnames(rawmat3) print("step 3: smoothing data with dlm ...") dlm.sm <- function(c) { model <- dlm::dlmModPoly(order = 1, dV = 0.16, dW = 0.001) x <- dlm::dlmSmooth(norm.mat[, c], model)$s x <- x[2:length(x)] x <- x - mean(x) } test.mc <- parallel::mclapply(1:ncol(norm.mat), dlm.sm, mc.cores = n.cores) norm.mat.smooth <- matrix(unlist(test.mc), ncol = ncol(norm.mat), byrow = FALSE) colnames(norm.mat.smooth) <- colnames(norm.mat) print("step 4: measuring baselines ...") if (cell.line == "yes") { print("running pure cell line mode") relt <- baseline.synthetic(norm.mat = norm.mat.smooth, min.cells = 10, n.cores = n.cores) norm.mat.relat <- relt$expr.relat CL <- relt$cl WNS <- "run with cell line mode" preN <- NULL } else if (length(norm.cell.names) > 1) { NNN <- length(colnames(norm.mat.smooth)[which(colnames(norm.mat.smooth) %in% norm.cell.names)]) print(paste(NNN, " known normal cells found in dataset", sep = "")) if (NNN == 0) stop("known normal cells provided; however none existing in testing dataset") print("run with known normal...") basel <- apply(norm.mat.smooth[, which(colnames(norm.mat.smooth) %in% norm.cell.names)], 1, median) print("baseline is from known input") d <- parallelDist::parDist(t(norm.mat.smooth), threads = n.cores, method = "euclidean") km <- 6 fit <- hclust(d, method = "ward.D2") CL <- cutree(fit, km) while (!all(table(CL) > 5)) { km <- km - 1 CL <- cutree(fit, k = km) if (km == 2) { break } } WNS <- "run with known normal" preN <- norm.cell.names norm.mat.relat <- norm.mat.smooth - basel } else { basa <- baseline.norm.cl(norm.mat.smooth = norm.mat.smooth, min.cells = 5, n.cores = n.cores) basel <- basa$basel WNS <- basa$WNS preN <- basa$preN CL <- basa$cl if (WNS == "unclassified.prediction") { Tc <- colnames(rawmat)[which(as.numeric(apply(rawmat[which(rownames(rawmat) %in% c("PTPRC", "LYZ", "PECAM1")), ], 2, mean)) > 1)] length(Tc) preN <- intersect(Tc, colnames(norm.mat.smooth)) if (length(preN) > 5) { print("start manual mode") WNS <- paste("copykat failed in locating normal cells; manual adjust performed with ", length(preN), " immune cells", sep = "") print(WNS) basel <- apply(norm.mat.smooth[, which(colnames(norm.mat.smooth) %in% preN)], 1, mean) } else { basa <- baseline.GMM(CNA.mat = norm.mat.smooth, max.normal = 5, mu.cut = 0.05, Nfraq.cut = 0.99, RE.before = basa, n.cores = n.cores) basel <- basa$basel WNS <- basa$WNS preN <- basa$preN } } norm.mat.relat <- norm.mat.smooth - basel } DR2 <- apply(rawmat3, 1, function(x) (sum(x > 0)))/ncol(rawmat3) norm.mat.relat <- norm.mat.relat[which(DR2 >= UP.DR), ] anno.mat2 <- anno.mat[which(DR2 >= UP.DR), ] ToRemov3 <- NULL for (i in 8:ncol(anno.mat2)) { cell <- cbind(anno.mat2$chromosome_name, anno.mat2[, i]) cell <- cell[cell[, 2] != 0, ] if (length(as.numeric(cell)) < 5) { rm <- colnames(anno.mat2)[i] ToRemov3 <- c(ToRemov3, rm) } else if (length(rle(cell[, 1])$length) < 23 | min(rle(cell[, 1])$length) < ngene.chr) { rm <- colnames(anno.mat2)[i] ToRemov3 <- c(ToRemov3, rm) } i <- i + 1 } if (length(ToRemov3) == ncol(norm.mat.relat)) stop("all cells are filtered") if (length(ToRemov3) > 0) { norm.mat.relat <- norm.mat.relat[, -which(colnames(norm.mat.relat) %in% ToRemov3)] } CL <- CL[which(names(CL) %in% colnames(norm.mat.relat))] CL <- CL[order(match(names(CL), colnames(norm.mat.relat)))] print("step 5: segmentation...") results <- CNA.MCMC(clu = CL, fttmat = norm.mat.relat, bins = win.size, cut.cor = KS.cut, n.cores = n.cores) if (length(results$breaks) < 25) { print("too few breakpoints detected; decreased KS.cut to 50%") results <- CNA.MCMC(clu = CL, fttmat = norm.mat.relat, bins = win.size, cut.cor = 0.5 * KS.cut, n.cores = n.cores) } if (length(results$breaks) < 25) { print("too few breakpoints detected; decreased KS.cut to 75%") results <- CNA.MCMC(clu = CL, fttmat = norm.mat.relat, bins = win.size, cut.cor = 0.5 * 0.5 * KS.cut, n.cores = n.cores) } if (length(results$breaks) < 25) stop("too few segments; try to decrease KS.cut; or improve data") colnames(results$logCNA) <- colnames(norm.mat.relat) results.com <- apply(results$logCNA, 2, function(x) (x <- x - mean(x))) RNA.copycat <- cbind(anno.mat2[, 1:7], results.com) print("step 6: convert to genomic bins...") Aj <- convert.all.bins.hg20(DNA.mat = DNA.hg20, RNA.mat = RNA.copycat, n.cores = n.cores) uber.mat.adj <- data.matrix(Aj$RNA.adj[, 4:ncol(Aj$RNA.adj)]) print("step 7: adjust baseline ...") if (cell.line == "yes") { mat.adj <- data.matrix(Aj$RNA.adj[, 4:ncol(Aj$RNA.adj)]) if (distance == "euclidean") { hcc <- hclust(parallelDist::parDist(t(mat.adj), threads = n.cores, method = distance), method = "ward.D") } else { hcc <- hclust(as.dist(1 - cor(mat.adj, method = distance)), method = "ward.D") } end_time <- Sys.time() print(end_time - start_time) reslts <- list(cbind(Aj$RNA.adj[, 1:3], mat.adj), hcc) names(reslts) <- c("CNAmat", "hclustering") return(reslts) } else { if (distance == "euclidean") { hcc <- hclust(parallelDist::parDist(t(uber.mat.adj), threads = n.cores, method = distance), method = "ward.D") } else { hcc <- hclust(as.dist(1 - cor(uber.mat.adj, method = distance)), method = "ward.D") } hc.umap <- cutree(hcc, 2) names(hc.umap) <- colnames(results.com) cl.ID <- NULL for (i in 1:max(hc.umap)) { cli <- names(hc.umap)[which(hc.umap == i)] pid <- length(intersect(cli, preN))/length(cli) cl.ID <- c(cl.ID, pid) i <- i + 1 } com.pred <- names(hc.umap) com.pred[which(hc.umap == which(cl.ID == max(cl.ID)))] <- "diploid" com.pred[which(hc.umap == which(cl.ID == min(cl.ID)))] <- "nondiploid" names(com.pred) <- names(hc.umap) results.com.rat <- uber.mat.adj - apply(uber.mat.adj[, which(com.pred == "diploid")], 1, mean) results.com.rat <- apply(results.com.rat, 2, function(x) (x <- x - mean(x))) results.com.rat.norm <- results.com.rat[, which(com.pred == "diploid")] dim(results.com.rat.norm) cf.h <- apply(results.com.rat.norm, 1, sd) base <- apply(results.com.rat.norm, 1, mean) adjN <- function(j) { a <- results.com.rat[, j] a[abs(a - base) <= 0.25 * cf.h] <- mean(a) a } mc.adjN <- parallel::mclapply(1:ncol(results.com.rat), adjN, mc.cores = n.cores) adj.results <- matrix(unlist(mc.adjN), ncol = ncol(results.com.rat), byrow = FALSE) colnames(adj.results) <- colnames(results.com.rat) rang <- 0.5 * (max(adj.results) - min(adj.results)) mat.adj <- adj.results/rang print("step 8: final prediction ...") if (distance == "euclidean") { hcc <- hclust(parallelDist::parDist(t(mat.adj), threads = n.cores, method = distance), method = "ward.D") } else { hcc <- hclust(as.dist(1 - cor(mat.adj, method = distance)), method = "ward.D") } hc.umap <- cutree(hcc, 2) names(hc.umap) <- colnames(results.com) cl.ID <- NULL for (i in 1:max(hc.umap)) { cli <- names(hc.umap)[which(hc.umap == i)] pid <- length(intersect(cli, preN))/length(cli) cl.ID <- c(cl.ID, pid) i <- i + 1 } com.preN <- names(hc.umap) com.preN[which(hc.umap == which(cl.ID == max(cl.ID)))] <- "diploid" com.preN[which(hc.umap == which(cl.ID == min(cl.ID)))] <- "aneuploid" names(com.preN) <- names(hc.umap) if (WNS == "unclassified.prediction") { com.preN[which(com.preN == "diploid")] <- "c1:diploid:low.conf" com.preN[which(com.preN == "nondiploid")] <- "c2:aneuploid:low.conf" } print("step 9: saving results...") res <- cbind(names(com.preN), com.preN) colnames(res) <- c("cell.names", "copykat.pred") end_time <- Sys.time() print(end_time - start_time) return(res) } }
f41573b7731bce5e3292d4d23c0e5760e86f7e7f
e89658aa8eae0c384c0b9ae0c47045cdad5d7341
/grizz def reb rate.R
350086dc8ed601c3aaa9c026f3dc048e593986bd
[]
no_license
ramirobentes/NBA-in-R
0d036a4cfe49c5ccf5eadec6c642b3c295321351
3aa845788ac447f4ccf8127e595adebf5e6ad4e1
refs/heads/master
2023-08-30T13:48:25.595147
2023-08-17T18:26:29
2023-08-17T18:26:29
230,468,326
31
2
null
null
null
null
UTF-8
R
false
false
3,060
r
grizz def reb rate.R
library(tidyverse) library(nbastatR) final_poss_pack <- read_csv("https://github.com/ramirobentes/NBA-in-R/releases/download/final-poss-pack-42862e5/data.csv", col_types = c(timeQuarter = "c", start_poss = "c")) %>% mutate(across(starts_with("description"), ~ coalesce(., ""))) # url above might change daily team_logs <- game_logs(seasons = 2022, result_types = "team") # put every missed shot and rebound in order shots_rebs <- final_poss_pack %>% filter(numberEventMessageType %in% c(2, 4) | numberEventMessageType == 3 & shotPtsHome + shotPtsAway == 0) %>% mutate(slugTeamPlayer1 = case_when(is.na(slugTeamPlayer1) & descriptionPlayHome == "" ~ slugTeamAway, is.na(slugTeamPlayer1) & descriptionPlayVisitor == "" ~ slugTeamHome, TRUE ~ slugTeamPlayer1)) %>% group_by(idGame, numberPeriod, shot_reb = ifelse(numberEventMessageType == 4, "rebound", "shot")) %>% mutate(sequence_num = row_number()) %>% ungroup() %>% arrange(idGame, numberPeriod, sequence_num) %>% mutate(desc_type = case_when(numberEventMessageType == 4 & slugTeamPlayer1 == lag(slugTeamPlayer1) ~ "off reb", numberEventMessageType == 4 & slugTeamPlayer1 != lag(slugTeamPlayer1) ~ "def reb", TRUE ~ "missed shot")) %>% filter(!(numberEventMessageType == 3 & numberEventActionType %in% c(11, 13, 14, 16, 18:22, 25, 27:29))) %>% filter(!(desc_type == "def reb" & numberEventMessageType == 4 & numberEventActionType == 1)) %>% mutate(lineup_team = ifelse(slugTeamPlayer1 == slugTeamHome, lineupHome, lineupAway), lineup_opp = ifelse(slugTeamPlayer1 == slugTeamHome, lineupAway, lineupHome)) %>% select(idGame, numberPeriod, timeQuarter, numberEventMessageType, numberEventActionType, slugTeam = slugTeamPlayer1, descriptionPlayHome, descriptionPlayVisitor, desc_type, lineup_team, lineup_opp) %>% left_join(team_logs %>% distinct(idGame, slugTeam, slugOpponent, dateGame)) %>% mutate(slugTeam = case_when(slugTeam == "MEM" & str_detect(lineup_team, "Steven Adams") ~ "MEM with Adams", slugTeam == "MEM" & !str_detect(lineup_team, "Steven Adams") ~ "MEM without Adams", TRUE ~ slugTeam), slugOpponent = case_when(slugOpponent == "MEM" & str_detect(lineup_opp, "Steven Adams") ~ "MEM with Adams", slugOpponent == "MEM" & !str_detect(lineup_opp, "Steven Adams") ~ "MEM without Adams", TRUE ~ slugOpponent)) shots_rebs %>% filter(desc_type == "def reb") %>% count(slugTeam, name = "def_reb") %>% left_join(shots_rebs %>% filter(desc_type == "missed shot") %>% count(slugTeam = slugOpponent, name = "def_reb_chances")) %>% mutate(def_reb_pct = round(def_reb / def_reb_chances, 4)) %>% arrange(-def_reb_pct)
0ab35ddfa07e1cdb51cd70283523f416124d6ad0
64257a0e57cf928b0ae7676a108a3688001181bd
/R/data.R
bb7971de8b45e2cabdb2a9552db7a7c532270ce4
[ "BSD-3-Clause" ]
permissive
marcpaterno/artsupport
9842a678c8070468dd93a258810b84067fe22f32
803310561741c4aa54bdd44e393da9ae8551bfa0
refs/heads/master
2020-06-30T06:49:04.780687
2020-04-20T23:14:48
2020-04-20T23:14:48
74,387,093
0
1
NOASSERTION
2019-02-07T07:11:33
2016-11-21T17:15:33
R
UTF-8
R
false
false
1,309
r
data.R
#' art event timing data for 240 events. #' #' Several datasets containing the data recorded by the *art* framework's Timing service. #' #' The event-by-event timing data written into the `TimeEvent` table, which contains one record per event. #' @format A tibble with 240 observatoins of 5 variables: #' \describe{ #' \item{Run}{the run number} #' \item{SubRUn}{the subrun number} #' \item{Event}{the event number} #' \item{Time}{event processing time in seconds} #' \item{sample}{sample id, an integer unique for each event} #' } "events" #' The module-by-module timing data written into the `TimeModule` table, which contains one record #' per module for each event. The recorded art process used 3 modules on just 1 path. There is also #' a record for the TriggerResults 'module'. #' @format A tibble with 960 observatios of 8 variables: #' \describe{ #' \item{Run}{the run number} #' \item{SubRun}{the subrun number} #' \item{Event}{the event number} #' \item{Path}{the path on which the module ran; note that one module can appear on multiple paths} #' \item{ModuleLabel}{the label of the module} #' \item{ModuleType}{the C++ class of the module} #' \item{Time}{module executon time in seconds} #' \item{sample}{sample id, and integer unique for each event} #' } "modules"
3e4d29718e940554cd27816c40e056a7f6a4934c
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/colorpatch/examples/DistColorFun.Rd.R
5075a3db7d6a822773bc199072eba4f9550de615
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
264
r
DistColorFun.Rd.R
library(colorpatch) ### Name: DistColorFun ### Title: Creates a color distance function ### Aliases: DistColorFun ### ** Examples library(colorspace) library(colorpatch) fn <- DistColorFun("LUV") a <- sRGB(1,0,0) b <- sRGB(0.8,0.1,0) my.distance <- fn(a,b)
5b06821d5b3578f4b4296defe623614bcb460bec
fc36112ec2687ee3a56086fc121a8e8101c5d62c
/man/validate_table_quote_character.Rd
ae658c27fd65e31dfce0c497f74ff269fc1ed7bf
[ "MIT" ]
permissive
EDIorg/EMLassemblyline
ade696d59147699ffd6c151770943a697056e7c2
994f7efdcaacd641bbf626f70f0d7a52477c12ed
refs/heads/main
2023-05-24T01:52:01.251503
2022-11-01T01:20:31
2022-11-01T01:20:31
84,467,795
36
17
MIT
2023-01-10T01:20:56
2017-03-09T17:04:28
R
UTF-8
R
false
true
528
rd
validate_table_quote_character.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/validate_arguments.R \name{validate_table_quote_character} \alias{validate_table_quote_character} \title{Validate data table quote characters} \usage{ validate_table_quote_character(fun.args) } \arguments{ \item{fun.args}{(named list) Function arguments and their values.} } \value{ \item{issues}{Description of issues} \item{fun.args}{Updated list of function arguments} } \description{ Validate data table quote characters } \keyword{internal}
5ab619cdad7b676531f913346b8b9c4b43ccc7bb
26c2b1e98c34d865b51202188551239de8f1b500
/man/l.small.Rd
71701897de3be86836a562b3e3a407ecfcc53930
[]
no_license
cran/LogicOpt
a88799844bd3b3c60e73dad2dae2e9acd0381beb
cad5a27882670bf7c4c3680a0e0e3550359ad33a
refs/heads/master
2020-12-22T00:57:09.661699
2016-05-07T01:27:50
2016-05-07T01:27:50
236,621,369
0
0
null
null
null
null
UTF-8
R
false
true
555
rd
l.small.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/l.small-data.R \docType{data} \name{l.small} \alias{l.small} \title{Espresso truth table with 4 inputs and 3 outputs} \format{R data frame table} \usage{ data(l.small) } \description{ Espresso compatible truth table generated from espresso format file small.esp. } \examples{ \dontrun{ # steps to recreate inpath <- system.file("extdata/espresso/small.esp", package="LogicOpt") l.small <- logicopt(esp_file=inpath,mode="echo")[1] } } \keyword{Espresso} \keyword{truth-table}
1f327402f03d4c659433c5c84f0b38693edece7b
a4c6dcffc21de8138403a3d0348bf4efe8736f1e
/MyFirstShinyApplication/server.R
05b49b13b34a673c3035990fa4f3e940406dddf2
[]
no_license
ricardorac/ddp_final
c576258b9b015bb7fd7109e6fe428766cb9082ba
9fbc5984b2b49b12b6e43d3c4880408ee5a89708
refs/heads/master
2022-09-20T05:32:38.773047
2020-06-05T12:29:09
2020-06-05T12:29:09
265,584,403
0
0
null
null
null
null
UTF-8
R
false
false
6,779
r
server.R
# # This is the server logic of a Shiny web application. You can run the # application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) library(lgrdata) library(ggplot2) library(RColorBrewer) library(caret) data(anthropometry) set.seed(1979) anthropometry <- anthropometry[complete.cases(anthropometry), ] inTrain = createDataPartition(anthropometry$height, p = 0.8)[[1]] testing = anthropometry[-inTrain, ] training = anthropometry[inTrain, ] trainCtrl <- trainControl(method = "cv", savePredictions = "none", number = 3) RMSE <- function(m, o) { sqrt(mean((m - o) ^ 2)) } pal <- "Set1" shinyServer(function(input, output) { formula <- "" model <- reactive({ if (input$buildModelButton) { selMethod <- input$modelInput selPred <- c() if (input$addFootLength) { selPred <- c(selPred, "foot_length") } if (input$addAge) { selPred <- c(selPred, "age") } if (input$addGender) { selPred <- c(selPred, "gender") } if (length(selPred) == 0) { return(NULL) } selFormula <- as.formula(paste("height", paste(selPred, collapse = " + "), sep = " ~ ")) modFit <- train( selFormula, method = selMethod, data = training, trControl = trainCtrl, model = FALSE ) modFit } else { return(NULL) } }) modelFootLength <- reactive({ brushed_data <- brushedPoints( anthropometry, input$brushHeightFootLength, xvar = "foot_length", yvar = "height" ) if (nrow(brushed_data) < 2) { return(NULL) } lm(height ~ foot_length, data = brushed_data) }) output$dataSummaryOut <- renderPrint( summary(anthropometry) ) output$rmseOnTesting <- reactive({ if (input$buildModelButton) { modFit <- model() if (is.null(modFit)) { return("You have to build a model first.") } else { pred <- predict(modFit, testing) return(paste( "RMSE on testing samples: ", RMSE(pred, testing$height), " (expected out-of-sample RMSE)" )) } } }) output$rmseOnTraining <- reactive({ if (input$buildModelButton) { modFit <- model() if (is.null(modFit)) { return("You have to build a model first.") } else { pred <- predict(modFit, training) return(paste( "RMSE on training samples: ", RMSE(pred, training$height) )) } } }) output$textPrediction <- reactive({ if (input$predictButton) { modFit <- model() if (is.null(modFit)) { return("You have to build a model first.") } else { toPred <- data.frame( age = as.numeric(input$ageValue), foot_length = as.numeric(input$footLengthValue), gender = input$genderValue ) pred <- predict(modFit, toPred) return(paste("The predicted Height (in cm) is ", pred[[1]])) } } }) output$modelOutput <- renderPrint({ modFit <- model() if (!is.null(modFit)) { return(summary(modFit$finalModel)) } }) output$plotModel <- renderPlot({ modFit <- model() if (!is.null(modFit)) { predicted <- predict(modFit, training) predictedDF <- data.frame(pred_height = predicted, age = training$age) g <- ggplot(training, aes(y = height)) + scale_color_brewer(palette = pal) g <- g + geom_point(aes(x = age, colour = gender)) + ggtitle("Predicted Height") + xlab("Age") + ylab("Height") g + geom_smooth( color = 'green', data = predictedDF, aes(x = age, y = pred_height), size = 2 ) } }) output$plotHeightFootLength <- renderPlot({ anthropometry <- anthropometry[complete.cases(anthropometry), ] g <- ggplot(anthropometry, aes(y = height)) + scale_color_brewer(palette = pal) g <- g + geom_point(aes(x = foot_length, colour = gender)) + ggtitle("Height by Foot Length") + xlab("Foot length") + ylab("Height") if (!is.null(modelFootLength())) { intrcpt <- coef(modelFootLength())["(Intercept)"] slp <- coef(modelFootLength())["foot_length"] g <- g + geom_abline( slope = slp, intercept = , color = "green", size = 2 ) } g }) output$slopeOut <- reactive({ if (!is.null(modelFootLength())) { return(paste(coef(modelFootLength())["foot_length"])) } }) output$interceptOut <- reactive({ if (!is.null(modelFootLength())) { return(paste(coef(modelFootLength())["(Intercept)"])) } }) output$plot1 <- renderPlot({ anthropometry <- anthropometry[complete.cases(anthropometry), ] g <- ggplot(anthropometry, aes(y = height)) + scale_color_brewer(palette = pal) g + geom_point(aes(x = age, colour = gender)) + ggtitle("Height by Age") + xlab("Age") + ylab("Height") }) output$plot2 <- renderPlot({ anthropometry <- anthropometry[complete.cases(anthropometry), ] g <- ggplot(anthropometry, aes(y = height)) + scale_color_brewer(palette = pal) g + geom_point(aes(x = foot_length, colour = gender)) + ggtitle("Height by Foot length") + xlab("Foot length") + ylab("Height") }) output$plot3 <- renderPlot({ anthropometry <- anthropometry[complete.cases(anthropometry), ] g <- ggplot(anthropometry, aes(y = height)) + scale_fill_brewer(palette = pal) g + geom_boxplot(aes(x = gender, fill = gender)) + ggtitle("Height by Gender") + xlab("Gender") + ylab("Height") }) })
62a8e5b0ac0a92c89b121cc2df577a0a21a206e1
7538c1f30b9c46d3901cae4c47e20f9a6e57f80e
/L01B2.isimip_nobias_global_processing.R
70a402ecb720201d3f8138b7c78a55a82b19248c
[]
no_license
JGCRI/frontEnd_grandExp
2e804320fc98d1f39a4389abf035652ff08cbbb8
bc09667e9aff9f7fe6aa6d12d145b3b4523f6b81
refs/heads/master
2020-03-28T21:32:13.983743
2018-10-12T17:05:44
2018-10-12T17:05:44
149,162,531
0
0
null
null
null
null
UTF-8
R
false
false
8,548
r
L01B2.isimip_nobias_global_processing.R
# Purpose: Because the bias corrected ISIMIP netcdfs only includes values over land and fldgen # requires a global mean average this script processes the no bias corrected monthly # output to a annual global average. # Users should check that all the directories defined in section 0 exists and should check # out section 1 for decisions about what isimip files to search for. # TODO may be we want to include some code that will check to see if we have all the global # averages we need to train the fldgen emulator? Might have to update the script so that # the output includes a column name and a years column # 0. Set Up ----------------------------------------------------------------------------- showMessages <- TRUE # a T/F to suppress or show script messages if(showMessages) message('0. Set Up') library(dplyr) library(tidyr) library(tibble) library(purrr) BASE <- "/pic/projects/GCAM/Dorheim/frontEnd_grandExp" # The project location on pic CDO_DIR <- "/share/apps/netcdf/4.3.2/gcc/4.4.7/bin/cdo" # Define the cdo directory ISIMIP_DIR <- "/pic/projects/GCAM/leng569/CMIP5" # The location of the isimip files on pic INTER_DIR <- '/pic/scratch/dorh012' # The intermediate dir to write things out to OUTPUT_DIR <- file.path(BASE, "output-L1", "annual_isimip"); dir.create(OUTPUT_DIR, showWarnings = FALSE, recursive = TRUE) # 1. User Decisions ----------------------------------------------------------------------------------------------------- # Select the ismip variables, experiment, model, and so on to process. The strings listed in each of the # vectors will be used in a search pattern to identify the files to process from the ISIMIP_DIR. We are interested # in the biased correct files and they have the following file pattern. If the vector is set to NULL then the # pattern will search for all options. # variable_bced_1960_1999_model_experiment_startYr-endYr.nc4 if(showMessages) message('1. User Decisions') # isimip search vectors VARIABLES <- c("tas") # isimip variables to process EXPERIMENTS <- c("rcp45", "rcp26", "rcp85", "rcp60") # isimip experiments to process MODELS <- "IPSL-CM5A-LR" # isimip models to process ENSEMBLES <- "r1i1p1" # the ensemble number # 2. Find the isimip files to process ----------------------------------------------------------------------------------------------------- # Create the search netcdf search pattern and then search the isimip directory. if(showMessages) message('2. Find the isimip files to process') # pattern_gen is a function that converts the isimip search vectors from section # into strings that will be used to create the regex search pattern. If the # input vector is set to NULL then the function will return a search all pattern. pattern_gen <- function(vector){ if(is.null(vector)){ "[a-zA-Z0-9-]+" } else { paste(vector, collapse = "|") } } varpattern <- pattern_gen(VARIABLES) modelpattern <- pattern_gen(MODELS) experimentpattern <- pattern_gen(EXPERIMENTS) ensemblepattern <- pattern_gen(ENSEMBLES) # Create the pattern for the isimip file names for the netcdfs to search for. isimip_search_pattern <- paste("(regridded)_(1deg)_(", varpattern, ")_(Amon)_(", modelpattern, ")_(", experimentpattern, ")_(", ensemblepattern, ')_', "([0-9]{6})-([0-9]{6}", # time, set up to search for any 6 digit date ").nc$", sep = "") # Sanity check if(showMessages) message("isimip file search pattern: ", isimip_search_pattern, "\n") # Search for the files file_list <- list.files(ISIMIP_DIR, pattern = isimip_search_pattern, full.names = TRUE, recursive = TRUE) # Sanity check if(length(file_list) < 1) stop('Could not find any isimip files files matching ', isimip_search_pattern) # Parse out the run meta information from the file_list tibble(path = file_list) %>% separate(path, into = c('A', 'B', 'variable', 'C', 'model', 'experiment', 'ensemble', 'yrs'), remove = FALSE, sep = '_' ) -> to_process # 4. Process to global annual average ------------------------------------------------------------------- # Because we need a global annual average but only have access to monthly gridded nobias corrected data # we will use CDO to process to the correct data. if(showMessages) message('4. Process to global annual average') # Create a mapping file to use to name the output so that it is compatible with the isismip # bias corrected files. tibble(experiment = c('rcp26', 'rcp45', 'rcp60', 'rcp85'), new_experiment = c('rcp2p6', 'rcp4p5', 'rcp6p0', 'rcp8p5')) %>% mutate(model = rep("IPSL-CM5A-LR", nrow(.)), new_model = rep("ipsl-cm5a-lr", nrow(.))) -> mapping_names # The fldgen training function will want txt files with the format # variable_annual_model_experiment_ensemble_start-end.ncglobalAvg.txt # So this function will use a mapping file to rename models / experiments to # match the isimip bias corrected nomenclature. annual_globalAvg_func <- function(df, cdo_dir, inter_dir, output_dir, mapping = mapping_names, showMessages = FALSE, removeIntermediate = TRUE){ # This function depends on CDO (https://code.zmaw.de/projects/cdo) being installed stopifnot(file.exists(cdo_dir)) stopifnot(dir.exists(inter_dir)) stopifnot(dir.exists(output_dir)) # Based on the isimip file information create the output file name. interOut1_nc <- file.path(inter_dir, paste0('inter-annual_avg-', basename(df[['path']]))) interOut2_nc <- file.path(inter_dir, paste0('inter-global_avg-', basename(df[['path']]))) # Get the global annual average. # TODO in theory this could be accomplished by a single if(showMessages) message("Convert to absolute time and annual average ", df[['path']]) system2(cdo_dir, args = c("-a", "yearmean", df[['path']], interOut1_nc), stdout = TRUE, stderr = TRUE) if(showMessages) message("Calculate global average ", df[['path']]) system2(cdo_dir, args = c("fldmean", interOut1_nc, interOut2_nc), stdout = TRUE, stderr = TRUE) # Extract the data from the global annual average nc to save as the txt file. # TODO it looks like the isimip data only includes values to 2099, we will want to # subset the results to match the number of years in the bias corrected data. nc <- nc_open(interOut2_nc) nc_time <- ncvar_get(nc, 'time') nc_data <- ncvar_get(nc, df[['variable']]) nc_units <- ncatt_get(nc, df[['variable']], 'units')[['value']] # The bias corrected data temp is in K so if we run into an issue where the # tas data is in C convert it to K if( df[['variable']] == 'tas' & nc_units == 'C'){ if(showMessages) message('converting from deg C to K') # Convert from C to K nc_data <- nc_data + 273.15 } # TODO make this not hard coded # Subset the data so that it matches the time step of the output # generated by L01B1. start <- 2006 end <- 2099 time <- as.integer(substr(nc_time, 1, 4)) keep <- which(start <= time & time <= end) final_data <- nc_data[keep] # Now that we have the final data with the correct units we need to name # the output file using the new names mapping file. df_mapping <- left_join(x = df, y = mapping, by = c("model", "experiment")) out_name <- paste0(df_mapping[['variable']], '_annual_', df_mapping[['new_model']], "_", df_mapping[['new_experiment']], '_xxx_', start, '-', end, '.ncGlobalAvg.txt') out_file <- file.path(output_dir, out_name) if(showMessages) message('saving ', out_file) write.table(final_data, file = out_file, row.names = FALSE, col.names = FALSE) if(removeIntermediate){ file.remove(interOut1_nc, interOut2_nc) } } # Use lapply to apply the annual_globalAvg_func to process all of the files in the to process data frame. lapply(X = split(to_process, to_process$path), FUN = annual_globalAvg_func, cdo_dir = CDO_DIR, inter_dir = INTER_DIR, output_dir = OUTPUT_DIR, mapping = mapping_names, showMessages = showMessages, removeIntermediate = TRUE) # Finish script if(showMessages) message('script complete')
cab9d981d771361f602857a1d10e3ba6908e185e
c4547314bb5e40b6386968ef995b1a4149c1de8c
/R/colorSpec.read.R
f8ad8dd268af678575681fb8eec590f1441a6d8e
[]
no_license
cran/colorSpec
a23ea51692949e43fce61e7ead9ba10b39668c58
7b6120a30cad781b413e6145a7d5b73c10991a64
refs/heads/master
2022-05-10T19:23:30.384707
2022-05-04T01:40:02
2022-05-04T01:40:02
58,973,975
2
1
null
null
null
null
UTF-8
R
false
false
30,611
r
colorSpec.read.R
# pathvec a vector of paths to files # ... optional arguments to pass to resample.colorSpec # # value: # a single colorSpec object, or NULL in case of error # readSpectra <- function( pathvec, ... ) { if( is.null(pathvec) || length(pathvec)==0 ) return(NULL) if( 1 < length(pathvec) ) { # call coroutine return( readAllSpectra( pathvec, ... ) ) } # only a single path now path = pathvec ftype = spectralFileType( path ) if( is.na(ftype) ) { log.string( ERROR, "Cannot determine type of file '%s'.", path ) return(NULL) } if( ftype == "Control" || ftype == "CGATS" ) { # These 2 types are special because they return a *list* of objects. if( ftype == "Control" ) out = readSpectraControl( path ) else out = readSpectraCGATS( path ) if( is.null(out) ) return(NULL) if( 0 < length( list(...) ) ) { # resample all of them for( k in 1:length(out) ) out[[k]] = resample( out[[k]], ... ) log.string( INFO, "Resampled %d spectra from file '%s' to new wavelengths.", length(out), path ) } if( length(out) == 1 ) { # only 1 object, so just return i return( out[[1]] ) } if( 0 ) { if( ! areSpectraBindable(out) ) { log.string( ERROR, "File '%s' has %d distinct spectra that cannot be combined. Try assigning a new wavelength sequence for resampling.", path, length(out) ) return(NULL) } } out.bound = bindSpectra( out ) return( out.bound ) } if( ftype == "scope" ) { # the simplest type out = readSpectrumScope( path ) } else if( ftype == "XYY" ) { # the simplest type out = readSpectraXYY( path ) } else if( ftype == "spreadsheet" ) { # this means tab-delimited text spreadsheet, e.g. the IT8 target files from Wolf-Faust out = readSpectraSpreadsheet( path ) } else if( ftype == "Excel" ) { # this means a real Excel spreadsheet out = NULL # readSpectraExcel( path ) } else { return(NULL) } if( is.null(out) ) return(NULL) # strip the extension off of .path, for nicer display # attr( out, "path" ) = sub( "[.][a-zA-Z]+$", "", .path ) #if( is.null(attr( out, "path" )) ) attr( out, "path" ) = .path #if( is.null(attr( out, "date" )) ) attr( out, "date" ) = file.info(.path)$mtime if( 0 < length( list(...) ) ) { out = resample( out, ... ) } return( out ) } # pathvec vector of paths, always 2 or more # ... optional arguments to pass to resample.colorSpec # # value: # a colorSpec with organization 'df.row', or NULL in case of ERROR readAllSpectra <- function( pathvec, ... ) { # read the 1st one out = readSpectra( pathvec[1], ... ) if( is.null(out) ) return(NULL) organization(out) = 'df.row' if( length(pathvec) == 1 ) return(out) # specnames = specnames(out) path = rep( pathvec[1], numSpectra(out) ) for( k in 2:length(pathvec) ) { obj = readSpectra( pathvec[k], ... ) if( is.null(obj) ) return(NULL) # organization(obj) = 'df.row' out = bind( out, obj ) if( is.null(out) ) return(NULL) # specnames = c( specnames, specnames(obj) ) path = c( path, rep( pathvec[k], numSpectra(obj) ) ) } extradata(out) = cbind( data.frame( path=path, stringsAsFactors=F ), extradata(out) ) return(out) } # readSpectraControl() # # unlike most of these functions, this one returns a *list* of colorSpecs # Each colorSpec in the list may have a different wavelength sequence ! readSpectraControl <- function( path) { line_vec = readLines( path) n = length(line_vec) if( n == 0 ) return( NULL ) # comments = line_vec[ grepl( "^[ \t]*#", line_vec ) ] # look for [Control] idx = which( grepl( "^\\[Control\\]", line_vec, ignore.case=TRUE ) ) if( length(idx) != 1 ) { log.string( ERROR, "Cannot find [Control] section in '%s'.", path) return( NULL ) } header = line_vec[ 1:(idx-1) ] # every line above [Control] # look for constant increment increment = 0 pattern = "^#[ \t]+increment[ \t=]+([0-9.]+).*$" inc = which( grepl( pattern, line_vec ) ) if( 0 < length(inc) ) { increment = sub( pattern, "\\1", line_vec[inc[1]] ) increment = as.numeric( increment ) # print( increment ) } x_px_vec = numeric(0) y_px_vec = numeric(0) wavelength_vec = numeric(0) response_vec = numeric(0) for( k in (idx+1):n ) { word = strsplit( line_vec[k], "[ \t]" )[[1]] #print(word) if( length(word) != 4 ) break vec = suppressWarnings( as.numeric(word) ) #print( vec ) if( all( ! is.na(vec) ) ) { x_px_vec = c( x_px_vec, vec[1] ) y_px_vec = c( y_px_vec, vec[2] ) wavelength_vec = c( wavelength_vec, vec[3] ) response_vec = c( response_vec, vec[4] ) } } #print( x_px_vec ) #print( y_px_vec ) #print( wavelength_vec ) #print( response_vec ) lm.x = lm( wavelength_vec ~ x_px_vec + y_px_vec ) lm.y = lm( response_vec ~ y_px_vec + x_px_vec ) # print( summary( lm.x ) ) # print( summary( lm.y ) ) out = list() # look for the data idx = grep( "^\\[[-._a-zA-Z0-9 ]+\\]", line_vec, value=F ) # print(idx) if( length(idx) <= 1 ) { log.string( ERROR, "Cannot find any [data] sections, only a [Control] section in '%s'.", path) return( NULL ) } # rgb_vec = c( "Red", "Green", "Blue" ) base = sub( "[.][a-zA-Z]+$", "", basename( path) ) # take away the extension for( i in idx ) { cname = gsub( "(\\[)|(\\])", "", line_vec[i] ) # print( cname ) if( cname == "Control" ) next # not a channel log.string( DEBUG, "Found [%s] channel on line %d.", cname, i ) x_px_vec = numeric(0) y_px_vec = numeric(0) for( k in (i+1):n ) { word = strsplit( line_vec[k], "[ \t]" )[[1]] #print(word) if( length(word) != 2 ) break vec = suppressWarnings( as.numeric(word) ) #print( vec ) if( all( ! is.na(vec) ) ) { x_px_vec = c( x_px_vec, vec[1] ) y_px_vec = c( y_px_vec, vec[2] ) } } if( length(x_px_vec) < 2 ) { log.string( WARN, "Found only %d points in [%s] channel", length(x_px_vec), cname ) } data_new = data.frame( x_px_vec=x_px_vec, y_px_vec=y_px_vec ) # ; print( data_new ) y = predict(lm.y,data_new) cextra = paste( base, cname, sep='.', collapse=NULL ) x_new = predict(lm.x,data_new) if( 0 < increment ) { # round to nearest multiple of increment x_new = increment * round( x_new / increment ) } # attr( y, "specname" ) = cname quant = guessSpectrumQuantity( cname, header ) if( is.na(quant) ) { quant = 'energy' log.string( WARN, "Cannot guess quantity from from contents of '%s', so assigning quantity='%s'.", basename(path), quant ) } spec = colorSpec( y, x_new, quantity=quant ) specnames( spec ) = cname metadata( spec ) = list( path=path, header=header ) out[[ cname ]] = spec } if( length(out) == 0 ) return(NULL) return( out ) } readSpectraXYY <- function( path ) { if( ! file.exists( path) ) { log.string( ERROR, "File '%s' does not exist !", path) return(NULL) } # peek to see whether tabs are used as separator header = readLines( path, 100 ) if( length(header) == 0 ) return(NULL) pattern = "^(wave|wv?l)" idx = which( grepl( pattern, header , ignore.case=T ) ) if( length(idx) == 0 ) { log.string( ERROR, "Cannot find Wavelength column in '%s' !\n", path) return(NULL) } # comments = header[ grepl( "^[ \t]*#", header ) ] # print( comments ) line = header[ idx[1] ] if( grepl( "\t", line) ) sep = '\t' else if( grepl( ",", line) ) sep = ',' else sep = '' df = read.table( path, header=T, sep=sep, skip=idx[1]-1, stringsAsFactors=F ) #; print( str(df) ) df[ is.na(df) ] = 0 # print( 2:ncol(df) ) data = as.matrix( df[ , 2:ncol(df) ] ) #; print( str(data) ) colnames(data) = colnames(df)[ 2:ncol(df) ] m = ncol(data) if( sep == '' ) sep = ' ' if( TRUE && m == 1 ) { base = sub( "[.][a-zA-Z]+$", "", basename( path) ) # take away the extension cname = colnames(data) colnames(data) = paste( base, cname, sep='.', collapse=NULL ) } header = header[ 1:(idx[1]-1) ] #; log.object( DEBUG, header ) # theType = guessSpectrumType( colnames(data), header ) #; print( theType ) theQuantity = guessSpectrumQuantity( colnames(data), header ) if( is.na(theQuantity) ) { theQuantity = 'energy' log.string( WARN, "Cannot guess quantity from from contents of '%s', so assigning quantity='%s'.", basename(path), theQuantity ) } out = colorSpec( data, df[[1]], quantity=theQuantity, organization='df.col' ) metadata( out ) = list( path=path) if( 0 < length(header) ) metadata( out, add=TRUE ) = list(header=header) return(out) } # Spreadsheet here means one of: # the Wolf Faust files: E131102.txt etc. readSpectraSpreadsheet <- function( path ) { if( ! file.exists( path) ) { log.string( ERROR, "File '%s' does not exist !", path) return(NULL) } # peek to find first line with data line = readLines( path, 60 ) if( length(line) == 0 ) return(NULL) idx_start = which( grepl( "^(ID|SAMPLE|Time)", line , ignore.case=F ) ) if( length(idx_start) == 0 ) { log.string( ERROR, "Cannot find header line in '%s' !\n", path) return(NULL) } skip = idx_start[1] - 1 header = line[ 1:skip ] #; print( header ) df = read.table( path, skip=skip, sep='\t', header=T, quote='', stringsAsFactors=F ) # print( str(df) ) pattern = "^[A-Z]+([0-9.]+)nm$" mask_nm = grepl( pattern, colnames(df) ) count = sum(mask_nm) log.string( INFO, "Found %d wavelengths in '%s'\n", count, path) if( count == 0 ) { return(NULL) } # print( colnames(df)[mask_nm] ) # convert wavelength from text to numeric wavelength = as.numeric( sub( pattern, "\\1", colnames(df)[mask_nm] ) ) # print( wavelength ) data = t( as.matrix( df[ , mask_nm ] ) ) # print( str(val) ) if( ! is.null( df$Name ) ) { # from Wolf Faust CD cnames = sub( "[ ]+$", '', df$Name ) # trim trailing space # cnames = paste( cnames, ".Transmittance", sep='' ) } else if( ! is.null( df$Sample ) ) { if( is.null( df$Sequence ) ) cnames = df$Sample else cnames = paste( df$Sample, df$Sequence, sep='.' ) # cnames = paste( cnames, ".Power", sep='' ) # ; print( cnames ) } colnames(data) = cnames # type = 'material' quantity = guessSpectrumQuantity( cnames, header ) if( is.na(quantity) ) { quantity = 'reflectance' log.string( WARN, "Cannot guess quantity from from contents of '%s', so assigning quantity='%s'.", basename(path), quantity ) } out = colorSpec( data, wavelength, quantity=quantity, organization="df.row" ) metadata( out ) = list( path=path, header=header ) part_left = df[ , ! mask_nm, drop=F ] if( 0 < ncol(part_left) ) extradata(out) = part_left for( w in c("date","originator","serial","white.point") ) attr( out, "metadata" )[[w]] = extractFieldFromHeader( header, w ) return( out ) } # .path to a CGATS file, e.g. .sp or .cal .cgt or .txt, or the Rosco files # # returns a *list* of colorSpec objects, each with organization 'df.row'. # WARNING: does not return a single object. readSpectraCGATS <- function( path ) { theData = readCGATS( path ) if( is.null(theData) ) return(NULL) n = length(theData) # n is the number of data.frames base = sub( "[.][a-zA-Z]+$", "", basename( path ) ) preamble = attr(theData,'preamble') # attr_name = c( "Substrate", "RefractiveIndex", "Thickness" ) # iterate in reverse order, so we can drop the tables with non-spectral data for( i in n:1 ) { obj = colorSpecFromDF( theData[[i]], path, preamble, i ) if( is.null(obj) ) # this is an error return(NULL) if( ! is.colorSpec(obj) ) { # table i does not have spectral data, so delete it theData = theData[-i] next } # overwrite previous data.frame with new colorSpec object theData[[i]] = obj } if( length(theData) == 0 ) { log.string( ERROR, "Found no tables with spectral data in '%s'.", path ) return(NULL) } attr( theData, 'path' ) = path return( theData ) } # df data.frame, from a table in a CGATS file # path the file # preamble from path. might be NULL # idxtable index of the table in path. 1-based # # returns a colorSpec object # in case of ERROR, returns NULL # if there is no spectral data, returns as.logical(NA) colorSpecFromDF <- function( df, path, preamble, idxtable ) { base = sub( "[.][a-zA-Z]+$", "", basename( path ) ) colspec = spectralColumns( df, path, idxtable ) #; print( colspec ) if( is.null(colspec) ) # this is an error return(NULL) if( ! is.list(colspec) ) { # table i does not have spectral data, so return any non-trivial thing return( as.logical(NA) ) } idx_val = colspec$idx_val idx_extra = colspec$idx_extra wavelength = colspec$wavelength # idx = which( mask ) mat = as.matrix.data.frame( df[ ,idx_val, drop=F] ) / colspec$divisor mat = t( mat ) #; print( dim(mat) ) rownames( mat ) = as.character( wavelength ) #; print( str(mat) ) # colnames(df)[mask] # print( mat ) # specnames = paste( base, as.character( 1:nrow(df)), sep='.' ) # just the defaults tableid = sprintf( "%s-%d", base, idxtable ) if( nrow(df) == 1 ) specnames = tableid else { #specnames = paste( tableid, as.character( 1:nrow(df)), sep='.' ) specnames = sprintf( "%s.%d", tableid, 1:nrow(df) ) } if( 0 < length(idx_extra) ) { candidate = c("SAMPLE_NAME","SAMPLE_ID","SampleID","Name") idx = which( candidate %in% colnames(df) ) if( 1 <= length(idx) ) specnames = df[[ candidate[idx[1]] ]] } # print(specnames) colnames(mat) = specnames header = attr( df, "header" ) # look for SPECTRAL_NORM, and if present divide by it pattern = '^SPECTRAL_NORM[ \t]*"?([.0-9]+)"?' vec = sub( pattern, "\\1", header, ignore.case=T ) idx = which( nchar(vec) < nchar(header) ) if( 0 < length(idx) ) { # found 1 or lines matching, only look at the first one value = as.numeric( vec[idx[1]] ) if( is.numeric(value) && is.finite(value) && 0 < value && value != 1 ) { log.string( INFO, "Dividing spectral values by SPECTRAL_NORM=%g.", value ) mat = mat / value } } theQuantity = guessSpectrumQuantity( specnames, c(preamble,header) ) if( is.na(theQuantity) ) { theQuantity = 'energy' log.string( WARN, "Cannot guess quantity from from contents of '%s', so assigning quantity='%s'.", basename(path), theQuantity ) } out = colorSpec( mat, wavelength, quantity=theQuantity, organization="df.row" ) # ColorMunki wavelengths in hires mode are equally spaced at 3.333 nm, but rounded to the nearest integer # check for this and fix it wavereg = regularizeWavelength(wavelength) discrep = max( abs(wavereg - wavelength) ) if( 0 < discrep && discrep < 0.5 ) { step.wl = wavereg[2] - wavereg[1] log.string( WARN, "Perturbed wavelengths in '%s' to have equal increments of %g nm [%g to %g nm]", path, step.wl, wavereg[1], wavereg[ length(wavereg) ] ) wavelength(out) = wavereg } if( 0 < length(idx_extra) ) { extra = df[ , idx_extra, drop=F ] # ;print( part_left ) extradata(out) = extra } metadata( out ) = list( header=header, date=attr(df,"date"), descriptor=attr(df,"descriptor") ) return( out ) } # df data.frame, from a table in a CGATS file # path to the file # idxtable index of the table in path # # returns a list with items # idx_val columns that correspond to a spectral values (but not to wavelength values) # idx_extra columns that correspond to extra data, maybe none # wavelength vector of wavelengths, the same length as idx_val # divisor for the values # in case of ERROR, returns NULL # if there is no spectral data, returns as.logical(NA) spectralColumns <- function( df, path, idxtable ) { #cat( "spectralColumns()\n" ) out = list() cname = colnames(df) #; print(cname) # search for standard convention for spectral data mask_dec = ("SPECTRAL_DEC" == cname) # grepl( "^SPECTRAL_DEC", cname ) mask_pct = ("SPECTRAL_PCT" == cname) # grepl( "^SPECTRAL_PCT", cname ) if( any( mask_dec | mask_pct ) ) { # the standard convention log.string( INFO, "In file '%s' and table %d, using standard convention for spectral data.", path, idxtable ) #cat( "Standard convention\n" ) idx_dec = which( mask_dec ) idx_pct = which( mask_pct ) # pattern = "^SPECTRAL_NM" mask_wl = ("SPECTRAL_NM" == cname) # grepl( pattern, cname ) idx_wl = which( mask_wl ) n = length(idx_wl) # number of wavelengths if( n == 0 ) { log.string( ERROR, "In file '%s' and table %d, there are %d spectral value fields, but there are no wavelengths.", path, idxtable, length(idx_dec)+length(idx_pct) ) return(NULL) } divisor = 0 if( length(idx_dec)==n && all( idx_dec == idx_wl+1 ) ) divisor = 1 # got a match else if( length(idx_pct)==n && all( idx_pct == idx_wl+1 ) ) divisor = 100 # got a match if( divisor == 0 ) { log.string( ERROR, "In file '%s' and table %d, there are %d wavelength columns, but spectral value columns do not match up.", path, idxtable, n ) return(NULL) } wavelength = lapply( df[ , idx_wl ], unique ) #; print(wavelength) waveunique = sapply( wavelength, length ) #; print(wavelength) idx_max = which.max( waveunique ) if( 1 < waveunique[ idx_max ] ) { # not unique log.object( ERROR, wavelength[[idx_max]] ) log.string( ERROR, "In file '%s', wavelength columns in table %d exist, but they are not unique.", path, idxtable ) return(NULL) } out$idx_val = idx_wl + 1 out$idx_extra = which( ! (mask_wl | mask_dec | mask_pct) ) out$wavelength = unlist( wavelength, use.names=FALSE ) #; print( out$wavelength ) out$divisor = divisor # print( out ) } else { # try again with non-standard pattern pattern = "^(nm|SPEC_|SPECTRAL_)[A-Z_]*([0-9.]+)$" mask_val = grepl( pattern, cname ) # ; print( idx ) idx_val = which( mask_val ) # ; print(idx_wl) n = length(idx_val) # number of wavelengths if( n == 0 ) # no spectral data found return( as.logical(NA) ) log.string( INFO, "In file '%s' and table %d, using non-standard convention for spectral data.", path, idxtable ) contig = all( diff(idx_val) == 1 ) if( ! contig ) { log.string( ERROR, "In file '%s' and table %d, there are %d spectral columns, but they are not contiguous.", path, idxtable, n ) # log.object( WARN, idx_val ) return(NULL) } wavelength = sub( pattern, "\\2", cname[idx_val] ) #; print( wavelength ) out$wavelength = type.convert( wavelength, as.is=TRUE ) #; print( wavelength ) out$idx_val = idx_val out$idx_extra = which( ! mask_val ) out$divisor = 1 } # verify that wavelength is valid ok = is.numeric(out$wavelength) && all( is.finite(out$wavelength) ) if( ! ok ) { log.string( ERROR, "In file '%s' and table %d, the %d wavelength values are not all numeric and finite.", path, idxtable, length(wavelength) ) return(NULL) } # verify that spectral values are valid ok = all( sapply( df[out$idx_val], function(y) { is.numeric(y) && all( is.finite(y) ) } ) ) if( ! ok ) { log.string( ERROR, "In file '%s' and table %d, the %dx%d spectral values are not all numeric and finite.", path, idxtable, nrow(df), length(idx_val) ) return(NULL) } return(out) } # read Ocean Optics format # we already know this is a light source of with quantity 'energy' # # TODO: extract integration time from header and organize as df.row readSpectrumScope <- function( path) { linevec = readLines( path) ok = (0 < length(linevec)) ; # assert( ok ) if( ! ok ) { return(NULL) } header = NULL idx = which( grepl( "^>+Begin", linevec[1:30] ) ) if( length(idx) == 1 ) header = linevec[ 1:(idx-1) ] # make a list of character vectors, tab-delimited line_split = strsplit( linevec, '\t', fixed=T ) # form subset of those lines that have data - 2 tab-delimted words theData = base::subset( line_split, sapply(line_split,length) == 2 ) # unlist() is faster than sapply() theData = as.double( unlist(theData) ) ; dim(theData) = c(2,length(theData)/2) y = theData[ 2, ] out = colorSpec( y, wavelength=theData[1, ], quantity="energy", organization="vector" ) # there is only 1 spectrum here, so use the path as the name specnames(out) = stripExtension( basename(path) ) metadata( out ) = list( path=path, header=header ) return( out ) } # plain text means: # the usual characters # TAB through CR # © and µ isPlainText <- function( .stringvec ) { n = length(.stringvec) out = logical(n) for( i in 1:n ) { byte = charToRaw( .stringvec[i] ) # utf8ToInt( .stringvec[i] ) out[i] = all( (32 <= byte & byte <= 126) | (9 <= byte & byte <= 13) | byte==169 | byte==181 ) } return( out ) } is.UTF8 <- function( .stringvec ) { n = length(.stringvec) out = logical(n) for( i in 1:n ) { ivec = try( utf8ToInt( .stringvec[i] ), silent=TRUE ) out[i] = ! inherits(ivec,"try-error") #class(ivec) != "try-error" } return( out ) } # does not look at file extension, except for .XLS(X) spectralFileType <- function( .path ) { out = as.character(NA) if( is.null(.path) ) { log.string( ERROR, "File argument is NULL !" ) return(out) } if( ! file.exists( .path) ) { log.string( ERROR, "File '%s' does not exist !", .path) return(out) } # read a few lines at the beginning of file line = readLines( .path, 32, warn=F ) # ignore comment lines line = line[ ! grepl( "^#", line ) ] if( length(line) == 0 ) return(out) # crude check for a text file if( ! all( is.UTF8(line) ) ) { # a binary file if( FALSE && grepl( "[.]xlsx?$", basename(.path), ignore.case=T ) ) return( "Excel" ) else { log.string( WARN, "File type of '%s' unnknown. It appears to be binary. !", .path ) return(out) } } pattern = c( "^CGATS|^ISO28178|^NUMBER_OF_FIELDS|^KEYWORD" , "^\\[Control\\]", "^(wave|wv?l)", "^>+Begin", "^ID\tName", "^Time" ) type = c( "CGATS", "Control", "XYY", "scope", "spreadsheet", "spreadsheet" ) for( i in 1:length(pattern) ) { # print( type ) # print( pattern[type] ) if( any( grepl( pattern[i] , line , ignore.case=T ) ) ) return( type[i] ) } return( out ) } stripExtension <- function( .path ) { pattern = "[.][a-z0-9]+$" return( sub(pattern,'',.path,ignore.case=T) ) } ################## semi-deadwood below ############################### if( 0 ) { # Spreadsheet here means a real Excel spreadsheet, e.g. ASTMG173.xls, sheet SMARTS2 # # path full path to file # worksheet name of the worksheet. If NULL then search for the 1st one with data. # readSpectraExcel <- function( path, worksheet=NULL ) { for( p in c('rJava','xlsxjars','xlsx') ) { ok = requireNamespace( p, quietly=TRUE ) if( ! ok ) { log.string( ERROR, "Package '%s' is required. Please install it.", p ) return(NULL) } } if( ! file.exists( path) ) { log.string( ERROR, "File '%s' does not exist !\n", path) return(NULL) } wb = xlsx::loadWorkbook( path) sheetlist = xlsx::getSheets(wb) # print( str(sheetlist) ) idx_sheet = 0 if( is.null(worksheet) ) { # search for the first worksheet that has rows for( i in 1:length(sheetlist) ) { # print( str(getRows( sheetlist[[i]] ) ) ) rowcount = length( xlsx::getRows( sheetlist[[i]] ) ) if( 0 < rowcount ) { log.string( INFO, "Found sheet '%s' rows=%d.", names(sheetlist)[i], rowcount ) idx_sheet = i break } } if( idx_sheet == 0 ) { log.string( ERROR, "Cannot find a suitable worksheet, with rows, in '%s'.", path) return(NULL) } } else { # search for 1st worksheet with matching name idx_sheet = which( worksheet == names(sheetlist) ) if( length(idx_sheet) != 1 ) { log.string( ERROR, "Cannot find worksheet '%s' in '%s'.", worksheet, path ) return(NULL) } } theSheet = sheetlist[[ idx_sheet ]] # look for Lambda in 1st column col1 = xlsx::readColumns(theSheet, 1, 1, 1, 16, header=F, as.data.frame=F )[[1]] # print( str(col1) ) iname = sub( "^([A-Za-z0-9]+).*$", "\\1", col1[1] ) pattern = "^lambda|nm$" idx = which( grepl( pattern, col1, ignore.case=T ) ) # print( idx ) if( length(idx) != 1 ) { log.string( ERROR, "Cannot find '%s' in worksheet %d in '%s'.", pattern, idx_sheet, path) return(NULL) } row1 = xlsx::readRows( theSheet, 1, 1, 1 ) # print( row1 ) spectra = length(row1)-1 mat = xlsx::readColumns( theSheet, 1, spectra+1, idx+1, header=F, colClasses='numeric' ) #; print( str(mat) ) wave = as.numeric( mat[ ,1] ) mat = as.matrix( mat[ ,2:ncol(mat)] ) colnames(mat) = sprintf( "%s%02d.Energy", iname, 1:spectra ) out = colorSpec( mat, wave, quantity='energy' ) metadata(out) = list( path=path) return( out ) } }
c724f33d11b30ba23402f16640c97b836291c861
92c22064740e2ebfc09bcbcad308b0420dbda343
/man/estat_index.Rd
ed355fe654ca60c334f10707cf5b8537120bdd1a
[]
no_license
Tungurahua/reurostat
9643b6486ed324d3091da660130e78c0ed365bf1
982944f0e19659c0a6685ed974aec045ebcfe715
refs/heads/master
2020-05-17T18:00:22.922657
2014-07-17T21:56:10
2014-07-17T21:56:10
null
0
0
null
null
null
null
UTF-8
R
false
false
665
rd
estat_index.Rd
% Generated by roxygen2 (4.0.1): do not edit by hand \name{estat_index} \alias{estat_index} \title{Loads the index of available datasets from Eurostat.} \usage{ estat_index(lang = c("en", "de", "fr"), url = "http://ec.europa.eu/eurostat/SDMX/diss-web/rest/dataflow/ESTAT/all/latest") } \arguments{ \item{lang}{language used to display name of dataflow. \code{en} for english (default), \code{de} for german or \code{fr} for french.} \item{url}{address of the dataflow list (REST)} } \value{ dataframe with two variables ID and name } \description{ This function downloads the current index of available datasets from Eurostat using the websites REST service. }
a8c59ba802d4323666d92ff984decc8d10f3be45
24c6064c55846266c96dc3ddbbd944e156c90e03
/man/betafunction.Rd
ffe57559e96c576510f18fa803029845493ee3e1
[]
no_license
liujin07/StartComp18065
78f04ffec16b20b3a99f9bff138d93cd999246e5
6d5cd6eea6b9c8298396676962a1d16130e954b0
refs/heads/master
2020-04-16T03:19:34.634420
2019-01-11T14:42:50
2019-01-11T14:42:50
164,424,037
0
0
null
null
null
null
UTF-8
R
false
true
690
rd
betafunction.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/acc_reBeta.R \name{betafunction} \alias{betafunction} \title{The function that generates random Numbers with the accept-rejection method} \usage{ betafunction(n, a, b) } \arguments{ \item{n}{The number of random Numbers generated} \item{a}{Parameter of beta distribution} \item{b}{Parameter of beta distribution} } \value{ a random sample of size \code{n} } \description{ a function to generate a random sample of size n from the Beta(a,b) distribution by the acceptance-rejection method. } \examples{ \dontrun{ sample_beta <- betafunction(1e3,3,2)#record the sample head(sample_beta,20) hist(sample_beta) } }
b91e4f42cd4a5d90eb6901b0c5a204a498f50977
fd76bfc240e097bf6040819061fe9c36d79a36de
/R/cross_validation.R
0f7b4726c909313c1bd9a25254b808529ad778e1
[]
no_license
lierscn789/interflex
b2409521f325e3b2bf83a3c1d2d353e46dcc9951
9abec7d1acae7c3f0cd904996726442bcef6b6ad
refs/heads/master
2022-12-23T12:20:43.573283
2020-09-28T04:56:25
2020-09-28T04:56:25
null
0
0
null
null
null
null
UTF-8
R
false
false
8,569
r
cross_validation.R
crossvalidate.new <- function(data, Y, D, X, CV.method='simple', FE=NULL, treat.type, Z = NULL, weights = NULL, cl = NULL, base=NULL, X.eval, grid, kfold = 10, parallel = TRUE, seed=NULL, bw.adaptive = FALSE, metric = "MSPE"){ bw <- NULL if(is.null(seed)==FALSE){ set.seed(seed) } requireNamespace('lfe') cat("Cross-validating bandwidth ... \n") if(TRUE){ ## Sample ## generate K random folds ## if CV.method=="cluster" then fold by cluster ## if CV.method=="stratify" then conduct stratified cross-validation ## if CV.method=="simple" then randomly sample n<-dim(data)[1] fold<-rep(0,n) if(CV.method=='simple'){ kfold <- min(n,kfold) cat("#folds =",kfold) cat("\n") fold <- c(0:(n-1))%%kfold + 1 fold<-sample(fold, n, replace = FALSE) } if(CV.method=='cluster' & is.null(cl)==TRUE){ stop("\"cl\" is not specified when using cluster cross-validation.") } if(CV.method=='cluster' & is.null(cl)==FALSE){ clusters<-unique(data[,cl]) m <- length(clusters) kfold <- min(m,kfold) cat("Use clustered cross-validation.\n") cat("#folds =",kfold) cat("\n") id.list<-split(1:n,data[,cl]) cl.fold <- c(0:(m-1))%%kfold + 1 cl.fold <- sample(cl.fold, m, replace = FALSE) for (i in 1:m) { id.list[[i]] <- rep(cl.fold[i],length(id.list[[i]])) } fold <- unlist(id.list) } if(CV.method=='stratify'){ requireNamespace("caret") fold <- createFolds(factor(data[,D]), k = kfold, list = FALSE) cat("Use stratified cross-validation.\n") cat("#folds =",kfold) cat("\n") } } if(TRUE){ ## TREAT.TYPE if(treat.type=='discrete') { all.treat <- unique(data[,D]) if(is.null(base)==TRUE){ base <- all.treat[1] } other.treat <- all.treat[which(all.treat!=base)] } } ##FUNCTION: calculate errors in testing set getError.new <- function(train, test, bw, Y, X, D, Z, FE, weights, X.eval, treat.type){ if(is.null(weights)==T){ w <- rep(1,dim(train)[1]) w2 <- rep(1,dim(test)[1]) } else{ w <- train[,weights] w2 <- test[,weights] } # FIXED EFFECTS ## demean outcome(y) and estimate fixed effects ## save fixed effects in add_FE ## add fixed effects to predicted values add_FE <- rep(0,dim(test)[1]) if(is.null(FE)==FALSE){ train_y <- as.matrix(train[,Y]) train_FE <- as.matrix(train[,FE]) invisible( capture.output( fastplm_res <- fastplm(data = train_y,FE = train_FE,weight = w, FEcoefs = 1L),type='message' ) ) FEvalues <- fastplm_res$FEvalues FEnumbers <- dim(fastplm_res$FEvalues)[1] FE_coef <- matrix(FEvalues[,3],nrow = FEnumbers, ncol = 1) rowname <- c() for(i in 1:FEnumbers){ rowname <- c(rowname,paste0(FE[FEvalues[i,1]+1],'.',FEvalues[i,2])) } rownames(FE_coef) <- rowname train[,Y] <- fastplm_res$residuals #addictive FE add_FE <- matrix(0,nrow = dim(test)[1],ncol = length(FE)) colnames(add_FE) <- FE for(fe in FE){ add_FE[,fe] <- 0 fe_name <- paste0(fe,".",test[,fe]) add_FE[which(fe_name %in% rownames(FE_coef)),fe] <- FE_coef[fe_name[(which(fe_name %in% rownames(FE_coef)))],] } add_FE <- rowSums(add_FE) add_FE <- add_FE + fastplm_res$mu #intercept } if(treat.type=='discrete'){ #generate dummy variable test_d <- test[,c(Y,X)] for (char in other.treat) { test_d[,paste0("D.",char)] <- as.numeric(test[,D]==char) } #get coef coef<-coefs.new(data=train,bw=bw,Y=Y,X=X,D=D,Z=Z,base=base,treat.type = 'discrete', weights = weights, X.eval= X.eval,bw.adaptive = bw.adaptive) coef[is.na(coef)] <- 0 num.Z<-length(Z) num.treat <- length(other.treat) esCoef<-function(x){ ##obtain the coefficients for x[i] Xnew<-abs(X.eval-x) d1<-min(Xnew) ## distance between x[i] and the first nearest x in training set label1<-which.min(Xnew) Xnew[label1]<-Inf d2<-min(Xnew) ## distance between x[i] and the second nearest x in training set label2<-which.min(Xnew) if(d1==0){ if(is.null(Z)==T){ func <- coef[label1,c(2:(2+num.treat))] # X.eval (1), intercept (2), d (3), xx (4), d:xx (5), z } else{ func <- coef[label1,c(c(2:(2+num.treat)),c((4+2*num.treat):(3+2*num.treat+num.Z)))] # X.eval (1), intercept (2), d (3), xx (4), d:xx (5), z } } else if(d2==0){ if(is.null(Z)==T){ func <- coef[label2,c(2:(2+num.treat))] } else{ func <- coef[label2,c(c(2:(2+num.treat)),c((4+2*num.treat):(3+2*num.treat+num.Z)))] } } else{ ## weighted average if(is.null(Z)==T){ func1 <- coef[label1,c(2:(2+num.treat))] func2 <- coef[label2,c(2:(2+num.treat))] } else{ func1 <- coef[label1,c(c(2:(2+num.treat)),c((4+2*num.treat):(3+2*num.treat+num.Z)))] func2 <- coef[label2,c(c(2:(2+num.treat)),c((4+2*num.treat):(3+2*num.treat+num.Z)))] } func <- (func1 * d2 + func2 * d1)/(d1 + d2) } return(func) } Knn<-t(sapply(test[,X],esCoef)) ## coefficients for test class==matrix ## predicting test.Y <- test[,Y] test.X <- as.data.frame(rep(1,dim(test)[1])) for (char in other.treat) { test.X[,paste0("D.",char)] <- test_d[,paste0("D.",char)] } test.X <- cbind(test.X,as.data.frame(test[,Z])) test.X <- as.matrix(test.X) sumOfEst<-matrix(lapply(1:length(test.X), function(i){test.X[i]*Knn[[i]]}), nrow=nrow(test.X), ncol=ncol(test.X)) error <- test.Y - rowSums(matrix(unlist(sumOfEst),length(test.Y))) - add_FE ## weights error <- error*w2/mean(w2) return(c(mean(abs(error)),mean(error^2))) } if(treat.type=='continuous'){ coef<-coefs.new(data=train,bw=bw,Y=Y,X=X,D=D,Z=Z,treat.type = 'continuous',bw.adaptive = bw.adaptive, weights = weights, X.eval= X.eval) coef[is.na(coef)] <- 0 n2<-length(Z) esCoef<-function(x){ ##obtain the coefficients for x[i] Xnew<-abs(X.eval-x) d1<-min(Xnew) ## distance between x[i] and the first nearest x in training set label1<-which.min(Xnew) Xnew[label1]<-Inf d2<-min(Xnew) ## distance between x[i] and the second nearest x in training set label2<-which.min(Xnew) if(d1==0){ func <- coef[label1,-c(1,4,5)] # X.eval (1), intercept (2), d (3), xx (4), d:xx (5), z } else if(d2==0){ func <- coef[label2,-c(1,4,5)] } else{ ## weighted average func <- (coef[label1,-c(1,4,5)] * d2 + coef[label2,-c(1,4,5)] * d1)/(d1 + d2) } return(func) } Knn<-t(sapply(test[,X],esCoef)) ## coefficients for test class==matrix ## predicting test.Y <- test[,Y] test.X <- as.matrix(cbind(rep(1,dim(test)[1]),test[,c(D,Z)])) sumOfEst<-matrix(lapply(1:length(test.X), function(i){test.X[i]*Knn[[i]]}), nrow=nrow(test.X), ncol=ncol(test.X)) error<-test.Y - rowSums(matrix(unlist(sumOfEst),length(test.Y)))-add_FE ## weights error <- error*w2/mean(w2) return(c(mean(abs(error)),mean(error^2))) } } ##FUNCTION: calculate MSE ## grid search and k fold cross-validation cv.new<-function(bw){ mse<-matrix(NA,kfold,2) for(j in 1:kfold){ # K-fold CV testid <- which(fold==j) train <- data[-testid,] test <- data[testid,] mse[j,] <- getError.new(train= train, test = test, treat.type = treat.type,FE=FE, bw = bw, Y=Y, X=X, D=D, Z=Z, weights = weights, X.eval= X.eval) } return(c(bw, apply(mse,2,mean))) } ## Parallel Computing or Not if (parallel == TRUE) { Error<-suppressWarnings(foreach(bw = grid, .combine = rbind, .export = c("coefs.new","getError.new"), .inorder = FALSE) %dopar% {cv.new(bw)}) } else { Error <- matrix(NA, length(grid), 3) for (i in 1:length(grid)) { Error[i, ] <- cv.new(grid[i]) cat(".") } } colnames(Error) <- c("bandwidth","MAPE","MSPE") rownames(Error) <- NULL if (metric=="MAPE") { opt.bw <- grid[which.min(Error[,2])] } else { opt.bw <- grid[which.min(Error[,3])] } output <- list(CV.out = round(Error,3), opt.bw = opt.bw) cat(paste("Bandwidth =", round(output$opt.bw,3),"\n")) return(output) }
e31e81ca02a167ce0a9d6b38883e2cd3b319400c
856fc05ab99ef6c205d61be0468cac347184269a
/RSWMM_Autocalibration_Nasrin Alamdari.R
5acae0fcd853c9f7692bc93606a1473da747cfcc
[]
no_license
nasrinalam/RSWMM-CostAutomation
3101f5e17eeaf4ec7dafb04d49d503eaca7851dd
6a3f6b92919ce2d456002ce10b155ccda9fc7000
refs/heads/master
2020-03-18T19:57:41.793200
2018-05-28T17:00:01
2018-05-28T17:00:01
135,187,942
1
0
null
null
null
null
UTF-8
R
false
false
30,235
r
RSWMM_Autocalibration_Nasrin Alamdari.R
SWMMExe <-function(swmm,Input,Report,Output,iType,vIndex){ swmm=paste('"',swmm,'"',sep="") Input=paste('"', Input,'"',sep="") Report=paste('"', Report,'"',sep="") Output=paste('"', Output,'"',sep="") # Running executable file system(paste(swmm,Input,Report,Output,sep=" "),show.output.on.console=T) return(Output) } GetObjectsSWMM<-function(Output){ BinaryFile = file(Output,"rb") Status ={} seek(BinaryFile,1*4,"start") #the version number of the engine (currently 51000) Status$VersionNum = readBin(BinaryFile, integer(), n = 1, size = 4) #a code number for the flow units that are in effect where #0 = CFS #1 = GPM #2 = MGD #3 = CMS #4 = LPS #5 = LPD Status$UnitCode = readBin(BinaryFile, integer(), n = 1, size = 4) #the number of subcatchments in the project reported on Status$SubCatchNum = readBin(BinaryFile, integer(), n = 1, size = 4) #the number of nodes in the project reported on Status$NodesNum = readBin(BinaryFile, integer(), n = 1, size = 4) #the number of links in the project reported on Status$LinksNum = readBin(BinaryFile, integer(), n = 1, size = 4) #the number of pollutants in the project Status$PollutantsNum = readBin(BinaryFile, integer(), n = 1, size = 4) seek(BinaryFile,-2*4,"end") #Check the error status (0 or 1) Status$Err= readBin(BinaryFile, integer(), n = 1, size = 4) if (Status$Err == 0){ print ("There is no error in the file") }else{ print("find the error in the file") } seek(BinaryFile,-6*4,"end") Status$ObjectID = readBin(BinaryFile, integer(), n = 1, size = 4) #Getting Object ID seek(BinaryFile,Status$ObjectID,"start") #subcatchment ID names Status$SubCatchName = {} if (Status$SubCatchNum>0){ for (i in 1:Status$SubCatchNum){ Status$SubCatchName[i]= readChar(BinaryFile,readBin(BinaryFile, integer(), n = 1, size = 4),useBytes = FALSE) } } else { print ("No Subcatchment") } #node ID names Status$NodesName = {} if (Status$NodesNum>0){ for (i in 1:Status$NodesNum){ Status$NodesName[i]= readChar(BinaryFile,readBin(BinaryFile, integer(), n = 1, size = 4),useBytes = FALSE) } } else { print ("No Node") } #link ID names Status$LinksName = {} if (Status$LinksNum>0){ for (i in 1:Status$LinksNum){ Status$LinksName[i]= readChar(BinaryFile,readBin(BinaryFile, integer(), n = 1, size = 4),useBytes = FALSE) } } else { print ("No Link") } #Pollutant names Status$PollutantsName = {} if (Status$PollutantsNum>0){ for (i in 1:Status$PollutantsNum){ Status$PollutantsName[i]= readChar(BinaryFile,readBin(BinaryFile, integer(), n = 1, size = 4),useBytes = FALSE) } } else { print ("No Pollutant") } #pollutant concentration units codes #0 for mg/L #1 for ug/L #2 for counts/L. Status$PollutantsUnitCode = {} for (i in 1:Status$PollutantsNum){ Status$PollutantsUnitCode[i]= readBin(BinaryFile, integer(), n = 1, size = 4) } #Getting Object Properties seek(BinaryFile,-5*4,"end") Status$ObjectProperties = readBin(BinaryFile, integer(), n = 1, size = 4) seek(BinaryFile,Status$ObjectProperties,"start") #Number of subcatchment properties saved (Currently equal to 1) Status$NumofSubCatchSaved = readBin(BinaryFile, integer(), n = 1, size = 4) #Code number of each subcatchment property saved (Currently equal to 1 for subcatchment area) Status$CodeNumSubCatchSaved = readBin(BinaryFile, integer(), n = 1, size = 4) #Value of each property for each subcatchment (Subcatchment area (ac or ha) for each subcatchment) Status$SubCatchArea=readBin(BinaryFile,what="double",n=Status$SubCatchNum,size=4); #Number of node properties saved (Currently equal to 3) Status$NumofNodesSaved = readBin(BinaryFile, integer(), n = 1, size = 4) #Code number of each node property saved #0 (node type code) #2 (node invert elevation) #3 (node max. depth) Status$CodeNumNodesSaved = readBin(BinaryFile, integer(), n = Status$NumofNodesSaved, size = 4) Status$TypeofNodes = {} if(Status$NodesNum>0){ NodeType=readBin(BinaryFile,what="double",n=Status$NumofNodesSaved*Status$NodesNum,size=4) Status$CodeNumNodesSaved=NodeType[seq(from=1,by=3,to=length(NodeType))] #0 = Junction #1 = Outfall #2 = Storage #3 = Divider for (i in 1 :length(Status$CodeNumNodesSaved)){ if (Status$CodeNumNodesSaved[i]==0){ Status$TypeofNodes[i]="Junction"} else if (Status$CodeNumNodesSaved[i]==1){ Status$TypeofNodes[i]="Outfall"} else if (Status$CodeNumNodesSaved[i]==2){ Status$TypeofNodes[i]="Storage"} else if (Status$CodeNumNodesSaved[i]==3){ Status$TypeofNodes[i]="Divider"} } Status$InvertElevation=NodeType[seq(from=2,by=3,to=length(NodeType))] Status$MaximumDepth=NodeType[seq(from=3,by=3,to=length(NodeType))] } #Number of node properties saved (Currently equal to 5) Status$NumofLinksSaved = readBin(BinaryFile, integer(), n = 1, size = 4) #Code number of each link property saved #0 (link type code) #4 (upstream invert offset) #4 (downstream invert offset) #3 (link max. depth) #5 (link length) Status$CodeNumLinkSaved = readBin(BinaryFile, integer(), n = Status$NumofLinksSaved, size = 4) Status$TypeofLinks = {} if(Status$LinksNum>0){ LinkType=readBin(BinaryFile,what="double",n=Status$NumofLinksSaved*Status$LinksNum,size=4) Status$CodeNumLinksSaved=LinkType[seq(from=1,by=5,to=length(LinkType))] #0 = Conduit #1 = Pump #2 = Orifice #3 = Weir #4 = Outlet for (i in 1 :length(Status$CodeNumLinksSaved)){ if (Status$CodeNumLinksSaved[i]==0){ Status$TypeofLinks[i]="Conduit"} else if (Status$CodeNumLinksSaved[i]==1){ Status$TypeofLinks[i]="Pump"} else if (Status$CodeNumLinksSaved[i]==2){ Status$TypeofLinks[i]="Orifice"} else if (Status$CodeNumLinksSaved[i]==3){ Status$TypeofLinks[i]="Weir"} else if (Status$CodeNumLinksSaved[i]==4){ Status$TypeofLinks[i]="Outlet"} #4 (upstream invert offset) Status$UpstreamInvertOffset=LinkType[seq(from=2,by=5,to=length(LinkType))] #4 (downstream invert offset) Status$DownstreamInvertOffset=LinkType[seq(from=3,by=5,to=length(LinkType))] #3 (link max. depth) Status$MaximumDepth=LinkType[seq(from=4,by=5,to=length(LinkType))] #5 (link length) Status$LinkLength=LinkType[seq(from=5,by=5,to=length(LinkType))] } } #Getting Reporting Variables #Number of subcatchment variables (currently 8 + number of pollutants). Status$NumofSubCatchVariables = readBin(BinaryFile, integer(), n = 1, size = 4) #Code number of each subcatchment variable #0 for rainfall (in/hr or mm/hr), #1 for snow depth (in or mm), #2 for evaporation loss (in/day or mm/day), #3 for infiltration losses (in/hr or mm/hr), #4 for runoff rate (flow units), #5 for groundwater outflow rate (flow units), #6 for groundwater water table elevation (ft or m), #7 for unsaturated zone moisture content (fraction) #8 for runoff concentration of first pollutant, #... #7 + N for runoff concentration of N-th pollutant. Status$CodeNumSubCatch = readBin(BinaryFile, integer(), n = Status$NumofSubCatchVariables, size = 4) #Number of node variables (currently 6 + number of pollutants) Status$NumNodesVariables = readBin(BinaryFile, integer(), n = 1, size = 4) #Code number of each node variable #0 for depth of water above invert (ft or m), #1 for hydraulic head (ft or m), #2 for volume of stored + ponded water (ft3 or m3), #3 for lateral inflow (flow units), #4 for total inflow (lateral + upstream) (flow units), #5 for flow lost to flooding (flow units), #6 for concentration of first pollutant, #... #5 + N for concentration of N-th pollutant. Status$CodeNumNode = readBin(BinaryFile, integer(), n = Status$NumNodesVariables, size = 4) #Number of link variables (currently 5 + number of pollutants) Status$NumLinksVariables = readBin(BinaryFile, integer(), n = 1, size = 4) #Code number of each link variable: #0 for flow rate (flow units), #1 for flow depth (ft or m), #2 for flow velocity (ft/s or m/s), #3 for flow volume (ft3 or m3) #4 for fraction of conduit's area filled or setting for non-conduits #5 for concentration of first pollutant, #... #4 + N for concentration of N-th pollutant. Status$CodeNumLink = readBin(BinaryFile, integer(), n = Status$NumLinksVariables, size = 4) #Number of system-wide variables (currently 14) Status$NumSystemVariables = readBin(BinaryFile, integer(), n = 1, size = 4) #Code number of each system-wide variable: #0 for air temperature (deg. F or deg. C), #1 for rainfall (in/hr or mm/hr), #2 for snow depth (in or mm), #3 for evaporation + infiltration loss rate (in/hr or mm/hr), #4 for runoff flow (flow units), #5 for dry weather inflow (flow units), #6 for groundwater inflow (flow units), #7 for RDII inflow (flow units), #8 for user supplied direct inflow (flow units), #9 for total lateral inflow (sum of variables 4 to 8) (flow units), #10 for flow lost to flooding (flow units), #11 for flow leaving through outfalls (flow units), #12 for volume of stored water (ft3 or m3), #13 for evaporation rate (in/day or mm/day) Status$CodeNumSystems = readBin(BinaryFile, integer(), n = Status$NumSystemVariables, size = 4) #Getting Reporting Interval Status$BytesPerPeriod= 2*4 +(Status$SubCatchNum*(Status$NumofSubCatchVariables) + Status$NodesNum*(Status$NumNodesVariables) + Status$LinksNum*(Status$NumLinksVariables) + Status$NumSystemVariables)*4; seek(BinaryFile,-3*4,"end") Status$ReportingPeriods= readBin(BinaryFile, integer(), n = 1, size = 4) Status$BinaryFile = BinaryFile seek(BinaryFile,-4*4,"end") Status$ComputedResults= readBin(BinaryFile, integer(), n = 1, size = 4) #Writing function to get table of computed results #ObjectType is the type of the Object that you want to see the result (i.e., Subcatchment, node, conduit, or system) #Object ID is the name of object to see the result (i.e., S1 or J2) #Index is the position of one object among other objects #Codenum is the code number of each variable from abover list #Time period return(Status) } getSWMMResult<-function(headObj,iType,iIndex,vIndex,period){ SUBCATCH=0 NODE = 1; LINK = 2; SYS = 3; f=headObj$BinaryFile StartPos=headObj$ComputedResults off = StartPos + period*(headObj$BytesPerPeriod) + 2*4; if ( iType == SUBCATCH ) { off = off+ 4*(iIndex*(headObj$NumofSubCatchVariables) + vIndex); } else if (iType == NODE) { off = off+ 4*(headObj$SubCatchNum*(headObj$NumofSubCatchVariables) + iIndex*(headObj$NumNodesVariables) + vIndex); } else if (iType == LINK) { off = off+ 4*(headObj$SubCatchNum*(headObj$NumofSubCatchVariables) + headObj$NodesNum*(headObj$NumNodesVariables) + iIndex*(headObj$NumLinksVariables) + vIndex); } else if (iType == SYS) { off = off+ 4*(headObj$SubCatchNum*(headObj$NumofSubCatchVariables) + headObj$NodesNum*(headObj$NumNodesVariables) + headObj$LinksNum*(headObj$NumLinksVariables) + vIndex); } seek(f,off,"start") Status=readBin(f,what="double",size=4,n=1) return(Status) } getSWMMTimes<-function(headObj){ #gets the time stamps of the SWMM results in binary file f=headObj$BinaryFile seek(f,headObj$ComputedResults,"start") headObj$SWMMTimes<-array(NaN,headObj$ReportingPeriods) if(headObj$ReportingPeriods>0){ for(i in 1:headObj$ReportingPeriods){ headObj$SWMMTimes[i]<-readBin(f,what="double",size=8,n=1) # if(i<100){ # print(headObj$SWMMTimes[i]) # } seek(f,headObj$BytesPerPeriod-8,"current") } }else{ stop("No time steps listed in SWMM output file.") } #Convert SWMM times to R POSIXlt datetimes headObj$SWMMTimes<-headObj$SWMMTimes*86400.0+as.POSIXct(strptime("12/30/1899", format="%m/%d/%Y",tz="GMT"))#edit 2/10/2012 to force GMT time zone rather than locale specific return(headObj) } getSWMMTimeSeriesData<-function(headObj,iType,nameInOutputFile,vIndex){ if(iType==0){ iIndex=(0:(headObj$SubCatchNum-1))[headObj$SubCatchName==nameInOutputFile] }else if(iType==1){ iIndex=(0:(headObj$NodesNum-1))[headObj$NodesName==nameInOutputFile] }else if(iType==2){ iIndex=(0:(headObj$LinksNum-1))[headObj$LinksName==nameInOutputFile] }else if(iType==3){ iIndex=0 } Status=array(NaN,headObj$ReportingPeriods) for(period in 0:(-1+headObj$ReportingPeriods)){ #browser() Status[period+1]=getSWMMResult(headObj=headObj,iType=iType,iIndex=iIndex,vIndex=vIndex,period=period) } return(Status) } TimeSeries<-function(Q, headObj){ f= data.frame(Q) f$hours = c(1:headObj$ReportingPeriods) require (ggplot2) p <- ggplot(f, aes(x = hours, y = Q)) + geom_line(color="red", size=1.5)+ scale_x_log10()+ scale_y_log10() p2<-p + ggtitle("Timeseries")+labs(x="Time",y="Flow(cfs)") print(p) return(p) } Exceedence1<-function(Q,headObj){ y=data.frame(Q) row_sub = apply(y, 1, function(row) all(row !=0 )) h = y[row_sub,] rank <- rank(h, ties.method="min") exceedtime <- 100 * (rank / (length(h)+1)) m=data.frame(exceedtime) m$Probability= sort(exceedtime, decreasing = T) m$Flow= sort(h) require (ggplot2) p2 <- ggplot(m, aes(x = Probability, y = Flow)) + geom_line(color="blue", size=1.5)+ scale_x_log10()+ scale_y_log10() p3<-p2 + ggtitle("Duration Curve for Simulated")+labs(x="Probability(%)",y="Flow(cfs)") print(p3) return(p3) } Exceedence2<-function(CalibrationData,headObj){ #wkObs = loadWorkbook("C:\\Users\\Alamdari\\Research\\R-SWMM Test Files\\Observed.xlsx") CalibrationData = readWorksheet(wkObs, sheet="Observed") x=data.frame(CalibrationData) rank <- rank(x$Observed, ties.method="min") exceedtime <- 100 * (rank / (nrow(x)+1)) m=data.frame(exceedtime) m$Probability= sort(exceedtime, decreasing = T) m$Flow= sort(x$Observed) require (ggplot2) p2 <- ggplot(m, aes(x = Probability, y = Flow)) + geom_line(color="red", size=1.5)+ scale_x_log10()+ scale_y_log10() p3<-p2 + ggtitle("Duration Curve for Observed")+labs(x="Probability(%)",y="Flow(cfs)") print(p3) return(p3) } # SimulatedData<-function(Q,headObj){ # Date = headObj$SWMMTimes # SimulatedData<-{} # SimulatedData$Times= data.frame(Date) # SimulatedData$Flow = data.frame(Q) # #write.xlsx(SimulatedData,"C:\\Users\\Alamdari\\Research\\R-SWMM Test Files\\Simulated.xlsx",sheet="TestSheet") # return(SimulatedData) # } # Calculate Runoff Volume # RunoffVolume<-function(Average){ # library(readxl) # Rainfall = read_excel("C:\\Users\\david\\Research\\DifficultRun_18Subs\\Washington_Hourly_2013.xlsx", sheet="Rainfall_Raw")# load XLConnect package # SimObsDate = data.frame(Average) # A = as.character.Date(Rainfall[,1]) # m = str_sub(A,12,19) # RainfallDate = as.POSIXct(paste(Rainfall[,1], m), format="%Y-%m-%d %H:%M:%S",tz="GMT") # Num1 = as.integer(RainfallDate) # left = str_sub(Num1,9,10) # left = as.numeric(left) # for (i in 1:length(left)){ # if(left[i]==99){ # Num1[i] = Num1[i]+ 1} # } # Num2 = as.integer(Average$Date) # Events = {} # Events$Date = SimObsDate$Date # k=1 # for (i in 1:nrow(SimObsDate)){ # Events$Sim[k]= 0 # Events$Obs[k]=0 # Events$Rain[k] = 0 # # k=k+1 # } # # k=1 # j=1 # # for (i in 1:nrow(SimObsDate)){ # for (j in 1:nrow(Rainfall)){ # if (Num2[i]-Num1[j]==0){ # Events$Rain[i]= Rainfall$Rainfall[j] # Events$Sim[i]= SimObsDate$Sim[i] # Events$Obs[i]= SimObsDate$Obs[i] # Events$Date[i] = SimObsDate$Date[i] # } # # } # } # # J=Events$Rain # H = Events$Sim # I = Events$Obs # X= Events$Date # ReadEventsFile = data.frame(Events) # # max=0 # count=0 # set=0 # for (i in 1:nrow(ReadEventsFile)){ # if(J[i]>=0.1){ # count=count+1 # if (count>max){ # max=count # } # if (J[i+1]<0.1){ # set=set+1 # } # } # else{ # count=0 # } # } # mm <- matrix(0, max, set) # nn <-matrix(0, max, set) # rr <-matrix(0, max+8, set) # xx<-matrix(0,max,set) # k=1 # m=1 # j=1 # # while (m!=(set+1)){ # if (J[k]>=0.1){ # mm[j,m]=J[k] # nn[j,m]=H[k] # rr[j,m]=I[k] # xx[j,m]=X[k] # j=j+1 # if (J[k+1]<0.1){ # m=m+1 # j=1 # } # k=k+1 # } # # else{ # k=k+1 # } # } # Sum = {} # Sum$Sim = colSums(nn) # Sum$Obs = colSums(rr) # Format= as.POSIXct(xx, origin = "1970-01-01", tz= "GMT") # Date = as.numeric(Format) # a = {} # b= {} # k=1 # m=1 # for (i in 1:set){ # a[k] = xx[1,i] # k=k+1 # } # m=2 # k=1 # for (i in 1:set){ # for (m in 2:(max)){ # if ((xx[m,i] == 0) & (xx[m-1,i]!=0)) { # b[k]=xx[m-1,i] # # } # if ((xx[m,i]!=0)){ # b[k]=xx[m,i] # } # # } # k=k+1 # } # # RunoffVolume = {} # RunoffVolume$Sim = Sum$Sim # RunoffVolume$Obs = Sum$Obs # return (RunoffVolume) # } #Hourly Calibration Aggregate1<-function(Q){ #define wkObs Sim <- aggregate(Q, list(hour=cut(as.POSIXct(headObj$SWMMTimes, format="%Y-%m-%d %H:%M:%S",tz="GMT"), "hour")), mean) #wkObs = loadWorkbook("2016_obs_watershed_outflow.xlsx") library(readxl) CalibrationData = read_excel("Observed.xlsx") #Creat Observed Data in the same format of Simulated Obs <- aggregate(CalibrationData$Flow, list(hour=cut(as.POSIXct(CalibrationData$Date, format="%Y-%m-%d %H:%M:%S",tz="GMT"), "hour")), mean) Average = {} Average$Date = Obs$hour Average$Sim = Sim$x Average$Obs = Obs$x return(Average) } #Create your rainfall data date same as writesimulatedObservedData File #Calibration for the events CalculateEvent<-function(Average){ library(stringi) library(stringr) library(lubridate) Rainfall = read_excel("Rainfall_Raw.xlsx") #wkSimObsDate = loadWorkbook("C:\\Users\\Alamdari\\Research\\R-SWMM Test Files\\WriteSimulatedObserved.xlsx") SimObsDate = data.frame(Average) A = as.character.Date(Rainfall[,1]) RainfallDate = as.POSIXct(A, format="%Y-%m-%d %H:%M:%S",tz="GMT") t <- strftime(RainfallDate, format="%H:%M:%S") a <- hms(as.character(t)) minute = minute(a) for (i in 1: length(RainfallDate)){ if(minute[i]==59){ RainfallDate[i]= RainfallDate[i]+1 } } Average$Date = as.POSIXct(Average$Date, format="%Y-%m-%d %H:%M:%S",tz="GMT") Num1 = as.integer(RainfallDate) Num2 = as.integer(Average$Date) Events = {} Events$Date = SimObsDate$Date k=1 for (i in 1:nrow(SimObsDate)){ Events$Sim[k]= 0 Events$Obs[k]=0 Events$Rain[k] = 0 k=k+1 } k=1 j=1 for (j in 1:nrow(Rainfall)){ for (i in 1:nrow(SimObsDate)){ if (Num2[i]-Num1[j]==0){ Events$Rain[i]= Rainfall$Rainfall[j] Events$Sim[i]= SimObsDate$Sim[i] Events$Obs[i]= SimObsDate$Obs[i] k=k+1 } } } J=Events$Rain H = Events$Sim I = Events$Obs X= Events$Date ReadEventsFile = data.frame(Events) max=0 count=0 set=0 for (i in 1:nrow(ReadEventsFile)){ if(J[i]>=0.1){ count=count+1 if (count>max){ max=count } if (J[i+1]<0.1){ set=set+1 } } else{ count=0 } } mm <- matrix(0, max, set) nn <-matrix(0, max, set) rr <-matrix(0, max, set) xx<-matrix(0,max,set) k=1 m=1 j=1 while (m!=(set+1)){ if (J[k]>=0.1){ mm[j,m]=J[k] nn[j,m]=H[k] rr[j,m]=I[k] xx[j,m]=X[k] j=j+1 if (J[k+1]<0.1){ m=m+1 j=1 } k=k+1 } else{ k=k+1 } } Maxmm <- matrix(0, 1,set) Maxnn <-matrix(0, 1,set) Maxrr <-matrix(0, 1,set) Maxxx <-matrix(0, 1,set) k=1 for (i in 1:set){ Maxmm[k,i]= max(apply(mm[,(i),drop=FALSE] ,2,max)) Maxnn[k,i]= max(apply(nn[,(i),drop=FALSE] ,2,max)) Maxrr[k,i]= max(apply(rr[,(i),drop=FALSE] ,2,max)) Maxxx[k,i]= xx[1,i] i=i+1 } FormatDate= as.POSIXct(Maxxx, origin = "1970-01-01", tz= "GMT") # # Char = as.character.Date(FormatDate) # #Months = str_sub(Char,1,7) # Days = str_sub(Char,1,10) # #NumDays = as.integer(Days) # Hours = str_sub(Char,12,13) # NumHours = as.integer(Hours) # # set2= 1 # for (j in 1:set){ # if (identical(Days[j+1],Days[j], num.eq = TRUE, single.NA = TRUE, attrib.as.set = TRUE, # ignore.bytecode = TRUE, ignore.environment = FALSE)==TRUE & (NumHours[j+1]- NumHours[j])<=(6+max)){ # use str_sub # set2=set2 # } # else{ # set2=set2+1 # } # } # Maxr = matrix(0, set+set,set2+set2) # Maxn = matrix(0, set+set,set2+set2) # Maxm = matrix(0, set+set,set2+set2) # k=1 # m=1 # j=1 # for (j in 1:1){ # if (identical(Days[j+1],Days[j], num.eq = TRUE, single.NA = TRUE, attrib.as.set = TRUE, # ignore.bytecode = TRUE, ignore.environment = FALSE)==TRUE & (NumHours[j+1]- NumHours[j])<=(6+max)){ # use str_sub # Maxm[k,m] = max(Maxmm[(j):(j+1)]) # Maxn[k,m] = max(Maxnn[(j):(j+1)]) # Maxr[k,m] = max(Maxrr[(j):(j+1)]) # k=k+1 # } # else{ # Maxm[k,m]= Maxmm[j] # Maxn[k,m]= Maxnn[j] # Maxr[k,m]= Maxrr[j] # m=m+1 # k=k+1 # } # } # # for (j in 2:(set)){ # if (identical(Days[j+1],Days[j], num.eq = TRUE, single.NA = TRUE, attrib.as.set = TRUE, # ignore.bytecode = TRUE, ignore.environment = FALSE)==TRUE & (NumHours[j+1]- NumHours[j])<=(6+max)){ # use str_sub # # # Maxm[k,m] = max(Maxmm[(j):(j+1)]) # Maxn[k,m] = max(Maxnn[(j):(j+1)]) # Maxr[k,m] = max(Maxrr[(j):(j+1)]) # k=k+1 # # # } # # else{ # if (j==2){ # m=m+1 # #Maxm[k]= max(Maxmm[i]) # # Maxn[k]= max(Maxnn[i]) # #Maxr[k]= max(Maxrr[i]) # #Max[k]= Maxxx[i] # Maxm[k,m]= Maxmm[j] # Maxn[k,m]= Maxnn[j] # Maxr[k,m]= Maxrr[j] # k=k+1 # m=m+1 # } # else{ # m=m+1 # #Maxm[k]= max(Maxmm[i]) # # Maxn[k]= max(Maxnn[i]) # #Maxr[k]= max(Maxrr[i]) # #Max[k]= Maxxx[i] # Maxm[k,m]= Maxmm[j+1] # Maxn[k,m]= Maxnn[j+1] # Maxr[k,m]= Maxrr[j+1] # k=k+1 # m=m+1 # } # # } # # # #mydf <- data.frame(mm[i+1],mm[i]) # #sdf <- stack(mydf) # #uni <- unique(sdf[, "values"]) # } # Maxm[is.na(Maxm)] <- 0 # Maxn[is.na(Maxn)] <- 0 # Maxr[is.na(Maxr)] <- 0 # # # MaxmNew = matrix(0, 1,(set2+set2)) # MaxnNew = matrix(0, 1,(set2+set2)) # MaxrNew = matrix(0, 1,(set2+set2)) # # k=1 # for (i in 1:(set2+set2)){ # MaxmNew[k,i]= max(apply(Maxm[,(i),drop=FALSE] ,2,max)) # MaxnNew[k,i]= max(apply(Maxn[,(i),drop=FALSE] ,2,max)) # MaxrNew[k,i]= max(apply(Maxr[,(i),drop=FALSE] ,2,max)) # i=i+1 # } MaxmNew = t(Maxmm) MaxnNew = t(Maxnn) MaxrNew = t(Maxrr) MaxmNew = data.frame(MaxmNew) MaxnNew = data.frame(MaxnNew) MaxrNew = data.frame(MaxrNew) EventsNew = {} EventsNew$Rain = MaxmNew$MaxmNew EventsNew$Sim = MaxnNew$MaxnNew EventsNew$Obs = MaxrNew$MaxrNew Dataframe = data.frame(EventsNew) EventsNew = Dataframe[apply(Dataframe[,-1], 1, function(x) !all(x==0)),] return(EventsNew) } #Calculating summary statistics PerfomrmStatistic2<-function(EventsNew){ require(hydroGOF) sim2 = EventsNew$Sim obs2 = EventsNew$Obs MeanError_2 = me(sim2,obs2) MeanSquaredError_2 = mse(sim2,obs2) IndexAgreement = d(sim2,obs2) IndexAgreementTimesMinus1_2 = -1*IndexAgreement Nashsutcliffe2 = NSE(sim2, obs2) NashsutcliffeTimesMinus1_2 = -1*Nashsutcliffe2 PercentBias2 = pbias(sim2,obs2) linearCorrelation2 =cor(sim2,obs2) linearCorrelationTimesMinus1_2 = -1*linearCorrelation2 output2=data.frame(MeanError_2,MeanSquaredError_2,IndexAgreementTimesMinus1_2,NashsutcliffeTimesMinus1_2,PercentBias2,linearCorrelationTimesMinus1_2) return(output2) } # Creating input files with uncertain parameters and name it as $1$ $2$ $3$ ReadSWMMOptFile<-function(SWMMOptFile){ SWMMOpt=readLines(con = SWMMOptFile, n = -1L, ok = TRUE, warn = TRUE, encoding = "unknown") return(SWMMOpt) } #Replace Optimization parameters to the Input File OptimizationFile<-function(Optimization){ Optimization = read.csv(file=Optimization, header = TRUE, sep = ",", quote="\"", dec=".", fill = TRUE, comment.char="",stringsAsFactors = FALSE) parameters = Optimization[,2] replacementCodes = Optimization[,1] return (Optimization) } replaceCodesInTemplateFile<-function(SWMMOpt,parameters, replacementCodes,File){ #Optimization = read.csv(file=Optimization, header = TRUE, sep = ",", quote="\"", dec=".", #fill = TRUE, comment.char="",stringsAsFactors = FALSE) #parameters = Optimization[,2] #replacementCodes = Optimization[,1] for(i in 1:length(parameters)){ SWMMOpt=sub(replacementCodes[i], parameters[i], SWMMOpt,fixed=TRUE) } writeLines(SWMMOpt, con = File, sep = "\n", useBytes = FALSE) return(SWMMOpt) } #Defining Minim, initial, and Maximum Vallues for uncertain parameters ParametersBound<-function(ParametersFile){ Bounds = read.csv(file=ParametersFile, header = TRUE, sep = ",", quote="\"", dec=".", fill = TRUE, comment.char="",stringsAsFactors = FALSE) #initial = Bounds$Initial #Minimum = Bounds$Minimum #Maximum = Bounds$Maximum return(Bounds) } Objectivefunction<-function(SWMMOptFile,x,OutFile,swmm,Timeseries,StatParameters){ SWMMOpt= ReadSWMMOptFile(SWMMOptFile) Input=paste(OutFile,iteration,'.inp',sep="") ReplaceCodes<<- replaceCodesInTemplateFile(SWMMOpt,x,as.matrix(Bounds["Code"]),Input) Report=paste(OutFile,iteration,'.rpt',sep="") Output=paste(OutFile,iteration,'.out',sep="") swmm= "C:\\Program Files (x86)\\EPA SWMM 5.1\\swmm5.exe" SWMMExe(swmm,Input,Report,Output) headObj = GetObjectsSWMM (Output) headObj = getSWMMTimes (headObj) Q = getSWMMTimeSeriesData(headObj,iType = 1,nameInOutputFile = "J11510.66",vIndex = 4) #TimeSeries = TimeSeries(Q, headObj) #Exceedence = Exceedence(Q, headObj) # SimulatedData = SimulatedData(Q, headObj) Average = Aggregate1(Q) # Average = read.zoo(data.frame(Average)) EventsNew = CalculateEvent(Average) require(hydroGOF) sim2 = EventsNew$Sim obs2 = EventsNew$Obs MeanError_2 = me(sim2,obs2) MeanSquaredError_2 = mse(sim2,obs2) IndexAgreement = d(sim2,obs2) IndexAgreementTimesMinus1_2 = -1*IndexAgreement Nashsutcliffe2 = NSE(sim2, obs2) NashsutcliffeTimesMinus1_2 = -1*Nashsutcliffe2 PercentBias2 = pbias(sim2,obs2) linearCorrelation2 =cor(sim2,obs2) linearCorrelationTimesMinus1_2 = -1*linearCorrelation2 library(hydroGOF) ggof(EventsNew$Sim, EventsNew$Obs, na.rm = TRUE, pt.style = "ts", ftype = "o", stype="default", gof.leg = TRUE, digits=2, gofs=c("me","RMSE","PBIAS","NSE","d","R2"),xlab = "Time", ylab=c("Q[cfs]")) output1=data.frame(NashsutcliffeTimesMinus1_2,PercentBias2,linearCorrelationTimesMinus1_2) library(xlsx) for (i in iteration){ write.xlsx(output1,paste("Combinations",i,".xlsx",sep=""))} SummaryStatistics1 = PerfomrmStatistic2(EventsNew) perfStatsToUse=as.numeric(SummaryStatistics1[StatParameters]) summaryRow=unlist(c(iteration,x,perfStatsToUse)) #write.xlsx(summaryRow[3:5],"summaryRow.xlsx",sheetName = paste("iteration",iteration),append = TRUE) names(summaryRow)= c("iteration",paste("Parameter",t(Bounds["Code"]),sep=""),StatParameters) iteration<<-iteration+1 print(summaryRow) return (summaryRow) } OptimizationFunction<-function(SWMMOptFile,OutFile,swmm,Timeseries,StatParameters,initial,lower,upper){ optimOpt={} optimOpt$OutFile = OutFile optimOpt$SWMMOptFile = SWMMOptFile optimOpt$swmm = swmm optimOpt$Timeseries = 'getSWMMTimeSeriesData(headObj=headObj,iType = 1,nameInOutputFile = "J11510.66",vIndex = 4)' optimOpt$StatParameters = StatParameters optimOpt$lower = lower optimOpt$upper = upper library(mco) out= nsga2(Objectivefunction, idim=length(optimOpt$lower), odim=length(optimOpt$StatParameters), OutFile= optimOpt$OutFile, SWMMOptFile = optimOpt$SWMMOptFile, swmm = optimOpt$swmm, Timeseries = optimOpt$Timeseries, StatParameters = optimOpt$StatParameters, generations=200, lower.bounds=as.double(optimOpt$lower), upper.bounds=as.double(optimOpt$upper), constraints=NULL,popsize = 1000) }
828c6c974c7e6f508e4890b199cd8f6acb454ca5
32ca0dd0dafbe713e2b7473dc036be1af9ed8b54
/run_analysis.R
e650a8ec2d3c28c0a25bd8447f306da7e2457cfc
[]
no_license
pyiapa/get-data004-project
f89f0f11e69ae40937f10edcc734a09a7b8e9800
9b4fdeae7a5811a2bbfd65c7d167b406d28b6c16
refs/heads/master
2021-01-13T01:55:39.299580
2014-06-22T23:20:59
2014-06-22T23:20:59
null
0
0
null
null
null
null
UTF-8
R
false
false
3,470
r
run_analysis.R
# Load the test and train data sets test_data = read.table("UCI HAR Dataset/test/X_test.txt") train_data = read.table("UCI HAR Dataset/train/X_train.txt") # Load the activity labels into a data frame activity_labels = read.table("UCI HAR Dataset/activity_labels.txt") colnames(activity_labels) <- c("id", "activity") # Get the id's that correspond to each activity for the subjects test_id_data = read.table("UCI HAR Dataset/test/y_test.txt") activity_id <- test_id_data$V1 # Create a vector with activity labels that correspond to the # activity id's. activities <- character() for(i in 1:length(activity_id)){ temp <- activity_labels[activity_id[i],] activities <- c(activities,as.character(temp$activity)) } # Attach the column with activity labels to the test data set test_data <- cbind(activities, test_data) # Attach the column with activity id's to the test data set test_data <- cbind(activity_id, test_data) # Load the subject id's subject_test_data = read.table("UCI HAR Dataset/test/subject_test.txt") subject_id <- subject_test_data$V1 # Attach the column with subject id's to the test data set test_data <- cbind(subject_id, test_data) # Collect train data # Get the id's that correspond to each activity for the subjects train_id_data = read.table("UCI HAR Dataset/train/y_train.txt") activity_id <- train_id_data$V1 # Create a vector with activity labels that correspond to the # activity id's. activities <- character() for(i in 1:length(activity_id)){ temp <- activity_labels[activity_id[i],] activities <- c(activities,as.character(temp$activity)) } # Attach the columns with activity labels and activity ids to the test data set train_data <- cbind(activities, train_data) train_data <- cbind(activity_id, train_data) # Load the subject id's subject_train_data = read.table("UCI HAR Dataset/train/subject_train.txt") subject_id <- subject_train_data$V1 # Attach the column with subject id's to the train data set train_data <- cbind(subject_id, train_data) # Merge the two data sets together mergedData = merge(test_data, train_data, all=TRUE) # Name the columns with proper labels from the features file features_data = read.table("UCI HAR Dataset/features.txt") column_names <- features_data$V2 column_names <- c("SubjectID", "ActivityID","Activity", as.character(column_names)) colnames(mergedData) <- column_names # Extract mean and standard deviation related columns col_names <- colnames(mergedData) mean_std_vector <- character() for(col in col_names){ if(grepl("std",col) | grepl("mean",col) | grepl("Mean",col)){ mean_std_vector <- c(mean_std_vector, col) } } mean_std_vector <- c("SubjectID", "ActivityID","Activity",mean_std_vector) mean_std_data <- mergedData[,mean_std_vector] # Find the averages and put them in a tidy file library(reshape2) # Get approproate column labels column_labels <- colnames(mean_std_data) column_labels <- column_labels[4:length(column_labels)] # Calculate avarages based on Acticity and Subject ID meltData <- melt(mean_std_data, id=c("Activity", "SubjectID"), measure.vars=column_labels) tidy_data <- dcast(meltData, SubjectID + Activity ~ column_labels, mean) # Tidy up the column labels column_labels <- lapply(column_labels, FUN= function(x) paste("AVG-", x, sep="")) column_labels <- c("SubjectID", "Activity", column_labels) colnames(tidy_data) <- column_labels # Write the tidy talbe back to a txt file write.table(tidy_data, file="tidy_set.txt")
194d63d12e101df09088495a198f0af378f3a915
0e1cd4250b7661a885b49ba3bbfd88c775d3869f
/searching_cited_books.R
2e8f81ed422aa8ce3f17e18471c7fe9044dd0918
[]
no_license
silviaegt/wiki-cite-colmex
c7439d89baf11c3442252add420a250074518960
848594fda469192ef23122fa14b947721fb8047b
refs/heads/master
2021-07-16T06:52:47.280466
2020-05-22T18:58:33
2020-05-22T18:58:33
149,190,161
1
0
null
null
null
null
UTF-8
R
false
false
6,504
r
searching_cited_books.R
getwd() #install.packages("XML") require(XML) library("methods") library("dplyr") library("tidyr") # set working directory # here you add were your data is (remember to change \ from Windows paths) setwd("yourpath") #1. Read your tsv with all citations with identifiers extracted from the most recent version of your language Wikipedia #Available here: https://figshare.com/articles/Wikipedia_Scholarly_Article_Citations/1299540/10 # (in this example we look at Spanish Wiki) eswiki <- read.table(file = 'eswiki.tsv', sep = '\t', header = TRUE, fill=TRUE, encoding = "UTF-8") #2. To get a glimpse of the first rows and thus of how data is ordered: #head(eswiki) #3. To get a summary of your data #sumeswiki <- summary(eswiki) #here we get, for instance, that the pages with the biggest number of references are: #Evolución bilógica(461), Infiriendo transferencia genética horizontal (252), and Historia social de los virus (229) ############Let's start digging into our data################# #1. Retrieve all types of ids types <- sort(table(eswiki$type),decreasing=T) View(types) barplot(types) #Compare with: https://medium.com/freely-sharing-the-sum-of-all-knowledge/what-are-the-ten-most-cited-sources-on-wikipedia-lets-ask-the-data-34071478785a #note how isbns are the more dominant! #2. Filter rows that have "isbn"; thus all book-citations libros <- eswiki[ which(eswiki$type=='isbn'), ] #2.1 Convert "libros" into a dataframe library("tibble") libros_df <- as_data_frame(libros) #View(libros) #summary(libros) #2.2 Create a subset with all the books that cite one book you know about as a test #Here you can see my test with "Historia Mínima de México" el El Colegio de México historia_minima = c(9681211391,9789681211394,9788415832010, 9789681211387, 9789680101672) hm_citations <- libros_df[which(libros_df$id %in% historia_minima),] View(hm_citations) #Notes: only one out of the 5 different isbns of the same book has been used: "9681211391" (2004 edition) ####################################################### ####3. Extract all ISBNs from your University Press#### ####################################################### # A little pre-processing was necessary for my data (did it with openrefine) #registroscolmex <- separate(registroscolmexraw, ISBN, into = c("ISBN", "Notas"), sep = "\\s") library(readr) registroscolmex <- read_csv("delColmex_limpio.csv", col_types = cols(ISBN = col_character())) View(registroscolmex) ## This is to subset where my real information is registroscolmexisbn <- subset(registroscolmex, (!is.na(registroscolmex$ISBN))) colmexissn <- subset(registroscolmex, (!is.na(registroscolmex$ISSN))) #This is a list of registers without ISBN, ISSN registroscolmexsinisbn <- subset(registroscolmex, (is.na(registroscolmex$ISBN)) & (is.na(registroscolmex$ISSN))) titulos_sin_isbn <- sort(table(registroscolmexsinisbn$title), decreasing = T) write.csv(registroscolmexsinisbn, file = "registroscolmex_sin-isbn-issn.csv", row.names=FALSE) length(registroscolmexisbn$ISBN) isbncolmexfreq <- as.data.frame(sort(table(registroscolmex$ISBN), decreasing = T)) colnames(isbncolmexfreq) <- c("ISBN", "Frecuencia") write.csv(isbncolmexfreq, file = "isbncolmexfreq.csv", row.names=FALSE) ############################################################ ###4. Compare your ISBNs with the ones cited in Wikipedia### ########################################################### #Now that I have my list of unique ISBNs isbncolmex <- isbncolmexfreq$ISBN #I will see if they are in the df of cited books in Wikipedia colmexcite_df <- as_data_frame(libros_df[which(libros_df$id %in% isbncolmex),]) View(colmexcite_df) #Number of unique different websites that cite our books length(unique(colmexcite_df$page_title)) #63 #Number of unique different books cited in Wikipedia length(unique(colmexcite_df$id)) #38 wikipages_list <- as.character(colmexcite_df$page_title) wikipagesfreq <- sort(table(wikipages_list), decreasing=T) View(wikipagesfreq) citedisbn_list <- as.character(colmexcite_df$id) citedisbnfreq <- as.data.frame(sort(table(citedisbn_list), decreasing=T)) registroscolmex_sin_repetir <- registroscolmexisbn[!duplicated(registroscolmexisbn$ISBN),] citedisbn_joined <- inner_join(citedisbnfreq , registroscolmex_sin_repetir, by=c("citedisbn_list"="ISBN")) citedisbn_joined[is.na(citedisbn_joined)] = 0 length(citedisbn_joined$freq) citedisbn <- data.frame(citedisbn_joined$citedisbn_list, citedisbn_joined$title, citedisbn_joined$Autor, citedisbn_joined$Freq) names(citedisbn) <- c("ISBN", "Título", "Autor", "No. de Citas") sort(table(citedisbn$Autor), decreasing = T) write.csv(citedisbn, file = "citedisbn.csv", row.names=FALSE) ############################################################################# # Get a filtered version of the books that do have citations on Wikipedia cited_books <- registroscolmex[which(registroscolmex$ISBN %in% citedisbn_list),] citedcenter <- table(cited_books$DEPARTAMENTO) citedyear <- table(cited_books$A.d1.O.EDICI.d3.N) View(citedyear) #3.1 Export different results into a csv #write.csv(libros, file = "eslibros.csv", row.names=FALSE) #write.csv(hm_citations, file = "hm_citations.csv", row.names=FALSE) #write.csv(colmexcite_df, file = "colmexcitations.csv", row.names=FALSE) write.csv(cited_books, file = "cited_books.csv", row.names=FALSE) pagwiki_citations <- table(colmex_citations$page_title) pagwiki_citations #4. Retrieve the most frequent isbns and get titles from OCLC (work in prgress) freqbooks <- sort(table(libros$id),decreasing=T) View(freqbooks) twenty <- data.frame(freqbooks[1:20]) class(data.frame(twenty)) twenty[1,1] dim(twenty) length(twenty$Var1) for (i in 1:3){ isbn = twenty[i,1] url = sprintf("http://classify.oclc.org/classify2/Classify?isbn=%s&summary=true", isbn) data <- xmlTreeParse(url) xml_data <- xmlToList(data) works = xml_data[[8]] print(works[[1]]) } library(rvest) work <- read_html("http://classify.oclc.org/classify2/Classify?isbn=3822847445&summary=true") #data <- xmlParse() # load packages library("XML") data <- xmlTreeParse(url) # convertimos a lista xml_data <- xmlToList(data) # hay 8 elementos en la lista length(xml_data) works = xml_data[[8]] # y de ahí quieres: author, holding, hyr y title # author works[[1]] # holding works[[4]] #hyr works[[5]] #title works[[10]] #http://classify.oclc.org/classify2/Classify?isbn=0940228475&summary=truev barplot(freqbooks)
d91611d89f68cb769bf6c07a65c2cf5809d221a6
93356416c6941126c3627edccabb08696d10dd05
/phospho_network/regression/generate/regression_multi_kinase_match_sub_BI.R
bcdb54817ca1b49a794965ad9b4f5833f67e9dc5
[]
no_license
ding-lab/phosphoproteomics
22c9a69127e7397c54dddba044d4588b495f21c5
00538a56143be08c0fffae8df6dd54f2bfdd4734
refs/heads/master
2021-03-19T06:18:15.490109
2019-04-25T21:36:45
2019-04-25T21:36:45
90,892,479
0
0
null
null
null
null
UTF-8
R
false
false
10,127
r
regression_multi_kinase_match_sub_BI.R
# Yige Wu @ WashU 2017 Feb # adopted by Kuan Huang @ Washu 2017 Apr # look at correlations of kinase and downstream substrates phosphorylation status # pho_sub~pro_sub+pho_kin(callapsed,multiple) # choose kinase/phosphotase, significance level, outlier threshold and least sample number------------------------- least_samples <- 10# least number of samples with complete data for each model protein <- "kinase" # protein <- "phosphotase" # library ----------------------------------------------------------------- library(stringr) library(ggplot2) library(reshape) library(grid) require(plyr) # for working on Kuan's mac baseD = "/Users/khuang/Box\ Sync/PhD/proteogenomics/CPTAC_pan3Cancer/" # # for working on Yige's mac # baseD = "/Users/yigewu/Box\ Sync/" setwd(paste(baseD,"pan3can_analysis/phospho_network",sep="")) source("../pan3can_aes.R") # aes for general purposes; it should be one directory out of the working directory # input k_s_table according to kinase or phosphotase------------------------------------------------------------------- if ( protein == "kinase" ) { ### read in the kinase/substrate table/ phosphorylation data ### k_s_table_phosphosite = read.delim(paste(baseD,"pan3can_shared_data/Phospho_databases/PhosphositePlus/data/Kinase_Substrate_Dataset_human_final_hugoified.txt",sep="")) k_s_table_network = read.delim(paste(baseD,"pan3can_shared_data/Phospho_databases/PhosphoNetworks/comKSI.csv",sep="")) k_s_table_phosphosite_sum = k_s_table_phosphosite[,c("GENE","SUB_GENE")] colnames(k_s_table_phosphosite_sum) = c("Kinase","Substrate") k_s_table_phosphosite_sum$Score=0 k_s_table = rbind(k_s_table_phosphosite_sum,k_s_table_network) } if ( protein == "phosphotase" ) { ### read in the phosphotase/substrate table/ phosphorylation data ### k_s_table <- read.csv(paste(baseD,"pan3can_shared_data/Phospho_databases/DEPOD/DEPOD_201612_human_phosphatase-protein_substrate_to_Kuan-lin.csv",sep = "")) colnames(k_s_table) <- c("Phosphatase_UniProtAC_human","GENE","Substrate_UniProtAC_ref","SUB_GENE","Substrate_Type","DephosphoSite","BioassayType", "PubMed_ID_rev") } substrate_trans <- as.vector(unique(k_s_table$Substrate[as.vector(k_s_table$Kinase)!=as.vector(k_s_table$Substrate)])) kinase_trans <- as.vector(unique(k_s_table$Kinase[as.vector(k_s_table$Kinase)!=as.vector(k_s_table$Substrate)])) table_single <- read.delim(paste(baseD,"pan3can_shared_data/analysis_results/tables/BRCA_HUMAN_",protein,"_substrate_regression_trans.txt", sep="")) # looping cancer ----------------------------------------------------------- for (cancer in c("HUMAN","PDX")) { # input according to cancer type------------------------------------------------------------------- if (cancer == "HUMAN") { # HUMAN HUMAN_pro_f = paste(baseD,"pan3can_shared_data/BRCA/BRCA77_unimodal_proteome-ratio-norm_exp_collapsed.txt",sep="") pro_data <- read.delim(HUMAN_pro_f) HUMAN_pho_f = paste(baseD,"pan3can_shared_data/BRCA/BRCA77_unimodal_phosphoproteome-ratio-norm_wGpos_cleaned.txt",sep="") pho_data = read.delim(HUMAN_pho_f) ## read in grouped phosphorylation data! HUMAN_pho_g = paste(baseD,"pan3can_shared_data/BRCA/BRCA77_unimodal_phosphoproteome-ratio-norm_collapsed.txt",sep="") pho_gdata = read.delim(HUMAN_pho_g) } if ( cancer == "PDX" ) { PDX_pho_f = paste(baseD,"pan3can_shared_data/BRCA/whim_phosphoproteome-ratio-norm_exp_filtered.txt",sep="") pho_data = read.delim(PDX_pho_f) colnames(pho_data)[2:3] = c("Gene","Gene.site") PDX_pho_g = paste(baseD,"pan3can_shared_data/BRCA/whim_phosphoproteome-ratio-norm_exp_filtered_collapsed.txt",sep="") pho_gdata = read.delim(PDX_pho_g) PDX_pro_f = paste(baseD,"pan3can_shared_data/BRCA/whim_proteome-ratio-norm_exp_v2_filtered_collapsed.txt",sep="") pro_data <- read.delim(PDX_pro_f) } # remove the phosphoproteins that have identical levels #pho_gdata = pho_gdata[pho_gdata$X != "CSNK2A2",]# identical entry as CSNK2A1 pho_gdata = pho_gdata[!duplicated(pho_gdata[,colnames(pho_gdata) != "X"]),] #split the SUBSTRATE and SUB_MOD_RSD in the first column pho_rsd_split <- data.frame(str_split_fixed(pho_data$Gene.site, ":", 3)) #covert the SUB_MOD_RSD from lowercase to uppercase pho_rsd_split[,3] <- toupper(pho_rsd_split[,3]) colnames(pho_rsd_split) <- c("SUBSTRATE","transcript","SUB_MOD_RSD") # remove duplicate and identical phosphoyrlation levels for different transcript # ps: they're not important genes dup_pho <- data.frame(table(paste(pho_rsd_split$SUBSTRATE,pho_rsd_split$SUB_MOD_RSD,sep = ":"))) dup_pho <- dup_pho[dup_pho$Freq>1,] dup_pho <- data.frame(str_split_fixed(dup_pho$Var1, ":", 2)) dup_pro <- as.vector(dup_pho$X1); dup_rsd <- as.vector(dup_pho$X2) remove_rows <- c() for (i in 1:nrow(dup_pho)) { dup_rows <- which(pho_rsd_split$SUBSTRATE==dup_pro[i] & pho_rsd_split$SUB_MOD_RSD==dup_rsd[i]) remove_rows <- c(remove_rows,dup_rows[-1]) } pho_rsd_split <- pho_rsd_split[-remove_rows,] pho_data <- pho_data[-remove_rows,] transcripts <- as.vector(pho_rsd_split$transcript) colx <- which(colnames(pro_data)=="X") # initiate ---------------------------------------------------------------- # calculate the length of trans table substrate_reg <- intersect(intersect(substrate_trans, pro_data$X),pho_rsd_split$SUBSTRATE) # use pro data and phosphosite data to narrow down the substrates to be examined(2119 to 1364) ntrans <- 0 for (gene in kinase_trans) { subs <- k_s_table$Substrate[k_s_table$Kinase==gene & k_s_table$Substrate!=gene] for ( sub in unique(subs)) { ntrans <- ntrans + length(which(pho_rsd_split$SUBSTRATE==sub)) } } phosphosites <- unique(table_single[table_single$SELF=="trans",c("SUBSTRATE","SUB_MOD_RSD","transcript")]) substrates <- as.vector(phosphosites$SUBSTRATE) rsds <- as.vector(phosphosites$SUB_MOD_RSD) for (i in 1:nrow(phosphosites)) { phosphosites$pho_size[i] <- length(which(!is.na(pho_data[pho_rsd_split$SUBSTRATE==substrates[i] & pho_rsd_split$SUB_MOD_RSD==rsds[i],-colx]))) phosphosites$num_k[i] <- nrow(table_single[table_single$SELF=="trans" & table_single$SUBSTRATE==substrates[i] & table_single$SUB_MOD_RSD==rsds[i],]) } phosphosites_multi <- phosphosites[phosphosites$num_k > 1,] substrates <- as.vector(phosphosites_multi$SUBSTRATE) rsds <- as.vector(phosphosites_multi$SUB_MOD_RSD) # looping over phosphosites for trans pairs ----------------------------------------------------------------- # initiating the table for trans vec_char <- vector(mode = "character", length = ntrans) vec_num <- vector(mode = "numeric", length = ntrans) + NA KINASE <- vec_char;SUBSTRATE <- vec_char; SUB_MOD_RSD <- vec_char; FDR_pro_kin <- vec_num;FDR_pro_sub <- vec_num;FDR_pho_kin <- vec_num; coef_pro_kin <- vec_num;coef_pro_sub <- vec_num;coef_pho_kin <- vec_num; Cancer <- vec_char;transcript <- vec_char;model <- vec_char; Size <- vec_num;num_k <- vec_num;P_pro_kin <- vec_num;P_pro_sub <- vec_num;P_pho_kin <- vec_num; count <- 0 examine1 <- vector(mode = "logical", length = nrow(phosphosites_multi)) for (i in 1:nrow(phosphosites_multi)) { substrate <- substrates[i] rsd <- rsds[i] pho_row <- which(pho_rsd_split$SUBSTRATE==substrate & pho_rsd_split$SUB_MOD_RSD==rsd) tscp <- transcripts[pho_row] #pho_sub <- t(pho_data[pho_row,-colx]) pho_sub <- t(pho_data[pho_row,-c(1:3)]) pro_sub <- t(pro_data[pro_data$X == substrate,-colx]) sub_k <- as.vector(unique(table_single$KINASE[table_single$SELF=="trans" & table_single$SUBSTRATE==substrate & table_single$SUB_MOD_RSD==rsd])) num_k <- sum(pho_gdata$X %in% sub_k) # rows <- c() # for (k in sub_k) { # temp <- which(pho_gdata$X==k) # rows <- c(rows,temp) # } # pho_kins <- t(pho_gdata[rows,-colx]) pho_kins <- t(pho_gdata[pho_gdata$X %in% sub_k,-colx]) data1 <- data.frame(pro_sub,pho_kins) colnames(data1)[1] <- "pro_sub" data2 <- data.frame(pho_sub,data1) colnames(data2)[1] <- "pho_sub" size <- nrow(data2[complete.cases(data2),]) if(size > least_samples & size >= num_k + 15){ fit2 <- lm(pho_sub ~ ., data = data2) pvalues <- coef(summary(fit2)) coefs <- fit2$coefficients examine1[i] <- TRUE for (j in 1:num_k) { count <- count + 1 KINASE[count] <- sub_k[j] SUBSTRATE[count] <- substrate SUB_MOD_RSD[count] <- rsd transcript[count] <- transcripts[i] P_pro_sub[count] <- pvalues[2,4] coef_pro_sub[count] <- fit2$coefficients[2] P_pho_kin[count] <- pvalues[j+2,4] coef_pho_kin[count] <- coefs[j+2] Size[count] <- size } } cat(i,'processed \n') } table_trans <- data.frame(KINASE,SUBSTRATE,SUB_MOD_RSD, FDR_pro_kin,FDR_pro_sub,FDR_pho_kin, coef_pro_kin,coef_pro_sub,coef_pho_kin, Cancer,transcript,model,Size, P_pro_kin,P_pro_sub,P_pho_kin) phosphosites_multi$examine1 <- examine1 # integrate table from all the models(need to repetite again for another cancer dataset) -------------------------------------------------------- table_trans$model <- "pho_sub~pro_sub+pho_kins" tabletrans <- table_trans[!is.na(table_trans$P_pro_sub),] name = c("pro_kin","pro_sub","pho_kin") ## adjust p-values to FDR for(coln in name) {#adjust pvalues for each variable tabletrans[,paste("FDR_",coln,sep = "")] <-p.adjust(tabletrans[,paste("P_",coln,sep = "")],method = "fdr") } tabletrans$pair <- paste(tabletrans$KINASE,tabletrans$SUBSTRATE,tabletrans$SUB_MOD_RSD,sep = ":") tabletrans = tabletrans[order(tabletrans$P_pho_kin),] # write out tables -------------------------------------------------------- tn = paste(baseD,"pan3can_shared_data/analysis_results/tables/BRCA_",cancer, "_", protein,"_substrate_regression_multi.txt", sep="") write.table(tabletrans, file=tn, quote=F, sep = '\t', row.names = FALSE) }
8fe00d4350d195ba4f971ae1e326b7125916a683
bcb5995a65f0d1764d1eb56816016f1aab9195ef
/workspace.r
ea5cb7e458b167eb373f3bd14de077f12de3b221
[]
no_license
pamgene/combatapp_nosync
c99c476edae5618c16c1e05722da7b62cbb78e56
77fcd3476cc1c979a6f25a598c4c6b0cfdd5d32b
refs/heads/master
2023-04-25T04:35:58.209522
2020-07-23T07:53:58
2020-07-23T07:53:58
null
0
0
null
null
null
null
UTF-8
R
false
false
556
r
workspace.r
library(bnutil) library(shiny) library(reshape2) library(pgBatch) library(combatapp) library(ggplot2) library(dplyr) getdata = function() { aData = AnnotatedData$new(data = combat_testdf, metadata =combat_testmetadf) } setResult = function(annotatedResult){ print(annotatedResult) result = annotatedResult$data } bnMessageHandler = bnshiny::BNMessageHandler$new() bnMessageHandler$getDataHandler = getdata bnMessageHandler$setResultHandler = setResult bnshiny::startBNTestShiny('combatapp', sessionType='show', bnMessageHandler=bnMessageHandler)
1a63ac51ff1cc1bb7367afa4becf32bd4d4b2bcb
67d49ab26430e7bfb5ca8889d2250309d1e97b9a
/xgboost_cv.R
27c64d3121e2690f191320f96e4df94670594ea2
[]
no_license
arpang87/XGBOOST_CROSSVALIDATION_IN_R
ff192ad391619d20bb682fbc8a9a2b67f2134a72
7cddc72bb3394571c45fb1962eb91cc4a54909d7
refs/heads/master
2022-12-23T14:03:08.760919
2020-09-30T12:07:34
2020-09-30T12:07:34
299,905,455
1
0
null
null
null
null
UTF-8
R
false
false
5,988
r
xgboost_cv.R
#title: "xgboost with crossvalidation in R" #author: "Arpan" #date: "January 4, 2017" #output: pdf_document Setting the seed so that we get the same results each time we run the model set.seed(123) Importing the library mlbench for sonar dataset library(mlbench) library(caret) Storing the data set named "Sonar" into DataFrame named "DataFrame" data("Sonar") DataFrame <- Sonar Type help("Sonar") to know about the data set help("Sonar") Check the dimension of this data frame dim(DataFrame) Check first 3 rows head(DataFrame,3) Check the summary of data summary(DataFrame) Lets check the data set again str(DataFrame) Lets create the train and test data set.Target variable is Class library(caTools) library(caret) ind = createDataPartition(DataFrame$Class, p = 2/3, list = FALSE) trainDF<-DataFrame[ind,] testDF<-DataFrame[-ind,] We will be using the caret package for crossvalidation.Function named train in caret package is used for crossvalidation. Let's choose the paramters for the train function in caret number = 5(It means we are using 5 fold cross-validation) method="cv"(Means we are using cross-validation.You can also choose other like LOOCV or repeated CV,etc.) classProbs=TRUE(It will give the probabilities for each class.Not just the class labels) ```{r} ControlParamteres <- trainControl(method = "cv", number = 5, savePredictions = TRUE, classProbs = TRUE ) We will put the above paramter in the model below in trControl argument Following are the Tuning parameters which one can tune for xgboost model in caret: 1. nrounds (# Boosting Iterations) It is the number of iterations the model runs before it stops.With higher value of nrounds model will take more time and vice-versa. 2. max_depth (Max Tree Depth) Higher value of max_depth will create more deeper trees or we can say it will create more complex model.Higher value of max_depth may create overfitting and lower value of max_depth may create underfitting.All depends on data in hand.Default value is 6. range: [1,infinity] 3. eta (Shrinkage) It is learning rate which is step size shrinkage which actually shrinks the feature weights. With high value of eta,model will run fast and vice versa.With higher eta and lesser nrounds,model will take lesser time to run.With lower eta and higher nrounds model will take more time. range: [0,1] 4. gamma (Minimum Loss Reduction) It is minimum loss reduction required to make a further partition on a leaf node of the tree. The larger value will create more conservative model. One can play with this parameter also but mostly other parameters are used for model tuning. range: [0,infinity] 5. colsample_bytree (Subsample Ratio of Columns) Randomly choosing the number of columns out of all columns or variables at a time while tree building process.You can think of mtry paramter in random forest to begin understanding more about this.Higher value may create overfitting and lower value may create underfitting.One needs to play with this value. range: (0,1] 6. min_child_weight (Minimum Sum of Instance Weight) You can try to begin with thinking of min bucket size in decision tree( rpart).It is like number of observations a terminal node.If the tree partition step results in a leaf node with the sum of instance weight less than min_child_weight, then the building process will give up further partitioning. In linear regression mode, this simply corresponds to minimum number of instances needed to be in each node range: [0,infinity] Why do we need model tuning? As we have already seen there are lot of parameters in xgboost model like eta,colsample_bytree,etc.You do not know which values of each parameters would give you the best predictive model.So you need to create a grid of several combinations of parameters which you think that can deliver best results.You can start by your intuition and later on keep on modifying the paramters till you are satisfied with the results. Here,for demonstration purpose I'm only choosing two values of colsample_bytree and two values of max_depth.For rest of the parameters single value is taken. parametersGrid <- expand.grid(eta = 0.1, colsample_bytree=c(0.5,0.7), max_depth=c(3,6), nrounds=100, gamma=1, min_child_weight=2 ) To check how this grid looks like type as below.It gives four combinations of parameters.You can choose more combinations if you need or want. parametersGrid Let's now do the 5-fold crossvalidation for the xboost the model with the chosen parameters grid using train function.We will put the parametersGrid in the tuneGrid argument and controlParameters in trControl argument of train function. To know more about the train function type and run ?train in the console modelxgboost <- train(Class~., data = trainDF, method = "xgbTree", trControl = ControlParamteres, tuneGrid=parametersGrid) Let's check the crossvalidation results for parameters tuning for xgboost model.We can easily see that there are four rows with each having the combination and their corresponding accuracy and kappa,etc.For max_depth=3 and colsample_bytree=0.5( rest values are fixed as we choose),the value of accuracy and kappa is 0.8203 and 0.6375(approx) respectively. As the max_depth =3 and colsample_bytree=0.7 gives the best accuracy,the final model is choosen for [nrounds = 100, max_depth = 3, eta = 0.1, gamma = 1, colsample_bytree = 0.7 and min_child_weight = 2].You can choose any customized metric other than accuracy.You have to put that in trainControl function. modelxgboost Let's check the predictions on the test data set predictions<-predict(modelxgboost,testDF) Let's check the confusion matrix t<-table(predictions=predictions,actual=testDF$Class) t
c81af4afb98574503fdeae7396a71beddb32ceaf
d1e8ac310e5ab7ad7e7e8641951cc0217efd10fa
/man/setDreamerr_dev.mode.Rd
a0bb6ee89b0ff06466f89668addb38a102c9367a
[]
no_license
cran/dreamerr
ed38bbc4838c2e86ed6567564eadd236c174a8e4
57b2abc755ed9663f95f770bb865dd53d75bd6b9
refs/heads/master
2023-08-31T02:45:12.600138
2023-08-23T21:30:02
2023-08-23T22:30:49
255,887,390
0
0
null
null
null
null
UTF-8
R
false
true
1,884
rd
setDreamerr_dev.mode.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/misc_funs.R \name{setDreamerr_dev.mode} \alias{setDreamerr_dev.mode} \title{Sets the developer mode to help form check_arg calls} \usage{ setDreamerr_dev.mode(dev.mode = FALSE) } \arguments{ \item{dev.mode}{A logical, default is \code{FALSE}.} } \description{ Turns on/off a full fledged checking of calls to \code{\link[dreamerr]{check_arg}}. If on, it enables the developer mode which checks extensively calls to check_arg, allowing to find any problem. If a problem is found, it is pinpointed and the associated help is referred to. } \details{ Since this mode ensures a detailed cheking of all \code{\link[dreamerr]{check_arg}} calls, it is thus a strain on performance and should be always turned off otherwise needed. } \examples{ # If you're new to check_arg, given the many types available, # it's very common to make mistakes when creating check_arg calls. # The developer mode ensures that any problematic call is spotted # and the problem is clearly stated # # Note that since this mode ensures a detailed cheking of the call # it is thus a strain on performance and should be always turned off # otherwise needed. # # Setting the developer mode on: setDreamerr_dev.mode(TRUE) # Creating some 'wrong' calls => the problem is pinpointed test = function(x) check_arg(x, "integer scalar", "numeric vector") try(test()) test = function(...) check_arg("numeric vector", ...) try(test()) test = function(x) check_arg(x$a, "numeric vector") try(test()) test = function(x) check_arg(x, "numeric vector integer") try(test()) test = function(x) check_arg(x, "vector len(,)") try(test()) # etc... # Setting the developer mode off: setDreamerr_dev.mode(FALSE) } \seealso{ \code{\link[dreamerr]{check_arg}} } \author{ Laurent Berge }
8670b12256578f07d708cf7e08ef0f953743314f
9e96145ecbea0530c967c14d17c35f1635f3c6f6
/FC_script.R
ebde99a8da5b2262aad9a2618e710cb8d1b147df
[]
no_license
colina83/Case_Study_Data_Science_for_Business
ceda63f67d9997c9163edd959ba44e3ad48a997a
7e72f02db17946b0686347342c9007032b88240a
refs/heads/main
2023-03-14T04:41:24.529452
2021-03-02T18:45:04
2021-03-02T18:45:04
341,239,957
0
0
null
null
null
null
UTF-8
R
false
false
6,244
r
FC_script.R
############################################### ## Tasks to do Prior Starting the project #Import Libraries library(Hmisc) library(Rmisc) library(jtools) library(UsingR) library(tidyverse) library(lmtest) library(sandwich) library(mctest) library(ggplot2) library(expss) #Uploading Data to R d <- ThyssenKrupp_PPL_Data_Final_20150513 # Excel File e <- ThyssenKrupp_Data # RDS File from all(e == d) # JUst checking that all values are the same in both datasets #Arrange the names of variables names(d) <- gsub(" ", "_", names(d)) #Information regarding size and Variables ## dim(d) # Number of Variables -> Rows (Observations ) & Variables names(d) # Variable Names table(d$shift_type) #Cleaning & Preparing Data ## identify variables that needs to be converted to factors (Day & Night Shift) ## Cleanup the date variable, we only need the date d$shift <- str_remove(d$shift,"22:00:00") d$shift <- str_remove(d$shift,"06:00:00") d$shift <- str_remove(d$shift,"14:00:00") #Exploratory Data Analysis and Plots ####################################################### #PART A #Answering Questions: #1.Perform a univariate analysis and answer the following questions: #a.- What is the average number of strips per shift? d$Total_Strips <- (d$thickness_1+d$thickness_2+d$thickness_3) Average_strips <- mean(d$Total_Strips) t1 <- sum(d$thickness_1) summary(d$MPT) #1.b- Which is the most common and least common a = sum(d$thickness_1)/sum(d$Total_Strips)*100 b = sum(d$thickness_2)/sum(d$Total_Strips)*100 c = sum(d$thickness_3)/sum(d$Total_Strips)*100 ## Thickness 2 is the most common and thickness 3 is the least common ## FC to create graph jpeg('1b.jpg') Bar_Plot_Q1b <- barplot(c(a,b,c), b,col=c("darkblue","lightblue","gray"), main = "Thickness Values", xlab = "Thickness", legend = c("Thickness 1", "Thickness 2", "Thickness 3")) dev.off() #1.C Values of delta par(mfrow =c(1,2)) boxplot(summary(d$run_time_ratio)) boxplot(summary(d$delta_throughput)) ## Add a summary table, and make the plot prettier Delta_Throughput_Summary <- summary(d$delta_throughput) Run_Time_Ratio <- summary(d$run_time_ratio) rbind(table_DT,table_TR) ##################################################### table(d$grade_1 == 100) table(d$grade_2 == 100) table(d$grade_3 == 100) table(d$grade_4 == 100) table(d$grade_5 == 100) table(d$grade_rest == 100) ##grade 1, 4, 5 and rest have 100 % ## 2.- Can the RTR Theory explain deviations valcol <- (d$MPT + abs(min(d$MPT)))/max(d$MPT + abs(min(d$MPT))) # This variable is to identify the low MPT values in light blue and the high MPT values in darker color plot(d$delta_throughput ~ d$run_time_ratio, xlab="RTR", ylab="Delta Throughput", main="Scatterplot Delta Througput", col = rgb(0, 0, valcol)) abline(h= 0,col ="black") lm_dt <- lm(d$delta_throughput ~ d$run_time_ratio) abline(lm_dt,col = "red") abline(h= 0,col ="black") # Points below zero summary(lm_dt) #3.- MPT plot(d$delta_throughput ~ d$MPT, xlab = "MPT", ylab = "Delta Throughput", main = "Scatterplot") lm_mpt <- lm(d$delta_throughput ~ d$MPT) abline(lm_mpt,col = "red") plot(d$delta_throughput ~ d$Total_Strips, xlab="Number of Strips per Shift", ylab="Delta Throughput", main="Scatterplot Delta Througput") # 4.- Regression model to predict delta throughput # The question alludes that all independent variables should be based on the characteristic of the strips # We did not include MPT (meters per ton), a dimension indicator, but a theoretical factor calculated by the engineers # Schulze did not account for MPT, so we based our models on the characteristics of the material # We have left thickness 1 to 3 and Width and Width3 , as this complements each other to account to a total number of strips # Grade is significant, and we have included 3 variables out of 6 # Test - heteroskedasticity - Removal of Grade 3 # Test Pass - Model with Grade 1 and Grade 5 (Final) lm_final <- lm(delta_throughput ~ thickness_1+ thickness_2 + thickness_3 + width_1 + width_3 + grade_1 + grade_5 + run_time_ratio, data = d) summary(lm_final) # Plotting to see the dispersion between the fitted values (estimations) and the residuals (errors) plot(fitted(lm_new),residuals(lm_new)) #Breusch-Pagan Test, small p-value, we can assume, we have to reject H:0 bptest(lm_final) # We are testing heteroskedasticity,heteroscedasticity is the absence of homoscedasticity. coeftest(lm_final, vcov = vcovHC(lm_new,"HC1")) # Testing Multi-Collinearity imcdiag(lm_final) # Low VIF's no correlation ########## #5.- Confidence Interval (90%) # Coefficient for run_time_ratio = 4.7 to 6.01 # This means that for each increase in percentage of RTR (Efficiency), we se an increase in the delta throughput of 5.40 confint(lm_final, level = 0.90) ############################# #6.- Change in delta throughput delta_1_3 <- 15.8708 + 3.4007 - 6.9680 + 6.4173 delta_1_3 ## 7.- Production Forecast - Delta Throughput (tons) Estimation per shift for the month of May ## The estimate for change delta throughput due to change in thickness and width (from 1 to 3) is 18.72 # Creating a dataframe for each individual value of X (independent variables) new <- data.frame(thickness_1 = 996/84, thickness_2 = 1884/84,thickness_3 = 434/84,width_1 = 1242/84,width_3 = 881/84,grade_1 = 109/3314,grade_5 =121/3314,run_time_ratio = 86) ## The prediction is -14.66 tons average delta through per shift for the month of May predict(lm_final, newdata = new, interval="prediction") ## Prediction Plot delta-Throughput for Schuze's prediction (86%) pred.int <- predict(lm_final, interval = "prediction") hist(d$delta_throughput) abline(v= -14.7,col ="red") ############### ##8.- Provide 90% confidence interval for the average delta throughput for 90% interval predict(lm_new, newdata = new, interval="confidence", level = 0.9) # Boundary level between -24.79 and -4.54 #################################################################### # Appendix Statistics ### par(mfrow = c(2,2)) hist(main = "Run Time Ratio", xlab = "Run Time Ratio", d$run_time_ratio) hist(main = "MPT", xlab = "MPT", d$MPT) hist(main = "Total Strips", xlab = "Total Strips", d$Total_Strips) hist(main = "Throughput", xlab = "Throughput", d$throughput)
84fdbbf49c862a0e7d0c36fabb3c8f3f42a10858
536dca63b85c687da2d179b16d062519f6af4e9d
/PilotRetention.R
69ec68fe005406c428e9c51bb076a9b02509556e
[]
no_license
madikas/R-Client_Retention
567be9aee64707f3783b8c62b0c02900a8cc8e12
ff740348bbdd4ce2a3ac232f8ed498f8bdf6fb58
refs/heads/main
2023-01-30T04:20:15.756558
2020-12-10T18:53:38
2020-12-10T18:53:38
null
0
0
null
null
null
null
UTF-8
R
false
false
4,700
r
PilotRetention.R
library(tidyverse) library(caret) library(rpart) library(rpart.plot) library(ranger) # Data import Pilot_data <- read.csv("~/Documents/HEC/Statistical_Learning/Client Retention/train_student.csv") Realdata <-read.csv("~/Documents/HEC/Statistical_Learning/Client Retention/score_student_withID.csv") str(Pilot_data) Pilot_data$unlimited_text <- NULL Pilot_data$active <- NULL Realdata$active <- NULL Realdata$unlimited_text <- NULL #Period id into categorical variable CreateGrp <- function(period){ if (period >= 0 & period <= 12){ return('0-12') }else if(period > 12 & period <= 24){ return('12-24') }else if (period > 24 & period <= 48){ return('24-48') }else if (period > 48 & period <=60){ return('48-60') }else if (period > 60){ return('> 60') } } #Factorize the customer by period of months Pilot_data$GrpTenure = sapply(Pilot_data$period_id, CreateGrp) Pilot_data$GrpTenure = as.factor(Pilot_data$GrpTenure) Realdata$GrpTenure = sapply(Realdata$period_id, CreateGrp) Realdata$GrpTenure = as.factor(Realdata$GrpTenure) # Target variable as 0 or 1 , I tried as.numeric but it gives back 1 and 2... Pilot_data$churn_in_12 <- as.numeric(as.logical(toupper(Pilot_data$churn_in_12))) summary(Pilot_data) set.seed(123456) #Remove useless columns Pilot_data$voice_minutes <- NULL Pilot_data$time_since_overage <- NULL Pilot_data$time_since_data_overage <- NULL Pilot_data$time_since_voice_overage <- NULL Realdata$voice_minutes <- NULL Realdata$time_since_overage <- NULL Realdata$time_since_data_overage <- NULL Realdata$time_since_voice_overage <- NULL #Split trainset into train and test set index_train <- sample(1:nrow(Pilot_data), 4/5 * nrow(Pilot_data)) train_set <- Pilot_data[index_train, ] test_set <- Pilot_data[-index_train, ] summary(train_set) #Impute trainset median for phone price, time_since_technical_problems and time_since_complaints phone_price_median <- 737.54 train_set$phone_price <- ifelse(is.na(train_set$phone_price), phone_price_median, train_set$phone_price) test_set$phone_price <- ifelse(is.na(test_set$phone_price), phone_price_median, test_set$phone_price) Realdata$phone_price <- ifelse(is.na(Realdata$phone_price), phone_price_median, Realdata$phone_price) tech_problem_median <- 3 train_set$time_since_technical_problems <- ifelse(is.na(train_set$time_since_technical_problems), tech_problem_median, train_set$time_since_technical_problems) test_set$time_since_technical_problems <- ifelse(is.na(test_set$time_since_technical_problems), tech_problem_median, test_set$time_since_technical_problems) Realdata$time_since_technical_problems <- ifelse(is.na(Realdata$time_since_technical_problems), tech_problem_median, Realdata$time_since_technical_problems) complaint_median <- 3 train_set$time_since_complaints <- ifelse(is.na(train_set$time_since_complaints), complaint_median, train_set$time_since_complaints) test_set$time_since_complaints <- ifelse(is.na(test_set$time_since_complaints), complaint_median, test_set$time_since_complaints) Realdata$time_since_complaints <- ifelse(is.na(Realdata$time_since_complaints), complaint_median, Realdata$time_since_complaints) summary(train_set) summary(test_set) # random forest case_weights <- ifelse(train_set$churn_in_12 == 1 , 5 , 1) RF <- ranger(formula = churn_in_12~ .-unique_id -id -family_id -total_overage_fees, data = train_set , case.weights = case_weights , classification = TRUE , verbose = TRUE , num.trees = 300, mtry = 6 , importance = "impurity", write.forest = TRUE , probability = TRUE , min.node.size = 1000 , max.depth = 15 , splitrule = "gini", ) PredTest <- predict(RF , data = test_set, num.trees = 300 , type = "response" , verbose= T ) PredTest <- PredTest$predictions PredTest <- PredTest[,2] source("~/Documents/HEC/Statistical_Learning/Week5-PredBinaries/PredictingBinaries.R") confusion(test_set$churn_in_12,as.numeric(PredTest>0.5)) roc(test_set$churn_in_12,PredTest,col="blue")$AUC importance(RF) #Realdataset prediction for churn probability RF_Prediction <- predict(RF , data = Realdata , num.trees = 300 , type = "response" , verbose= T ) RF_Prediction <- RF_Prediction$predictions RF_Prediction<- RF_Prediction[,2] #Best cut off was 0.5023 trees = 300 Cutoff_up <- 0.51 #Result Realdata$INVITATION <- ifelse(RF_Prediction> Cutoff_up, 1, 0) Realdata$INVITATION = factor(Realdata$INVITATION) Result <- data.frame(Realdata$unique_family , Realdata$INVITATION) Index_NoChurn <- which(Result$Realdata.INVITATION==0) Churn <- Result[-Index_NoChurn,] nrow(Churn) write.csv(Churn$Realdata.unique_family , "~/Documents/HEC/Statistical_Learning/Client Retention/Result1.csv",row.names = FALSE)
e9a74b8178dadb26b535ef912343a89be4875939
c9e938b2098f8d2b4a7a1f524247523acd3327f2
/cachematrix.R
4d1dd8210d5e4d02339750b696d8d33174e8de6f
[]
no_license
cherish2019/ProgrammingAssignment2
23affb7ff7728801c049fff270278aa991c45441
6985abed3fe7b390917cec722223b1c77a38bace
refs/heads/master
2020-04-20T18:25:33.128702
2019-02-04T03:15:53
2019-02-04T03:15:53
169,021,078
0
0
null
2019-02-04T03:04:32
2019-02-04T03:04:31
null
UTF-8
R
false
false
803
r
cachematrix.R
## This function creates the invserse mayrix of the original one ## The inverse of a matrix can be extracted by function cacheSolve makeCacheMatrix <- function(x = matrix()) { inverse <- NULL set <- function(y) { x <<- y inverse <<- NULL } get <- function() x setInverse <- function(inverse) inv <<- inverse getInverse <- function() inv list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## create "matrix" that cache the inverse of the matrix cacheSolve <- function(x, ...) { inverse <- x$getInverse() if (!is.null(inverse)) { message("getting cached data") return(inverse) } mat <- x$get() inverse <- solve(mat, ...) x$setInverse(inverse) inverse ## Return a matrix that is the inverse of 'x' }
475dbab196d47bb4e8756a677d566de0a7c81d64
11b126a360963aee9042c4b94a95854b9f6e0348
/Microarray/Filtering_absent_genes_in_microarray.R
48f0eba2296699f4fca1ac0131780d01bac08911
[]
no_license
Cosmoboss/CRC-biomarkers
82ebe9fa39767a41ae1c3e2a48f99c09114a6fe7
a607c0a9144098315bb0a9d35dd50fdd8040e7dd
refs/heads/main
2023-05-24T10:38:59.429686
2021-06-09T17:02:10
2021-06-09T17:02:10
368,797,688
0
0
null
null
null
null
UTF-8
R
false
false
9,142
r
Filtering_absent_genes_in_microarray.R
#Load the libraries that will be used. library(matrixStats) #Read in the merged microarray datasets hgu133plus2 <- read.table("HGU133Plus2_after_ComBat_df.xls", sep="\t", header=T) hgu133a <- read.table("HGU133A_after_ComBat_df.xls", sep="\t", header=T) #Read in the RNA-Seq studies gse74369 <- read.table("gse74369_processed.xls", header=T) gse146009 <- read.table("gse146009_processed.xls", sep = "\t", header=T) #Remove any gene that is an NA gse74369 <- gse74369[!is.na(gse74369$external_gene_name),] gse146009 <- gse146009[!is.na(gse146009$external_gene_name),] #Identify all unique genes in RNA-Seq rna_seq_genes <- unique(c(gse74369$external_gene_name, gse146009$external_gene_name)) `%notin%` <- Negate(`%in%`) # Create a negate of %in% operator hgu133plus2_genes <- unique(hgu133plus2$Gene) #All unique genes in HGU133Plus2 hgu133a_genes <- unique(hgu133a$Gene) #All unique genes in HGU133A #Find all HGU133's genes not present in RNA-Seq genes hgu133a_specific <- hgu133a_genes[hgu133a_genes %notin% rna_seq_genes] hgu133plus2_specific <- hgu133plus2_genes[hgu133plus2_genes %notin% rna_seq_genes] #Overlap both HGU133 to find microarray specific genes microarray_specific <- hgu133a_specific[hgu133a_specific %in% hgu133plus2_specific] #find all genes specific in HGU133plus2 only hgu133plus2_specific <- hgu133plus2_specific[hgu133plus2_specific %notin% microarray_specific] #List of the Housekeeping genes HKG_genes <- c("GPI","PSMB2","PSMB4","SNRPD3","RAB7A","REEP5","VCP","CHMP2A","C1orf43","VPS29","EMC7","CSTB","GUSB","HADHA","HPRT1", "SGSH","PGK1","TCOF1","CYB5R3","GM2A","SOD1","GNAS","COMT","GUK1","IMPDH2","P4HB","POLR2A","RPL5","RPL8","RPL11","RPL19", "RPL17","RPL27","RPL32","RPL34","RPL36AL","RPS5","RPS9","RPS11","RPS13","RPS15","RPS16","RPS24","RPS25","ADAR","ADD1", "AP1B1","AES","ANXA6","ATP6AP1","BTF3","ENTPD6","GAPDH","CHD4","TBCB","CSNK2B","CTBP1","DAD1","DAXX","DDT","EIF4G2", "ENO1","FBL","EXTL3","XRCC6","BLOC1S1","GDI1","GDI2","PRMT1","HSBP1","APLP2","ARAF","ARF1","ARF4","ARF5","RHOA","ATF4", "ATP5D","ATP5G3","ATP6V0C","ATP6V1E1","ATP5O","BSG","CANX","CAPNS1","SEPT7","CENPB","CLTA","CLTB","COX4I1","COX5B", "COX6B1","COX7A2","COX7C","CTNNB1","CTSD","CYC1","E2F4","EEF2","FAU","FTH1","GAPDH","GOT2","GPX4","HMGB1","HNRNPD", "HNRNPK","ID3","JAK1","M6PR","MAP4","MAZ","MIF","MAP3K11","MPG","MTX1","NDUFA2","NDUFC1","NME2","ODC1","PRDX1","PFDN1", "PFDN5","SLC25A3","PHF1","PIM1","PPP1R10","PRKAG1","PRKCSH","PSMA7","PSMB1","PSMB7","PSMD2","PSMD3","PSMD8","PSMD11", "PSME2","PTBP1","RING1","RNH1","RPA2","RPL15","RPN1","RPS27A","SAFB","SRSF2","SGTA","SNRNP70","SNRPB","SNRPG","SRM", "SRP14","SSR2","TAPBP","TMBIM6","TSTA3","TTC1","TUFM","TXN","UBA1","UBE2D2","UBE2I","UQCRC1","YWHAB","YWHAZ","ZNF91", "HIST1H2BC","SLC25A11","STK24","YARS","EIF3D","EIF3F","EIF3G","EIF3I","BECN1","B4GALT3","SNX3","GPAA1","ADAM15","BANF1", "ARHGEF7","MCM3AP","BUD31","CPNE1","RPS6KB2","UBE2M","RPL14","ATP5A1","ATP6V0B","AP2M1","AP2S1","COX8A","NDUFB7","RAB1A", "SDHA","SREBF1","ATP6V1F","ARHGAP1","ARHGDIA","PTTG1IP","CD81","SEPT2","ENSA","ERH","HDGF","HNRNPAB","ILF2","ILK", "NDUFA1","NDUFS5","SNRPA","SNRPD2","DDX39B","PABPN1","C21orf33","MTA1","HGS","COX7A2L","MAPKAPK2","VAMP3","ATP6V1G1", "ATP5J2","SPAG7","H2AFY","C14orf2","CLOCK","ACTN4","CAPZB","FUS","NDUFA7","PFN1","RBM8A","WDR1","ABL1","ATP5G1", "BMI1","DDOST","GNB2","HINT1","HSPA5","JUND","NCL","MLF2","CFL1","HNRNPH1","KARS","LAMP1","LDHA","RPS14","SCAMP3", "ARPC4","ARPC3","TSFM","ARPC2","BCAP31","TRIM28","EIF1","SRRM1","SAP18","ACAT2","SLC25A1","VPS72","CCT3","UQCRFS1", "UQCRH","RPL10","AKR1A1","TUBA1B","HAX1","NEDD8","PIN1","DPF2","VARS","RAN","C1D","ZNHIT1","TIMM44","TADA3","ATP5H", "NXF1","CREB3","SYNCRIP","HYOU1","ANP32B","AGPAT1","RABAC1","CCT7","DRAP1","PRPF8","HEXIM1","TRIM27","SARS","RRAGA", "API5","HSPA8","TUBGCP2","JTB","NUDT3","RNPS1","TALDO1","ZFPL1","AFG3L2","KDELR1","SEC61B","TMED2","YWHAQ","UQCR11", "COPS6","CALM1","IDH3B","RAC1","SUMO3","RTN4","KAT7","ATP5I","NDUFV1","RPL10A","TCEB2","RPL35","ATXN2L","LYPLA2", "PARK7","COPE","GABARAP","GABARAPL2","ABL1","HSP90AB1","CASC3","NONO","CD3EAP","DNPEP","ARL2BP","AHSA1","CIZ1","AATF", "FBXO7","PICK1","H2AFV","RPL13A","PDCD6","EIF3K","PRRC2B","PPP2R1A","CNPY2","PUF60","SEC61G","SND1","UQCRQ","ZNF592", "MLEC","PTDSS1","IST1","EFCAB14","MFN2","PDAP1","LMTK2","TCF25","XPO7","ESYT1","CTDNEP1","BRMS1","NELFB","RAP1B","ANAPC5", "TRAP1","INPP5K","PTOV1","TMED9","OTUB1","BTBD2","COMMD4","UBB","TERF2IP","TOMM7","GSK3A","SAR1A","STARD7","SDR39U1", "UBC","NDUFV2","MRPS12","POLR2L","MRPL23","PPP1R11","MCL1","POLR2F","RELA","TUT1","CDK11A","KXD1","TMEM109","C9orf16", "MAP2K2","MRPL9","TMEM147","MYL12B","ZNF384","TEX261") #put in the microarray platform that you want to filter a1 <- hgu133plus2 #Remove any genes that are labelled as NA a1 <- a1[!is.na(a1$Gene),] #Calculate the average expression of the genes in all samples a1$AveExpr <- rowMeans(a1[,1:(length(a1)-1)]) #Add this if you're curious about the hgu133plus2 specific genes sel_3381 <- a1[a1$Gene %in% hgu133plus2_specific,] #Safe the expression levels of the microarray specific genes sel_1504 <- a1[a1$Gene %in% microarray_specific,] columns_sel <- c("Gene","AveExpr") #Save these columns for later #get the selected columns from hgu133plus2 specific genes if you're processing it sel_3381_sel <- sel_3381[,columns_sel] #Safe the gene names and average expression of the microarray specific genes sel_1504_sel <- sel_1504[,columns_sel] #Get all HKG genes from all the genes sel_hkg <- a1 [a1$Gene %in% HKG_genes,] #Safe the gene names and average expression from the HKG sel_hkg_sel <- sel_hkg[,columns_sel] #Plot the average expression of all genes hist(a1$AveExpr, col="skyblue", ylim = c(0, 2500),border=F) #All genes in microarray hist(sel_3381$AveExpr, col="gold",add=TRUE,border=F) #hgu133plus2 specific genes hist(sel_1504$AveExpr, col="red",add=TRUE,border=F) #microarray specific genes hist(sel_hkg$AveExpr, col="black",add=TRUE,border=F) #Housekeeping genes #To calculate Standard Deviation (SD) aa1 <- transform(as.matrix(a1[, 1:(length(a1)-2)]), SD=apply(as.matrix(a1[, 1:(length(a1)-2)]),1, sd, na.rm = TRUE)) A1_Sel <- a1[,columns_sel] A1_Sel$SD <- aa1$SD #Add the SD for each GENE type sel_3381_sel$SD <- A1_Sel[which(row.names(sel_3381_sel) %in% row.names(A1_Sel)),]$SD sel_1504_sel$SD <- A1_Sel[which(row.names(sel_1504_sel) %in% row.names(A1_Sel)),]$SD sel_hkg_sel$SD <- A1_Sel[which(row.names(sel_hkg_sel) %in% row.names(A1_Sel)),]$SD #Calculate the average SD and average expression to identify the cut-off AveExpr <- mean(apply(sel_1504[,1:(length(sel_1504)-2)], 1, mean)) AveSD <- mean(apply(sel_1504[,1:(length(sel_1504)-2)], 1, sd)) #Test the filtering criteria of AveExpr + SD times 1,2, or 3 #SD less than 1 FilteredGenes_V1 <- A1_Sel[which(A1_Sel$AveExpr < AveExpr + (AveSD * 1)),] SelectedGenes_V1 <- A1_Sel[- which(A1_Sel$AveExpr < AveExpr + (AveSD * 1)),] filtered_1504_V1 <- sel_1504_sel[which(row.names(sel_1504_sel) %in% row.names(FilteredGenes_V1)),] filtered_HKG_V1 <- sel_hkg_sel[which(row.names(sel_hkg_sel) %in% row.names(FilteredGenes_V1)),] print(c(dim(filtered_1504_V1), dim(filtered_HKG_V1), dim(SelectedGenes_V1), (AveExpr+AveSD*1))) #SD less than 2 FilteredGenes_V2 <- A1_Sel[which(A1_Sel$AveExpr < AveExpr + (AveSD * 2)),] SelectedGenes_V2 <- A1_Sel[- which(A1_Sel$AveExpr < AveExpr + (AveSD * 2)),] filtered_1504_V2 <- sel_1504_sel[which(row.names(sel_1504_sel) %in% row.names(FilteredGenes_V2)),] filtered_HKG_V2 <- sel_hkg_sel[which(row.names(sel_hkg_sel) %in% row.names(FilteredGenes_V2)),] print(c(dim(filtered_1504_V2), dim(filtered_HKG_V2), dim(SelectedGenes_V2), (AveExpr+AveSD*2))) #SD less than 3 FilteredGenes_V3 <- A1_Sel[which(A1_Sel$AveExpr < AveExpr + (AveSD * 3)),] SelectedGenes_V3 <- A1_Sel[- which(A1_Sel$AveExpr < AveExpr + (AveSD * 3)),] filtered_1504_V3 <- sel_1504_sel[which(row.names(sel_1504_sel) %in% row.names(FilteredGenes_V3)),] filtered_HKG_V3 <- sel_hkg_sel[which(row.names(sel_hkg_sel) %in% row.names(FilteredGenes_V3)),] print(c(dim(filtered_1504_V3), dim(filtered_HKG_V3), dim(SelectedGenes_V3), (AveExpr+AveSD*3))) #Safe the criteria where the least amount of HKG were filtered whilst filtering #as much absent/low expressed genes (SD times 1 in my case) safe_filtered <- a1[which(row.names(a1) %in% row.names(FilteredGenes_V1)),] write.table(safe_filtered, "HGU133Plus2_filtered.xls", sep="\t", quote=F) safe_selected <- a1[which(row.names(a1) %in% row.names(SelectedGenes_V1)),] write.table(safe_selected, "HGU133Plus2_after_lowExpression_filter.xls", sep="\t", quote=F)
1ae919c984adac4cccd24587a9ee9bbe5752357c
1b605394809312ea6c0a1a6d69a1a24f9cdd8982
/inst/examples/server.R
30e0f2c276012c50cfb0502ea90e8f3dfe61d3b5
[]
no_license
AparicioJohan/GS
7994604c10904927ceefe29289fbeeaec0d32ba2
d81b725ff79726f182e148732e92d997348de6c4
refs/heads/master
2021-03-30T05:58:42.203100
2020-10-07T13:54:53
2020-10-07T13:54:53
248,023,382
2
0
null
null
null
null
UTF-8
R
false
false
6,810
r
server.R
library(shiny) library(ggplot2) library(plotly) library(SpATS) library(ggsci) library(ggpubr) library(shinyjs) library(shinytoastr) library(GS) library(sommer) # source("https://raw.githubusercontent.com/AparicioJohan/GPrediction/master/crossGP.R") options(shiny.maxRequestSize = 70*1024^2) shinyServer(function(input,output,session)({ # Update variable traits -------------------------------------------------- observe({ phen <- input$file3$datapath validate(need(input$file3, "missing file 3")) phen <- read.csv(phen) updatePickerInput(session, "Id094", choices=names(phen[,-1])) }) observe({ updatePickerInput(session, "Id095", choices=input$Id094) }) # Read data and run the models -------------------------------------------- df <- eventReactive(input$action,{ geno <- input$file1$datapath samp <- input$file2$datapath phen <- input$file3$datapath if(is.null(input$file1)|is.null(input$file2)|is.null(input$file2)) toastr_error( "Missing files..." ,position = "bottom-right") validate(need(input$file1, "missing file 1")) validate(need(input$file2, "missing file 2")) validate(need(input$file3, "missing file 3")) prior <- input$checkGroup # prior[prior=="1"] <- "ASReml" validate(need(input$checkGroup, "Select one model")) validate(need(input$Id094, "Select the traits")) withCallingHandlers({ results <- crossGP(geno,samp,phen,prior,niter = input$iter, testporc = input$porcent, traits = input$Id094) }, message = function(m) { shinyjs::html("console", m$message, TRUE) } ) results }) # Output data ------------------------------------------------------------- output$Rawdata <- DT::renderDataTable({ req(nrow(df()$data)>=1) df()$data %>% DT::datatable( extensions = 'Buttons', filter = 'top', selection="multiple", options = list(dom = 'lfrtipB', scrollX = TRUE, pageLength = 10,lengthMenu = c(2, nrow(df()$data)), buttons = c('excel', "csv"))) }) # Plot correlations ------------------------------------------------------- output$plot <- renderPlot({ if (input$action==0) {return()} else { validate(need(input$file1, "missing file 1")) validate(need(input$file2, "missing file 2")) validate(need(input$file3, "missing file 3")) if(length(input$checkGroup)>=1){ g1 <- df()$data %>% ggplot(aes(x=trait,y=corr,fill=prior))+geom_boxplot()+theme_bw(base_size = 13)+ theme(axis.text.x = element_text(angle = 70,hjust = 1),legend.title = element_blank())+ ylab("Prediction Ability")+xlab("")+ scale_fill_simpsons() if(input$iter==1||input$porcent==0){ g1 <- df()$data %>% ggplot(aes(x=trait,y=corr,color=prior))+geom_point()+theme_bw(base_size = 13)+ theme(axis.text.x = element_text(angle = 70,hjust = 1),legend.title = element_blank())+ ylab("Prediction Ability")+xlab("")+ scale_fill_simpsons() } } else { g1 <- df()$data %>% ggplot(aes(x=trait,y=corr,fill=trait))+geom_boxplot()+theme_bw(base_size = 13)+ theme(axis.text.x = element_text(angle = 70,hjust = 1),legend.title = element_blank())+ ylab("Prediction Ability")+xlab("")+ scale_fill_simpsons() if(input$iter==1||input$porcent==0){ g1 <- df()$data %>% ggplot(aes(x=trait,y=corr,color=trait))+geom_point()+theme_bw(base_size = 13)+ theme(axis.text.x = element_text(angle = 70,hjust = 1),legend.title = element_blank())+ ylab("Prediction Ability")+xlab("")+ scale_fill_simpsons() } } isolate(g1) } }) # Marker information ------------------------------------------------------ output$mark <- renderPlot({ if (input$action==0) {return()} else { validate(need(input$file1, "missing file 1")) validate(need(input$file2, "missing file 2")) validate(need(input$file3, "missing file 3")) req(input$Id095) validate(need(input$porcent==0, "Percentage of test population should be zero")) validate(need(input$method%in%input$checkGroup, paste(input$method, "is not include in the fitted models"))) out_table <- df() bHat <- out_table$models[[input$Id095,input$method]]$ETA[[1]]$b MarK <- data.frame(Marker=1:length(bHat),bHat = bHat^2) g1 <- MarK %>% ggplot(aes(x=Marker, y=bHat)) + geom_point(size=1.5,color="black") + geom_segment(aes(x=Marker, xend=Marker, y=0, yend=bHat), color="red") + labs(title="Marker Effects", subtitle=paste(input$method, "model",sep = " "), caption="generated by: Mr.Gen", y= 'Estimated Squared-Marker Effect') + theme(axis.text.x = element_text(angle=65, vjust=0.6))+theme_bw(base_size = 15) isolate(g1) } }) output$pred <- renderPlot({ if (input$action==0) {return()} else { validate(need(input$file1, "missing file 1")) validate(need(input$file2, "missing file 2")) validate(need(input$file3, "missing file 3")) req(input$Id095) validate(need(input$porcent==0, " ")) req(input$method%in%input$checkGroup) out_table <- df() bHat <- out_table$models[[input$Id095,input$method]]$ETA[[1]]$b MarK <- data.frame(Marker=1:length(bHat),bHat = bHat^2) Pred <- data.frame( yHat=out_table$models[[input$Id095,input$method]]$yHat, y=out_table$models[[input$Id095,input$method]]$y) g1 <- Pred %>% ggplot(aes(x=yHat,y=y)) +geom_point(alpha=0.2,size=3)+ geom_abline(slope = 1,intercept = 0,linetype=2, color="red",size=1)+ geom_smooth(method = "lm",formula = y~x, se = F)+ labs(y="Phenotype",x='Predicted genomic value', title="Predicted genomic values vs phenotypes")+ stat_cor()+theme_bw(base_size = 15) isolate(g1) } }) # update number iterations ------------------------------------------------ observe({ if (input$porcent != 0) { shinyjs::show("nonIter",animType = "fade",anim = TRUE) # enable("nonIter") } else { shinyjs::hide("nonIter",animType = "fade",anim = TRUE) # disable("nonIter") toastr_info("Percentage of test population equal to zero: Only one iteration selected",position = "bottom-right") } }) observeEvent(input$run,{ toastr_info(paste(input$Id094,collapse = " ")) }) }))
c600bea64280bcbe8eabc2ef721ffc0774a25aeb
07cbeb7cffaa00d21734c486c793e4ed4fe698db
/plot1.R
078e0038dd7fda725b8f75a8b52d88d2c289fd51
[]
no_license
ssuresh8/ExData_Plotting1
0897bd40a96cb1769c270a640e196496fa28f558
376b0d95156015f90de680d346d831aac8a8233a
refs/heads/master
2020-05-29T11:45:56.200047
2015-12-13T22:19:51
2015-12-13T22:19:51
47,864,087
0
0
null
2015-12-12T04:25:19
2015-12-12T04:25:19
null
UTF-8
R
false
false
893
r
plot1.R
## read in the text file ## since it is a semicolon delimited file use sep as semi colon and headings are in first row dat <- read.table("household_power_consumption.txt", header = T, sep= ";") #convert the date and time columns in to the date and time classes in R dat$Date <-as.Date(dat$Date, format = "%d/%m/%Y") ##index the data frame for the required dates of 2007-02-01 and 2007-02-02 dat2 <- dat[(dat$Date=="2007-2-1" | dat$Date=="2007-2-2" ), ] ##convert global active power column to numeric dat2$Global_active_power <- as.numeric(as.character(dat2$Global_active_power)) #send the plot to PNG png('plot1.png', width=480, height=480) ##plot the histogram #Title:Global Active Power #x-ais Global Activer Power (kilowatts) # column color red hist(dat2$Global_active_power,main = "Global Active Power", xlab = "Global Active Power (kilowatts)",col ='red') ##complete plot dev.off()
912bf5673e5d3c7f162f0ab57a5c7bf080e84c44
c3ab6a0f29d068ff5f25dae32cbcefea14645fef
/man/JustATestPlot.Rd
6e552c12fb05dda8893291d3276abcebd23aeef7
[]
no_license
1587causalai/gong-pkg
acac9de28c0e81bce531dc79591a03a8a108616d
fe53d136b828170ee0d4d6cb0c8dbb4da5bcfae8
refs/heads/master
2023-02-06T20:01:21.233805
2017-10-06T01:13:03
2017-10-06T01:13:03
null
0
0
null
null
null
null
UTF-8
R
false
true
240
rd
JustATestPlot.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hello.R \name{JustATestPlot} \alias{JustATestPlot} \title{A function for plot a picture with ggplot2} \usage{ JustATestPlot() } \description{ This function ... }
d4df0c02fe5c70be41a473769041135260cfb3c2
2bce49ab57997fe6121efcfba8544e8ede5f6376
/tests/testthat.R
afcde10bc7bf8d5b6654f8246735af8035ef102c
[]
no_license
hfjn/nmmso_benchmark
7e0309244529226f1ab2b0bd7091772392ceba38
bf13085ce7ce6d597c45095d30d2e0909467eb56
refs/heads/master
2021-05-30T02:31:26.276871
2016-01-09T16:24:01
2016-01-09T16:24:01
null
0
0
null
null
null
null
UTF-8
R
false
false
72
r
testthat.R
library(testthat) library(nmmsoBenchmark) test_check("nmmsoBenchmark")
542666acf64a00a63a4e8c505be066d56c4730af
8d2fab7f71a20ebbc5d9de832cf16a62ba6ca0b4
/src/SEER_Summary.R
b8cacdd2eda7603a12c0b6199bf6be2305c7b14f
[ "MIT" ]
permissive
phildwalker/local_cancer_prev_MrP
e89986afa4059f71d449b705cc706e41b6bf4d10
a269935cc001fdeda71e5f71821b7af574ee17c4
refs/heads/main
2023-03-09T05:59:51.330416
2021-02-18T16:20:27
2021-02-18T16:20:27
338,878,514
0
0
null
null
null
null
UTF-8
R
false
false
1,235
r
SEER_Summary.R
# https://seer.cancer.gov/explorer/application.html?site=55&data_type=1&graph_type=3&compareBy=race&chk_race_1=1&chk_race_5=5&chk_race_4=4&chk_race_3=3&chk_race_6=6&chk_race_8=8&chk_race_2=2&sex=3&rate_type=2&advopt_precision=1&advopt_display=2 SEER <- readxl::read_excel(here::here("data-raw", "Summary_Cancer_Age_Rates.xlsx"), sheet = "All_Cancer") %>% pivot_longer(cols = 3:9, names_to = "Races", values_to = "RatePer") %>% left_join(., readxl::read_excel(here::here("data-raw", "Summary_Cancer_Age_Rates.xlsx"), sheet = "lookup"), by = c("Races" = "ColName")) SEER_All_Long <- SEER %>% filter(Short == "All_Race") %>% mutate(RatePer = ifelse(is.na(RatePer), 0,RatePer)) %>% group_by(AgeGroup, Short) %>% summarise(RateAvg = mean(RatePer)) %>% ungroup() %>% mutate(NonCan = 100000-RateAvg) %>% pivot_longer(cols = 3:4, names_to = "CancerFlag", values_to = "EstIncid") %>% mutate(CancerFlag = ifelse(CancerFlag == "RateAvg", 1,0), EstCount = round(EstIncid)) %>% uncount(weights = EstCount) library(lme4) fit <- glmer(CancerFlag ~ 1 + (1|AgeGroup) , data = SEER_All_Long, family = binomial) summary(fit) save(fit, file = here::here("data", "fit.rda"))
81c291d37aed3f7dafc2323d609051c042f5461d
b5555aca84eba3fdad763c8922e5b856718ff1d9
/Image Restoration.R
2640c9c5db3f3accbc0753edd7b8ee60ae06dbb9
[]
no_license
resobyte/ImageRestorationR
242edbac317133e1846fa1f5cf0acef320811335
31d89048e368431dc2ca10352457c7b6c1682c65
refs/heads/master
2020-03-18T14:36:29.973462
2018-05-25T13:29:45
2018-05-25T13:29:45
134,856,833
0
0
null
null
null
null
UTF-8
R
false
false
1,716
r
Image Restoration.R
temp <- (matrix(1,nrow=3,ncol=3) %x% matrix(c(2,1,1,2),2))[1:5,1:5] M1 <- temp %x% matrix(1,nrow=10,ncol=10) M2 <- matrix(2,nrow=50, ncol=50) M2[21:30,1:10] <- M2[21:30,41:50] <- 1 M2[11:40,11:20] <- M2[11:40,31:40] <- 1 M2[1:50,21:30] <- 1 M3 <- matrix(2,nrow=50, ncol=50) M3[11:20,] <- M3[31:40,] <- 1 M3[1:10,21:30] <- M3[41:50,21:30] <- 1 M4 <- 3 - M2 X.ori <- cbind(rbind(M1,M4),rbind(M2,M3)) image(X.ori, axes=FALSE, frame.plot=FALSE, col = grey(c(0, 0.8))) p <- 0.2 set.seed(12345) N <- dim(X.ori)[1] Y <- X.ori Y1 <- Y[2:(N-1),2:(N-1)] i1 <- which(runif(((N-2)^2)) < p) Y1[i1] <- 3-Y1[i1] Y[2:(N-1),2:(N-1)] <- Y1 image(Y, axes=FALSE, frame.plot=FALSE, col=grey(c(0, 0.8))) alpha <- 0.03 beta <- 1 nmcmc <- 50 N <- 100 set.seed(12345) X <- matrix(runif(N^2)<0.5,N)+1 for (k in (1:nmcmc)) { for (i in sample(2:(N-1))) { for (j in sample(2:(N-1))) { Vij <- c(X[i-1,j], X[i+1,j], X[i,j-1], X[i,j+1]) u1 <- beta*sum(Vij!=1) + alpha u2 <- beta*sum(Vij!=2) p1 <- 1/(1+exp(-u2+u1)) r <- runif(1) if (r < p1) X[i,j] <- 1 else X[i,j] <- 2 } } } image(X, axes=FALSE, frame.plot=FALSE, col = grey(c(0, 0.8))) alpha <- 0 beta <- 1.5 lambda <- log((1-p)/p) nmcmc <- 50 set.seed(12345) X <- Y for (k in (1:nmcmc)) { for (i in sample(2:(N-1))) { for (j in sample(2:(N-1))) { Vij <- c(X[i-1,j], X[i+1,j], X[i,j-1], X[i,j+1]) u1 <- beta*sum(Vij!=1) + alpha + lambda*(Y[i,j]!=1) u2 <- beta*sum(Vij!=2) + lambda*(Y[i,j]!=2) p1 <- 1/(1+exp(-u2+u1)) r <- runif(1) if (r < p1) X[i,j] <- 1 else X[i,j] <- 2 } } } image(X, axes=FALSE, frame.plot=FALSE, col = grey(c(0, 0.8)))
ea927be4e0ecff9bd5bd1dadb6562a72e82238d8
655f8fe46c2c6143cf3889df5d3191f07ce09563
/man/hngm.Rd
26aac35299c4a8086378ddb7da638b1a7770241b
[]
no_license
jongguri80/NGM
374b9909e9094ad84f14fcc9e407a1414fa9a418
192b4543d641ef0d58158d52b06cfe9e9441aa97
refs/heads/master
2020-06-24T23:13:12.783303
2017-07-12T00:59:03
2017-07-12T00:59:03
96,938,916
0
0
null
null
null
null
UTF-8
R
false
false
2,445
rd
hngm.Rd
\name{SSVM_OU} \alias{SSVM_OU} \docType{package} \title{ Bayesian Semi-parametric Stochastic Model with Ornstein-Uhlenbeck process prior (B-SSVM-OU) } \description{ To fit B-SSVM-OU with longitudial data to examine the association between growth acceleration and an exposure. } \usage{ SSVM_OU(Y_list, X_logrho, X_nu_bar, del_list, mu0, C0, smooth_fix = FALSE, lambda = 1, int_list = list(sigma2_eps = 0.5, sigma2_xi = 0.1, rho = rep(5, N), nu_bar = rep(-0.5, N), sigma2_logrho = .1, sigma2_nu_bar = .1), prior_list = list(a_eps = .001, b_eps = .001, eps_lb = 0, eps_ub = 10, a_xi = .1, b_xi = .1, xi_lb = 0, xi_ub = 200, a0 = .01, b0 = .01), n_iter = 1500, burn_in=500, thin=1, per_print=500) } \examples{ \dontrun{ data(sparse_dat) ## visit for each subject J_i = 8 ## ## same for data(moderate_dat): visit for each subject J_i = 30 ## head(sparse_dat) dat = dat_list(indata=sparse_dat, subj_id="subj", time_var="year", Y_var="Y") del_list = dat$del_list Y_list = dat$Y_list N = length(Y_list) X_dat = unique(data.frame(subj=sparse_dat$subj, X=sparse_dat$X)) X_logrho = model.matrix(~ X, data=X_dat) X_nu_bar = model.matrix(~ 1, data=X_dat) #################################### MCMC simulation ##################################### n_iter = 2500; burn_in = 500; thin=1; per_print=500 ## prior for initial distribution of trajectory and velocity (should be set as a list format) mu0 = C0 = as.list(NULL) for(i in 1:N){ mu0[[i]] = c(13.1, 31) # c(m01, m02), where m01 and m02 are prior means, respectively, for trajectory and velocity at the initial time. C0[[i]] = diag(c(10, 20)) # c(c01, c02), where m01 and m02 are prior variances, respectively, for trajectory and velocity at the initial time. } ## initial values for MCMC iterations. int_list = list(sigma2_eps = 0.5, sigma2_xi = 0.5, rho = rep(5, N), nu_bar = rep(-0.5, N), sigma2_logrho = .1, sigma2_nu_bar = .1) ## values for hyper-parameters. ## sigma2_eps ~ IG(a_eps, b_eps)I(eps_lb, eps_ub) ## sigma2_xi ~ IG(a_xi, b_xi)I(xi_lb, xi_ub) ## sigma2_logrho, sigma2_gamma ~ IG(a0, b0)I(0, inf). prior_list = list(a_eps = .01, b_eps = .01, eps_lb = 0, eps_ub = 10000, a_xi = .1, b_xi = .1, xi_lb = 0, xi_ub = 10000, a0 = .01, b0 = .01) SSVM = SSVM_OU(Y_list, X_logrho, X_nu_bar, del_list, mu0=mu0, C0=C0, prior_list = prior_list, int_list = int_list, n_iter = n_iter, burn_in=burn_in, thin=thin, per_print=per_print) } }
ba1fd6f304090a80d20a52e49abbd805cf0d2d7d
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/circlize/examples/circos.yaxis.rd.R
e7066f961af84f02c08ebf3e671d1103fbb1ec3d
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
561
r
circos.yaxis.rd.R
library(circlize) ### Name: circos.yaxis ### Title: Draw y-axis ### Aliases: circos.yaxis ### ** Examples op = par(no.readonly = TRUE) factors = letters[1:8] circos.par(points.overflow.warning = FALSE) circos.par(gap.degree = 8) circos.initialize(factors = factors, xlim = c(0, 10)) circos.trackPlotRegion(factors = factors, ylim = c(0, 10), track.height = 0.5) par(cex = 0.8) for(a in letters[2:4]) { circos.yaxis(side = "left", sector.index = a) } for(a in letters[5:7]) { circos.yaxis(side = "right", sector.index = a) } circos.clear() par(op)
450765baf45213b58f8bdfed371bdf28bfd52500
ce2bed3a57df5f6c25141b017bac624f3915ac7e
/week 2/week 2 programming assessment.R
3809f4cf405e07d61061470027686f73fc24d5de
[]
no_license
Doublefacez/datasciencecoursera
e0b72d40dc0d0e245d4f85e2b411b29716d4f64f
e9d1b9ecf28fabbe1e5ed5c76ba3439fea9ad4d9
refs/heads/master
2022-11-12T10:43:22.984794
2020-06-23T16:53:35
2020-06-23T16:53:35
271,297,858
0
0
null
null
null
null
UTF-8
R
false
false
3,233
r
week 2 programming assessment.R
####################### Week 2 Programming Assignmane ##################### ## Part 1 Write a function "pollutantmean" to calculate the mean pollutantmean <- function(directory, pollutant, id = 1:332){ locate_files <- list.files(directory, full.names = TRUE) #Locating the files in the directoroy data <- data.frame() #Creating an empty data frame for storing the values for (i in id) { data <- rbind(data, read.csv(locate_files[i])) #subseting the data in all files and put it into the data frame } mean <- mean(data[, pollutant], na.rm = TRUE) #calculating the mean of the pollutant return(mean) } pollutantmean("specdata","sulfate", 1:10) pollutantmean("specdata", "nitrate", 70:72) pollutantmean("specdata", "sulfate", 34) pollutantmean("specdata", "nitrate") ####Part 2 Write a function that reads a directory full of files ####and reports the number of completely observed cases in each data file. complete <- function(directory, id= 1:332){ locate_files <- list.files(directory, full.names = TRUE) data <- data.frame() for(i in id){ read_each_file <- read.csv(locate_files[i]) #Read the specified files nobs <- sum(complete.cases(read_each_file)) #calculate the total number of complete rows in each file store_data <- data.frame(i, nobs) #Store the file name and the values into a data frame data <- rbind(data, store_data) } colnames(data) <- c("id", "nobs") #provide a names to each column in the data frame return(data) } complete("specdata", 1:32) #Question 5 cc <- complete("specdata", c(6, 10, 20, 34, 100, 200, 310)) print(cc$nobs) #Questopm 6 cc <- complete("specdata", 54) print(cc$nobs) #Question 7 RNGversion("3.5.1") set.seed(42) cc <- complete("specdata", 332:1) use <- sample(332, 10) print(cc[use, "nobs"]) #### Part 3 Write a function that takes a directory of data files #and a threshold for complete cases and calculates the correlation #between sulfate and nitrate for monitor locations where the #number of completely observed cases (on all variables) is greater #than the threshold. corr <- function(directory, threshold = 0){ files <- list.files(directory, full.names = TRUE) correlation <- c() id <- 1:332 for (i in id){ data_each_file <- read.csv(files[i]) cvalue <- if(sum(complete.cases(data_each_file))> threshold){ cor(data_each_file$sulfate, data_each_file$nitrate, use ="pairwise.complete.obs") } correlation <- c(correlation, cvalue) } return(correlation) } cr <- corr("specdata", 150) head(cr) #Question 8 cr <- corr("specdata") cr <- sort(cr) RNGversion("3.5.1") set.seed(868) out <- round(cr[sample(length(cr), 5)], 4) print(out) #Question 9 cr <- corr("specdata", 129) cr <- sort(cr) n <- length(cr) RNGversion("3.5.1") set.seed(197) out <- c(n, round(cr[sample(n, 5)], 4)) print(out) #Question 10 cr <- corr("specdata", 2000) n <- length(cr) cr <- corr("specdata", 1000) cr <- sort(cr) print(c(n, round(cr, 4)))
020b61b8d8ba5e56260d430c5007354289c5362d
55d7f8bf639aa3f5b00597acb4017021d7f9ed1e
/tests/testthat.R
e8427cba2a0bfa7511ba2c09c7b66fbf8607a0e1
[ "MIT" ]
permissive
nemochina2008/mgcvtools
b6b131fb6fba0c1ea5535930a6e2730c4d068747
3bc04bda15065ea6d4d6a6c632bb88cbdd998b34
refs/heads/master
2021-06-14T07:24:45.465596
2016-12-22T09:40:26
2016-12-22T09:40:26
null
0
0
null
null
null
null
UTF-8
R
false
false
62
r
testthat.R
library(testthat) library(mgcvtools) test_check("mgcvtools")
8126ef880101c365f43b53e0cfc2da75075972de
b2f46956d55e81c4abe581d90b059675678b611a
/Clustering.r
1f0ec08662b8dfa8633bd63c981931085281588e
[]
no_license
cosmoschen94/BigHero
568a4063633d7f52edf50953532f59dc60fa1034
db54ffe1b7771ae89f07435dba6cf77f384b7729
refs/heads/master
2021-01-10T13:18:23.218299
2016-12-08T17:32:57
2016-12-08T17:32:57
46,522,924
0
0
null
null
null
null
UTF-8
R
false
false
1,791
r
Clustering.r
library("rjson") library(fpc) library(cluster) library("party") json_file <- "data.json" json_data <- fromJSON(file=json_file) nrow <- length(json_data) ncol <- length(json_data[[1]]) data_attribute <- names(json_data[[1]]) data_mat <- matrix(data = unlist(json_data), nrow = nrow, ncol = ncol, byrow = TRUE) colnames(data_mat) <- data_attribute data_frame <- data.frame(data_mat) data_frame_no_price <- data_frame data_frame_no_price$Rent.Price <- NULL #visualize pie(table(data_frame$Number.of.Bedrooms)) pie(table(data_frame$Rent.Price)) #dbscan ds <- dbscan(data_frame_no_price, eps = 0.5, MinPts = 2) plot(ds, data_frame) plotcluster(data_frame_no_price, ds$cluster) #k-mean set.seed(8953) (kmeans.result <- kmeans(data_frame,2)) plot(data_frame[c("Latitude", "Longitude","Number.of.Bedrooms","Rent.Price")], col = kmeans.result$cluster) #pam, k = 2 pam.result <- pam(data_frame,2) plot(pam.result) #pam, k = 3 pam.result <- pam(data_frame,3) plot(pam.result) #pam, k = 4 pam.result <- pam(data_frame,4) plot(pam.result) #pam, k = 5 pam.result <- pam(data_frame,5) plot(pam.result) cluster_result <- pam(data_frame,2)$clustering data_frame$Cluster <- cluster_result data_frame_no_price$Cluster <- cluster_result cluster1_mean<-mean(data_frame$Rent.Price[data_frame$Cluster == 1]) cluster2_mean<-mean(data_frame$Rent.Price[data_frame$Cluster == 2]) cluster1_min<-min(data_frame$Rent.Price[data_frame$Cluster == 1]) cluster2_min<-min(data_frame$Rent.Price[data_frame$Cluster == 2]) cluster1_max<-max(data_frame$Rent.Price[data_frame$Cluster == 1]) cluster2_max<-max(data_frame$Rent.Price[data_frame$Cluster == 2]) #decision tree my_ctree <- ctree(Cluster ~ Number.of.Bedrooms + Latitude + Longitude, data=data_frame_no_price) print(my_ctree) plot(my_ctree, type="simple")
885536b9415e8053828e2c2db859a763d842e487
57d9c9c9603f66cfadbaf99c62366d0bf02cadc5
/man/runCubeShiny.Rd
79a977e8ac456a25433f56913f5a16e31e5dcd2c
[]
no_license
jlwaddell/soloDrafting
ad5393afd14d3089aa9f1b8fd80f983da141f3fc
472316034854ec691a1d1234d789801aab49ae46
refs/heads/main
2023-04-05T15:59:02.920252
2021-04-18T13:20:19
2021-04-18T13:20:19
346,645,939
0
0
null
null
null
null
UTF-8
R
false
true
527
rd
runCubeShiny.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/runCubeShiny.R \name{runCubeShiny} \alias{runCubeShiny} \title{Run the shiny application} \usage{ runCubeShiny(installDependencies = FALSE, ...) } \arguments{ \item{installDependencies}{boolean, whether to first install packages listed in the Suggests field of DESCRIPTION; default value is FALSE} \item{...}{further arguments that can be passed to \code{\link[shiny]{runApp}}} } \value{ no return value } \description{ Run the shiny application }
241e47ad1c6e1040ec004c18e7749d6755419993
f0ba683353c4e3faf242e56c84defda4972686e1
/man/pmid2doi.Rd
90d9db92512d92191215d82c71504b44d3126d38
[ "MIT" ]
permissive
epongpipat/eepR
bf567c666eef0417b0dece4088ec95697f02cdba
970c4699db1e005cabd282e903706239033c7b02
refs/heads/main
2023-04-01T22:44:23.247733
2023-03-28T17:42:07
2023-03-28T17:42:07
205,262,495
1
0
null
null
null
null
UTF-8
R
false
true
258
rd
pmid2doi.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/pmid2funcs.R \name{pmid2doi} \alias{pmid2doi} \title{pmid2doi} \usage{ pmid2doi(pmid) } \arguments{ \item{pmid}{} } \value{ } \description{ pmid2doi } \concept{references_pubmed}
fafada14acf96875e037a1216d1fb8899e405265
d7beab3a9f1aeaa2db5978582f7ae4c3d3f265d7
/STORING_USER_EDUCATION.R
5605ef2db25ae7c3b1334b4351dc439c1ea76cbb
[]
no_license
raunaqrameshporwal/Facebook-Influencer-Identification
6f22e0ca2e0592888338bda539dc981d7f09d2c9
44e3f8d188cfb77ce6a4c5700bd88303dc025291
refs/heads/master
2022-11-09T04:40:54.483055
2020-07-02T23:40:34
2020-07-02T23:40:34
276,765,312
0
0
null
null
null
null
UTF-8
R
false
false
1,438
r
STORING_USER_EDUCATION.R
library(RMySQL) library(magrittr) library(httr) library(jsonlite) library(RCurl) library(Rfacebook) load("my_db_connection") load("FB_ID_FILE") load("fb_oauth_auto") load("fb_oauth_manual") options(stringsAsFactors = FALSE) #EDUCATION TABLE IS CREATED WITH THE NAME -> education_details #IN CASE OF " ' EXTRACT CODE FROM extra_education.r #FORMING HTTP QUERY q1 <- "https://graph.facebook.com/v2.12/" q2 <- "?fields=education%2Cname&access_token=" httpquery <- paste(q1,fb_user_id,q2,fb_oauth_manual,sep = "") #CALLINT THE API result <- GET(httpquery) %>% stop_for_status() #PARSING THE ABOVE API's REPLY parsed_content <- parse_content(result) names(parsed_content$education$school$name) parsed_content$education$school$name[2] #CONVERTING THE PARSED CONTENT INTO DATA FRAME #df <- as.data.frame(parsed_content) #FORMING AN INSERT FUNCTION insert_education <- function (df) { q1 <- "INSERT INTO education_details VALUES(" q2 <-paste(q1,df$id,",","'",df$name,"',",sep = "") i<-1 while(i<=3) { if(i<3) { temp <-paste("'",df$education$type[i],"','",df$education$school$name[i],"',",sep = "") q2 <- paste(q2,temp,sep = "") } if(i==3) { temp <-paste("'",df$education$type[i],"','",df$education$school$name[i],"')",sep = "") q2 <- paste(q2,temp,sep = "") } i <-i+1 } dbSendQuery(mydb,q2) } #Calling the above function insert_education(parsed_content)
1e609c2063e3dd3b03401668ce7de759a601dd7a
1fd484b29193d33a9ecffb964540b9fe2dbcb134
/server.R
5393c8de1ecff9565da4f164bc236aae9ad11aba
[]
no_license
alanct/shiny
5d976d67574ea02ba4f04bd156a7c01e8eecfd39
cd8ec6d167d0b51302e8c77cd6761b5e24bad687
refs/heads/master
2020-05-10T00:20:17.379141
2014-09-20T02:21:03
2014-09-20T02:21:03
null
0
0
null
null
null
null
UTF-8
R
false
false
1,246
r
server.R
library(shiny) library(kernlab); data(spam) library(MASS) mydata <- spam attach(mydata) type <- factor(type, labels = c("spam", "not spam")) shinyServer(function(input, output) { formulaText <- reactive({ paste(input$variable, "~ type") }) formulaTextPoint <- reactive({ paste("type ~", "as.integer(", input$variable, ")") }) formulaTextPoint1 <- reactive({ paste("fit()$fitted ~", "as.integer(", input$variable, ")") }) fit <- reactive({ glm(as.formula(formulaTextPoint()), family=binomial(logit), data=mydata) # fit = glm(type ~ make, family=binomial(logit), data=mydata) }) output$caption <- renderText({ formulaText() }) output$typeBoxPlot <- renderPlot({ boxplot(as.formula(formulaText()), data = mydata, outline = input$outliers) }) output$fit <- renderPrint({ summary(fit()) }) output$typePlot <- renderPlot({ with(mydata, { #plot(input$variable, fit()$fitted, type="l", col="red") # plot(as.integer(input$variable), fit()$fitted, type="l", col="red") plot(as.formula(formulaTextPoint1())) #abline(fit(), col=2) title(main="Spam Data with Fitted Logistic Regression Line") }) }) })
6005104be7799dc343f5514ec161f73b25f133ac
e2b1baef26e62a7de8ff2b916fe2afd737f1b378
/scripts/machine_learning_algorithms/knn.R
3312ed166015abe88a943c7f6b7f89388101f41a
[]
no_license
MuhammadYasirAliKhan786/SDMGISR
9ecb7ae1996c7714d27295fbbc172b871168a6db
03087bee61a7da470895a89eb8181cc9f2c8af11
refs/heads/master
2022-01-15T14:26:28.400240
2019-07-14T22:10:45
2019-07-14T22:10:45
null
0
0
null
null
null
null
UTF-8
R
false
false
1,310
r
knn.R
####################################################################### ############### kNN head(pa) set.seed(1) #pseudo-repeatability trainIndex = createDataPartition(pa$pb, p = .75, list = FALSE, times = 1) #y as basis of splitting training = pa[ trainIndex,] #75% data for model training testing= pa[-trainIndex,] #25% for model testing set.seed(825) pb=as.factor(training$pb) #1 stands for presence and 0 for absence land=as.factor(training$land) #land use categories are categorical ## caret # define training control--> 10fold cv train_control = trainControl(method="cv", number=10) mod_fit=train(pb~.,data=training,trControl=train_control,method="knn") summary(mod_fit) ## importance of the different predictors varImp(mod_fit) ## test the model p1=predict(mod_fit, newdata=testing) #predict on the test data #test model fit-auc library(pROC) roc.glmModel = pROC::roc(testing[,"pb"], p1) #compare testing data #with predicted responses auc= pROC::auc(roc.glmModel) auc plot(roc.glmModel) text(0.5,0.5,paste("AUC = ",format(auc, digits=5, scientific=FALSE))) p1 = predict(stck, mod_fit) #use predict to implement the MARS model stored #in mod_fit on the raster stack of our predictors plot(p1,main="kNN Predictive Map")
4245a3a4e2b55c9c0222b9e91d66d1f3016bd4e5
05407980f99cf6f828ce411e728c3a140093b970
/beaver(july19).R
e76e6839c0459dd69cfe36ec4d29edf04781b3a7
[]
no_license
BeliveINkevin/R-project-July-19-
4edcb47e16f54093218942d7d9ba73f460251e62
b4cbdf6c8050651fd92f5c6b0da234e5261e9eb6
refs/heads/master
2020-03-23T13:59:43.323407
2018-07-20T01:45:00
2018-07-20T01:45:00
141,649,456
0
0
null
null
null
null
UTF-8
R
false
false
1,175
r
beaver(july19).R
library(readr) beaver <- read_csv("C:/Documents/My Excel/beaver.csv") View(beaver) install.packages("dplyr") install.packages("ggplot2") library(dplyr) library(ggplot2) head(beaver) tail(beaver) nrow(beaver) #Note that 307 corresponds to day 1 while 308 corresponds to day 2 day1<-dplyr::filter(beaver,day=='307') day1day2<-dplyr::filter(beaver,day=='308') #this code filters out the bevers that were and weren't active. Since all beavers in day 2 were active #then it's not necessary to write any code day1active<-dplyr::filter(day1,activ=='1') day1NOTactive<-dplyr::filter(day1,activ=='0') summary(day1) summary(day2) summary(day1active) summary(day1NOTactive) var(day1active$temp) var(day1NOTctive$temp) var(day2$temp) f<-ggplot(data=day1active,aes(time,temp)) f+geom_point()+ggtitle("Temperature vs time for day1 active ") g<-ggplot(data=day1NOTactive,aes(time,temp)) g+geom_point()+ggtitle("Temperature vs time for day1 inactive ") h<-ggplot(data=day2,aes(time,temp)) h+geom_point()+ggtitle("Temperature vs time for day2 active ") i<-ggplot(data=day1,aes(time,temp)) i+geom_point()+ggtitle("Temperature vs time for day1 all ")
775af18cd5b85c67ad601b2f4ced17bb037bb8c1
468d9f58ec5449bb5db4decdb757c406a295a081
/MyWork/plot4.R
73b62a99703e7d49388cb7826d36cdef05298b6c
[]
no_license
JamesZDonline/ExData_Plotting1
f07b0325404199b874218043daa13be604fec6b1
08b0d8e1061d8f18d3acf73cb022f7cabe3ea6bf
refs/heads/master
2021-01-14T11:25:11.698262
2015-01-11T00:52:54
2015-01-11T00:52:54
29,076,238
0
0
null
2015-01-11T00:26:02
2015-01-11T00:26:01
null
UTF-8
R
false
false
1,918
r
plot4.R
#Exploratory Data Analysis First Project Plot 4 R Script #Download Data and unzip file URLname<-"https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" download.file(URLname,"PowerConsumptionData.zip",method="curl") unzip("PowerConsumptionData.zip") #Read Data in filename="household_power_consumption.txt" data<-read.delim(filename,header=TRUE,sep=";",na.strings="?") #Combine Date and time into a single POSIXct column and save it in DateTime #Also Put Dates and Times in Date and time classes data$DateTime<-as.POSIXct(paste(data$Date,data$Time,sep=" "), format="%d/%m/%Y %H:%M:%S") data$Date<-as.Date(data$Date, format="%d/%m/%Y") data$Time<-strptime(data$Time, format="%H:%M:%S") #Subset data to first two days in February of 2007 ourData<-data[data$Date==as.Date("2007/02/01")|data$Date==as.Date("2007/02/02"),] #Create png device png(filename="plot1.png",width=480, height=480,units="px") # Plotting ---------------------------------------------------------------- #create four places to put graphs par(mfrow=c(2,2)) #Plot the first graph against global power plot(ourData$DateTime, ourData$Global_active_power,type="l", xlab="", ylab="Global Active Power") #Plot the second graph agains voltage plot(ourData$DateTime, ourData$Voltage,type="l", ylab="Voltage",xlab="datetime") #Plot the third with all of the submetering as in plot3.R plot(ourData$DateTime, ourData$Sub_metering_1,type="l", xlab="", ylab="Energy sub metering") lines(ourData$DateTime,ourData$Sub_metering_2,col="red") lines(ourData$DateTime,ourData$Sub_metering_3,col="blue") legendText<-c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3") legend(x="topright",legend=legendText, col=c("black","red","blue"),lty=1) #Plot the final against reactive power plot(ourData$DateTime, ourData$Global_reactive_power,type="l", ylab="Global_reactive_power",xlab="datetime") #Close png device dev.off()
5a669fbbf53702e09377f10133c405bd85514689
449714efa83eb3071200b90bd5d584e0e3e5103f
/cachematrix.R
cbc9599621ba4c6cac8d10690cab433f9c5ed0d8
[]
no_license
LindaS321/ProgrammingAssignment2
237977455fb188e5b3d898ad05660dd0a55b2a1f
f56590f71d9ea8ab82e1a90b10e2a8c340ab1b6a
refs/heads/master
2021-01-15T21:07:56.739556
2015-03-20T23:15:19
2015-03-20T23:15:19
32,351,537
0
0
null
2015-03-16T20:37:25
2015-03-16T20:37:23
null
UTF-8
R
false
false
1,783
r
cachematrix.R
## A pair of functions that cache the inverse of a matrix ## ## creates a special "matrix" object that can cache its inverse makeCacheMatrix <- function(x = matrix()) { inv = NULL ## Set the value of the matrix to value passed as y setMatrix = function(y) { ## use `<<-` to assign a value to an object in an environment ## different from the current environment. (create a cache) ## Set the value of the matrix to value passed as y x <<- y ## set the variable that holds the inverse to NULL inv <<- NULL } getMatrix <- function() x ## save the inverse of the matrix to inv setInverse <- function(solve) inv <<- solve ## retrieve the inverse of the matrix getInverse <- function() inv ## create a list which holds get and set inverse functions list(setMatrix = setMatrix, getMatrix = getMatrix, setInverse = setInverse, getInverse = getInverse) } ## computes the inverse of the special "matrix" returned by makeCacheMatrix ## If the inverse has already been calculated and the matrix has not changed ## then the cachesolve will retrieve the inverse from the cache. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' ## Determine if the inverse has already been calculated and the matrix has not changed i <- x$getInverse() ## If the inverse has already been calculated returned cached value if(!is.null(i)){ message("getting cached data") return(i) } ## if the inverse has not been calculated, then do it with solve ## get the data data <- x$getMatrix() ## Use the solve function to return the inverse of the matrix i <- solve(data, ...) ## Use the set function to set new value of matrix x$setInverse(i) ## return the matrix's inverse i }